Skip to main content

Event-driven quantitative trading framework for China A-share backtesting and research

Project description

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 backtestinginitializerun_dailyhandle_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

HTML Report (Interactive)

HTML Report — MACD+Volume

How to read reports: header summary → metric cards (Sharpe, max drawdown, alpha) → K-line chart with MA/RSI/MACD/Bollinger Bands → 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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

easyquant_eqlib-1.0.2.tar.gz (175.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

easyquant_eqlib-1.0.2-py3-none-any.whl (149.6 kB view details)

Uploaded Python 3

File details

Details for the file easyquant_eqlib-1.0.2.tar.gz.

File metadata

  • Download URL: easyquant_eqlib-1.0.2.tar.gz
  • Upload date:
  • Size: 175.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.12

File hashes

Hashes for easyquant_eqlib-1.0.2.tar.gz
Algorithm Hash digest
SHA256 bd0aef59bba7b151e0ab5cb846df6c0bd6b363fea47952eecf330d118ae3490c
MD5 ea4fbd944942489a04a61a98dcc5ff71
BLAKE2b-256 6d586ddae6838f3427689c184e01c55ff9b725bc07235a0ec771513f28a4f16c

See more details on using hashes here.

File details

Details for the file easyquant_eqlib-1.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for easyquant_eqlib-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 e49106c6caf26b94d9236ba7685d1e85770b13799236c79b21b02e6322603b58
MD5 249f87714ae978edf5488b9b4284f254
BLAKE2b-256 927955b12fbab5128b020483c0c989456e654f298203b57ff18a394a09eabf1c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page