Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SmartMoneyTracker

English | 简体中文

Follow the smart money: identify the full institutional capital cycle—from accumulation to distribution—through multidimensional market analysis.

Python Version License

📋 Overview

SmartMoneyTracker is a modular Python application that automatically scans and analyzes stocks across the Chinese A-share, US, and Hong Kong markets. It identifies signals throughout the full institutional capital cycle, from entry and accumulation to exit and distribution.

Institutional capital comes from mutual funds, pension funds, hedge funds, QFIIs, and high-net-worth investors. These participants follow different strategies, time horizons, and execution methods, leaving distinct footprints in the market. Identifying the complete cycle can help with:

  • Risk management — avoid buying into institutional distribution
  • Opportunity discovery — detect early signs of institutional accumulation
  • Tactical positioning — align positioning with institutional sentiment
  • Trend anticipation — identify potential trend breakouts and reversals

🎯 Key Features

Multidimensional Analysis

The system does not rely on a single indicator. Instead, it combines bidirectional signals from several independent areas of analysis:

  1. Price and volume

    • Accumulation: high-volume consolidation near a bottom, high-volume resistance breakouts, and Wyckoff accumulation patterns such as springs and last points of support (LPS)
    • Distribution: high-volume price stagnation near a top, high-volume support breakdowns, and low-volume rallies at elevated prices
  2. Technical indicators

    • Accumulation: bullish OBV/MFI divergence and oversold MFI readings below 20
    • Distribution: bearish OBV/MFI divergence and overbought MFI readings above 80
  3. Market microstructure extension ⚠️ Interface only; inactive without a commercial Level 2 feed

    • Extension interfaces are retained for a future licensed data provider
    • Full order-book analysis, static order imbalance ratio (SOIR), and execution-footprint detection are not on the current roadmap
    • The application does not produce Level 2 signals from the current free AkShare, Tushare, or yfinance data sources
  4. Ownership structure

    • Accumulation: new institutional shareholders and a declining shareholder count
    • Distribution: institutional selling and a rising shareholder count
    • Changes in shareholdings by directors and senior executives
  5. Relative strength

    • Accumulation: sustained RSP outperformance against a market or sector benchmark
    • Distribution: sustained RSP underperformance against a market or sector benchmark
    • Stock-to-sector comparisons and stock-to-market divergence detection

Bidirectional Scoring

  • Weighted aggregation across multiple signals
  • Composite directional score from -10 to +10:
    • +6 to +10: STRONG_BUY — strong accumulation signals
    • +2 to +5: BUY — moderate accumulation signals
    • -1 to +1: NEUTRAL — no clear direction
    • -5 to -2: SELL — moderate distribution signals
    • -10 to -6: STRONG_SELL — strong distribution signals
  • Human-readable analysis reports

AKQuant-Powered Indicator Engine

  • AKQuant provides the quantitative computation foundation
  • Rust-backed SMA, OBV, RSI, MACD, and MFI calculations by default
  • Configurable rust, python, or auto TA-Lib-compatible backend
  • The market-data layer remains independent because AKQuant is a strategy and backtesting framework, not a data provider

🏗️ Architecture

SmartMoneyTracker/
├── app.py                         # Web application
├── main.py                        # CLI and scanner entry point
├── config.py                      # Configuration
├── requirements.txt               # Python dependencies
├── Dockerfile
├── docker-compose.yml
│
├── data_fetcher/                  # Data access layer
│   ├── __init__.py
│   └── manager.py                 # Unified data API manager
│
├── analysis/                      # Signal analysis layer
│   ├── __init__.py
│   ├── price_volume_signals.py    # Accumulation and distribution signals
│   ├── indicator_signals.py       # Technical indicator signals
│   ├── disclosure_signals.py      # Ownership and disclosure signals
│   ├── microstructure_signals.py  # Inactive Level 2 extension interfaces
│   └── relative_strength.py       # Relative-strength signals
│
├── aggregator/                    # Signal aggregation layer
│   ├── __init__.py
│   └── scorer.py                  # Scoring and composite ratings
│
├── quant_engine/                  # Quantitative computation layer
│   ├── __init__.py
│   └── akquant_adapter.py         # AKQuant indicator adapter
│
├── backtesting/                   # Point-in-time backtesting layer
│   ├── __init__.py
│   ├── engine.py                  # AKQuant event-driven signal backtester
│   └── validation.py              # Rolling out-of-sample validation
│
├── disclosures/                   # Publication-time disclosure storage
├── monitoring/                    # End-of-day scheduling and alerts
├── backtest.py                    # Backtest and validation CLI
├── monitor.py                     # Scheduled-monitor CLI
├── snapshot_disclosures.py        # Point-in-time snapshot collector
│
├── reporting/                     # Reporting layer
│   ├── __init__.py
│   └── generator.py               # Text and HTML reports
│
├── static/                        # Web assets
├── templates/                     # Web templates
└── tests/                         # Test suite

🚀 Getting Started

Docker (Recommended) 🐳

Run the application without configuring a local Python environment:

git clone https://github.com/RTsien/SmartMoneyTracker.git
cd SmartMoneyTracker

docker-compose up -d

Open http://localhost:8001 in your browser.

For more information, see the Docker deployment guide (Chinese).

Local Installation

Requirements

  • Python 3.10 or later
  • pip

Installation

git clone https://github.com/RTsien/SmartMoneyTracker.git
cd SmartMoneyTracker

pip install -r requirements.txt

API credentials are optional. If you want to use Tushare, add your token in config.py or provide it through the supported environment configuration.

Usage

Web Interface 🌐

python app.py

Open http://localhost:8001 in your browser.

The web interface provides:

  • 🎨 A modern user interface
  • 📊 On-demand analysis results
  • 📈 Visual scores and signals
  • 🔄 Single-stock and batch analysis
  • 📱 A responsive layout for desktop and mobile devices
  • 📉 Interactive strategy, benchmark, drawdown, and signal-score charts

Command Line and Python API

Run a scan directly from the command line:

python3 main.py 600519.SH

Or use the scanner from Python:

from main import SmartMoneyScanner

scanner = SmartMoneyScanner()

# Scan one stock: Kweichow Moutai (A-share)
result = scanner.scan_stock("600519.SH")
if result["success"]:
    print(result["report"])

# Scan stocks across multiple markets
stocks = ["600519.SH", "AAPL", "0700.HK"]
results = scanner.scan_batch(stocks)

for ticker, result in results.items():
    if result["success"]:
        print(f"\n{ticker}:")
        print(f"Score: {result['score']:+.1f}/10")
        print(f"Rating: {result['rating']}")

Backtesting

Run the price-volume and technical-indicator strategy on historical data:

python3 backtest.py 600519.SH --period 1000 --warmup 120

The backtester uses AKQuant's event-driven engine. It evaluates signals only from bars available at each decision point and fills orders at the next bar's open. The report includes net return, buy-and-hold return, excess return, annualized return and volatility, Sharpe ratio, maximum drawdown, win rate, and trade count. Commission and slippage are enabled by default and configurable:

python3 backtest.py AAPL --commission-bps 10 --slippage-bps 5 --json

Price-volume and technical-indicator signals are included by default. Structural signals are opt-in and can only read disclosures captured in the point-in-time store, avoiding publication-date and survivorship bias.

Run rolling out-of-sample validation. Each fold selects its rebalance frequency using only its training window and evaluates it on the following unseen window:

python3 backtest.py 600519.SH --period 2000 --walk-forward \
  --train-bars 504 --test-bars 126 --step-bars 126 \
  --candidates 1,5,20

The sensitivity table compares every candidate on the same out-of-sample folds.

End-of-Day Monitoring and Point-in-Time Disclosures

# Capture disclosures with their publication timestamps
python3 snapshot_disclosures.py 600519.SH

# Include only disclosures already public at each historical decision
python3 backtest.py 600519.SH --include-structural

# Run all configured markets once, or keep the scheduler running
python3 monitor.py --once
python3 monitor.py

The scheduler uses separate A-share, Hong Kong, and US market times, suppresses duplicate alerts, writes JSONL locally, and optionally posts to a webhook.

Example Output

Distribution Signal

===== Smart Money Tracker Report =====
Ticker: 600519.SH
Date: 2025-10-13
Overall Score: -7/10 (SELL)

--- Outflow Signals Triggered ---
[-] HIGH_VOLUME_STAGNATION (Score: -2) on 2025-09-15
    Volume surged after a substantial rally, but price stopped advancing.

[-] MFI_BEARISH_DIVERGENCE (Score: -2)
    Price reached a new high while the Money Flow Index did not confirm it.

[-] INSTITUTIONAL_SELL_OFF (Score: -3)
    China Merchants Fund reduced its position by 5%.

[-] RSP_WEAK (Score: -1)
    The stock underperformed the CSI Liquor Index.

--- Inflow Signals Triggered ---
(None)

Recommendation:
The probability of institutional distribution is elevated. Exercise caution;
large holders may be selling into retail enthusiasm.

Accumulation Signal

===== Smart Money Tracker Report =====
Ticker: 000858.SZ
Date: 2025-10-13
Overall Score: +7/10 (BUY)

--- Inflow Signals Triggered ---
[+] ACCUMULATION_BREAKOUT (Score: +2) on 2025-10-10
    Price broke out of a long consolidation range on 2.5x average volume.

[+] OBV_BULLISH_DIVERGENCE (Score: +2)
    Price reached a new low while OBV held above its previous low.

[+] NEW_INSTITUTION (Score: +3)
    China Merchants Fund entered the top-ten shareholder list.

[+] SHAREHOLDER_COUNT_DECREASE (Score: +1)
    The shareholder count declined 15% quarter over quarter.

--- Outflow Signals Triggered ---
(None)

Recommendation:
The probability of institutional accumulation is high and the trend is bullish.
Shares may be moving from retail investors to institutions.

📊 Supported Markets

Market Data sources Highlights
Chinese A-shares AkShare (Tencent default, Eastmoney fallback), Tushare Northbound capital flows, top-ten shareholder analysis, and shareholder count analysis
US stocks AkShare (Sina), yfinance fallback Institutional ownership and daily market data
Hong Kong stocks AkShare (Sina), yfinance fallback Institutional ownership and Stock Connect holdings

📈 Data Sources

  • Daily market data
    • Chinese A-shares: AkShare via Tencent (default) or Eastmoney, with Tushare as a fallback
    • US and Hong Kong stocks: AkShare via Sina, with yfinance as a fallback
  • Level 2 data ⚠️ Not included; extension interfaces only
    • Potential providers: Eastmoney Choice, Wind, and similar vendors
    • Full microstructure analysis remains out of scope until a licensed provider is selected
    • The architecture only retains extension points for a compatible feed
  • Institutional holdings
    • Chinese A-shares: AkShare or Tushare (top10_holders, stk_holdernumber)
    • US stocks: yfinance
    • Hong Kong stocks: yfinance and AkShare
  • Capital flows
    • Northbound flows: AkShare or Tushare (hk_hold)
    • Southbound flows: Eastmoney API
  • Potential disclosure and news sources: CNInfo and official exchange websites; broader integration remains in the long-term backlog

🔧 Configuration

Configure the application in config.py:

# Data source
A_STOCK_DATA_SOURCE = "akshare"  # "akshare" (default) or "tushare"
AKSHARE_ENABLED = True
AKSHARE_HISTORY_SOURCE = "tencent"  # "tencent" (default) or "eastmoney"
TUSHARE_TOKEN = "your_token_here"  # Required only for Tushare

# Quantitative computation
QUANT_ENGINE = "akquant"             # "akquant" (default) or "native"
AKQUANT_TALIB_BACKEND = "rust"       # "rust", "python", or "auto"

# Stocks to scan
STOCK_POOL = [
    "600519.SH",  # Kweichow Moutai
    "AAPL",       # Apple
    "0700.HK",    # Tencent
]

# Bidirectional signal weights
SIGNAL_WEIGHTS = {
    # Accumulation signals (positive)
    "ACCUMULATION_BREAKOUT": 2,
    "OBV_BULLISH_DIVERGENCE": 2,
    "NEW_INSTITUTION": 3,
    "SHAREHOLDER_COUNT_DECREASE": 1,
    "RSP_STRONG": 1,

    # Distribution signals (negative)
    "HIGH_VOLUME_STAGNATION": -2,
    "OBV_BEARISH_DIVERGENCE": -2,
    "INSTITUTIONAL_SELL_OFF": -3,
    "BREAK_SUPPORT_HEAVY_VOLUME": -3,
    "RSP_WEAK": -1,
}

# Analysis parameters
LOOKBACK_PERIOD = 60
VOL_MULTIPLIER = 2.0

Switching the A-share Data Source

# AkShare: the default; no token required
python3 main.py 600519.SH

# Use the Eastmoney history endpoint instead of the Tencent default
AKSHARE_HISTORY_SOURCE=eastmoney python3 main.py 600519.SH

# Tushare: requires TUSHARE_TOKEN
A_STOCK_DATA_SOURCE=tushare python3 main.py 600519.SH

📚 Methodology

The project is based on a detailed smart-money analysis framework:

Core Principles

  1. Two sides of the same cycle: institutional accumulation and distribution form one complete capital cycle. Useful market insight comes from understanding the progression from position building through markup and, ultimately, exit.

  2. The capital-flow fallacy: many conventional “main capital flow” indicators measure trade aggressiveness rather than the actual movement of capital.

  3. Signal convergence: high-confidence conclusions require confirmation across independent dimensions. Any single indicator can be misleading.

  4. Signal sequencing: institutional activity tends to reveal itself in stages:

    • Market signals such as price-volume behavior and divergences usually appear first
    • Fundamental catalysts emerge later as confirmation
    • Official disclosures provide strong but delayed evidence
  5. Market-specific behavior: Chinese A-share, US, and Hong Kong markets differ in investor composition, trading rules, and disclosure regimes, so each requires a tailored analytical approach.

🛣️ Roadmap

Phase 1: Foundations ✅

  • Architecture design
  • Methodology documentation
  • Technical specification

Phase 2: Data Layer ✅

  • Unified data manager
  • AkShare integration as the default A-share source
  • Optional Tushare integration
  • yfinance integration for US and Hong Kong stocks
  • Intelligent data-source switching

Phase 3: Analysis Layer ✅

  • Price-volume signals
  • Technical indicator signals
  • Structural signals
  • Relative-strength analysis
  • Institutional ownership data for US and Hong Kong stocks

Phase 4: Aggregation and Reporting ✅

  • Risk-scoring system
  • Report generator
  • Backtest equity, benchmark, drawdown, and signal visualizations

Phase 5: Reliability and Expansion ✅

  • In-memory daily-data caching
  • Persistent TTL caching across processes
  • Bounded concurrent batch processing with provider-aware rate limiting
  • Scheduled end-of-day scans, duplicate suppression, and configurable alerts
  • Web interface
  • Unit tests
  • Point-in-time backtesting MVP with AKQuant next-open execution
  • Walk-forward validation and out-of-sample parameter-sensitivity reports
  • Publication-time disclosure storage for structural-signal backtests

Long-Term Backlog — No Delivery Date

  • SEC Form 13F institutional-holdings ingestion
  • HKEXnews disclosure ingestion for Hong Kong stocks
  • News and fundamental-catalyst analysis
  • A general persistent application database, introduced only when historical scores or richer scheduled-task state require it; the existing TTL cache and disclosure store remain purpose-specific

Explicitly Not on the Current Roadmap

  • Machine-learning integration: deferred until reliable labels and point-in-time backtests can demonstrate value without false precision
  • Strategy-optimization engine: excluded at the current stage because automated parameter search would create a high overfitting risk
  • Community-sharing platform: excluded because it does not support the project's core role as a focused analysis tool
  • Full Level 2 microstructure analysis: excluded until a licensed commercial data source is selected; only extension interfaces are retained
  • Tick-level real-time monitoring: replaced by scheduled end-of-day scans, which match the capabilities of the current daily-data stack

🧪 Testing

# Run the convenience script
./run_tests.sh

# Or run the test entry point directly
python3 tests/run_tests.py

# Run a specific test module
python3 -m unittest tests.test_app

See the testing guide (Chinese) for more details.

🤝 Contributing

Contributions are welcome:

  1. Fork the repository.
  2. Create a feature branch: git checkout -b feature/AmazingFeature.
  3. Commit your changes: git commit -m 'Add some AmazingFeature'.
  4. Run the test suite: ./run_tests.sh.
  5. Push the branch: git push origin feature/AmazingFeature.
  6. Open a pull request.

⚠️ Disclaimer

This project is intended for educational and research purposes only. It does not constitute investment advice.

  • Past performance does not guarantee future results.
  • Investing involves risk; make decisions carefully.
  • You are solely responsible for decisions made using this software.
  • Understand the meaning and limitations of each signal before relying on it.

📄 License

This project is licensed under the MIT License.

🙏 Acknowledgments

  • Thanks to the AKQuant, Tushare, AkShare, and other open-source communities.
  • The methodology draws on academic research and market practice.
  • Thanks to everyone who has contributed to the project.

📞 Links


⭐ If you find this project useful, please consider giving it a star.

The market is always telling a story. Smart-money footprints are hidden in price and volume, technical indicators, order-book activity, and ownership changes.

About

Track smart money with multidimensional analysis of institutional accumulation and distribution signals.

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages