Skip to content

AlanFokCo/EasyQuant

Repository files navigation

EasyQuant logo

EasyQuant

Event-driven quantitative backtesting framework for China A-share market.

Tests Studio CI Docs Python License Version

δΈ­ζ–‡ζ–‡ζ‘£ Β· Docs Site Β· Tutorials Β· Doc Center Β· API Reference Β· Examples Β· FAQ


Features

  • Event-driven backtesting β€” initialize β†’ run_daily β†’ handle_data, compatible with JoinQuant / Zipline programming model
  • A-share data β€” daily OHLCV, minute K-lines, tick data, real-time quotes, fundamentals, money flow via free AKShare API
  • Position management β€” buy/sell by shares, value, or target; automatic lot-size rounding (100 shares), commission calculation
  • Risk analysis β€” Sharpe, Sortino, max drawdown, alpha/beta, Brinson attribution, Fama-French factor analysis
  • Portfolio optimization β€” minimum variance, maximum Sharpe, risk parity
  • Paper trading β€” run strategies live with real-time market data before going live
  • PTrade/QMT adapter β€” one-click export to broker platforms
  • Stock selection β€” periodic rebalancing with factor screening (ST/PB/PE/momentum filters, Top-N, multi-factor scoring)
  • Utility library β€” 30+ technical indicators (MA, MACD, RSI, KDJ, Bollinger, ATR, ADX), statistical tools, position sizing (Kelly, ATR-based, fixed fractional)
  • Reports β€” interactive HTML, chart PNG, Markdown, JSON with 20+ risk/return metrics
  • Chainable stock screening β€” fluent API (query / valuation / get_fundamentals) for fundamental analysis

Quick Start

pip install easyquant-eqlib   # or: pip install -e .  (from source)
python -c "from eqlib import *; print('eqlib OK')"
python examples/03_run_backtest.py

Open the generated .html report in reports/ in your browser.

Write Your First Strategy

from eqlib import *

def initialize(context):
    g.security = '601390'
    set_benchmark('000300.XSHG')
    run_daily(market_open, time='every_bar')

def market_open(context):
    hist = attribute_history(g.security, 20, '1d', ['close'])
    ma20 = hist['close'].mean()
    price = hist['close'].iloc[-1]

    if price > ma20 * 1.02:
        order_value(g.security, context.portfolio.available_cash)
    elif price < ma20 * 0.98 and context.portfolio.positions.get(g.security):
        order_target(g.security, 0)

result = run_strategy(
    initialize,
    start_date='2024-01-01',
    end_date='2024-12-31',
    starting_cash=100000,
    securities=['601390'],
)

Execution model: order* APIs queue orders in the current callback; they are filled at the next trading day's open to avoid look-ahead bias.

Output: 4 files in reports/ β€” .png chart, .html interactive report, .md summary, .json data.


Report Preview

run_strategy generates an interactive HTML report plus PNG, Markdown, and JSON. Below are snapshots from real backtest runs.

Profitable Strategies

MACD Trend + Volume (600536) Bollinger Mean Reversion (601088) Support/Resistance (8 stocks)
+103.48% Β· 16 trades +57.77% Β· 8 trades +119.97% Β· 171 trades
MACD Bollinger S/R

Losing Strategies (For Learning)

Momentum Portfolio (5 stocks) Local Data (000768)
βˆ’25.69% Β· 52 trades βˆ’33.28% Β· 16 trades
Portfolio Local

How to read reports: header summary β†’ metric cards (Sharpe, max drawdown, alpha) β†’ K-line chart β†’ cumulative returns vs benchmark β†’ drawdown curve β†’ daily P&L β†’ trade/position tabs. Full guide: Report & Metrics.


Project Structure

EasyQuant/
β”œβ”€β”€ eqlib/                 # Core library (backtest engine, data API, analysis)
β”œβ”€β”€ agent/                 # AI optimization utilities
β”‚   β”œβ”€β”€ optimizer.py       # Rule-based parameter search (reference)
β”‚   β”œβ”€β”€ audit_log.py       # Structured JSONL + Markdown audit logging
β”‚   └── strategy_template.py  # Parameterized strategy template
β”œβ”€β”€ examples/              # 24 runnable example scripts
β”œβ”€β”€ tutorials/             # Step-by-step learning tutorials
β”‚   └── prerequisites/     # Python, technical analysis, A-share basics
β”œβ”€β”€ doc/                   # User manual, API reference, FAQ
β”œβ”€β”€ docs/                  # GitHub Pages site source (MkDocs Material)
β”œβ”€β”€ tests/                 # Test suite
β”œβ”€β”€ assets/                # Brand assets (logo, icons)
β”œβ”€β”€ web_strategy_studio/   # Web Strategy Studio (FastAPI + React)
β”‚   β”œβ”€β”€ backend/           # FastAPI backend + Alembic migrations
β”‚   β”œβ”€β”€ frontend/          # React + Vite + TypeScript frontend
β”‚   β”œβ”€β”€ Dockerfile         # Multi-stage: frontend-builder β†’ api β†’ nginx
β”‚   β”œβ”€β”€ docker-compose.yml
β”‚   └── CONTRIBUTING.md    # Studio-specific contributor guide
β”œβ”€β”€ CLAUDE.md              # AI agent configuration & optimization workflow
└── mkdocs.yml             # Documentation site configuration

Examples

Full index at examples/Examples.md.

# File Description
01 01_fetch_data.py Data API: history, CSV, local loading, market scan
02 02_write_strategy.py Strategy templates (MA crossover, RSI, multi-stock)
03 03_run_backtest.py End-to-end backtest with reports
04 04_stock_screener.py Real-time stock screening
05 05_paper_trade.py Paper trading with live quotes
06 06_advanced_api.py Scheduling, portfolio optimization, attribution
07 07_market_data.py Financials, industry, index, minute, tick data
08 08_lifecycle_callbacks.py Lifecycle callbacks & stock pool management
09 09_attribution_analysis.py Brinson + Fama-French factor analysis
10 10_index_concept.py Index & concept board strategies
11 11_utils_library.py Full utility library demonstration
12 12_portfolio_backtest.py Multi-stock portfolio backtest
13 13_ptrade_export.py Export to PTrade/QMT platform
14–17 Strategies Bollinger, MACD+Volume, Multi-Factor, Grid Trading
18 18_strategy_comparison.py Side-by-side strategy comparison
19 19_local_data_backtest.py Local data mode (download once, offline backtest)
20 20_sr_strategy/ Support & Resistance portfolio (production case)
21 21_combined_strategy/ All-Weather Alpha comprehensive strategy
22 22_stock_selection_strategy.py Periodic stock selection with factor screening
23 23_small_cap_query_example.py Small-cap screening with chainable query API
24 24_quick_report_test.py Quick report format validation

Documentation

Resource Description
Docs Site Full documentation site with search, dark theme, navigation
Doc Center Entry point: user guide, API index, FAQ, report metrics
User Guide Install β†’ write strategy β†’ run backtest β†’ read reports
API Reference All public APIs with parameters and examples
Utils Reference Technical indicators, statistics, position sizing
Tutorials Zero to production, with real strategy cases
Report & Metrics Guide Field-by-field report walkthrough
FAQ Installation, data, performance, troubleshooting

Installation

PyPI (recommended for users)

pip install easyquant-eqlib
python -c "from eqlib import *; print('eqlib OK')"

From source (for contributors / editable install)

git clone https://github.com/AlanFokCo/EasyQuant.git
cd EasyQuant
pip install -e ".[dev]"
python -m pytest tests/

Requirements: Python 3.10+ Β· macOS / Linux / Windows


Performance

  • Memory-aware data loading β€” automatic memory limit (default 1 GB) with fallback to compact slicing; identical results, slightly slower
  • Fast I/O β€” in-memory attribute_history reduces 6+ year backtests from ~20 min to ~1 min
  • Parallel data loading β€” multi-threaded preload for faster startup

Contributing

We welcome contributions! Please read CONTRIBUTING.md for guidelines.

For contributions to the Web Strategy Studio, see web_strategy_studio/CONTRIBUTING.md.

Development Setup

pip install -e ".[dev,docs]"
python -m pytest tests/ -v

Studio β€” Quick Dev Start

cd web_strategy_studio
npm run install:all          # installs deps + builds symbol manifest
npm run dev:all              # API on :8080, frontend on :5173

Or with Docker:

cd web_strategy_studio
docker compose up --build    # full stack on http://localhost:8080

CI/CD

Pipeline Trigger Description
Tests Push / PR to main Runs eqlib test suite on Python 3.10, 3.11, 3.12
Studio Tests Push / PR to main (studio paths) Backend pytest + ruff/black + frontend typecheck/ESLint/vitest
Deploy Docs Push to main (docs paths) Builds and deploys MkDocs site to GitHub Pages

License

This project is licensed under the MIT License.


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

About

πŸ“Š EasyQuant - Event-driven quantitative trading framework for China A-share market. Backtest strategies, analyze risk metrics, and deploy with eqlib core library.

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors