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

# PyPI install (recommended for users)
pip install easyquant-eqlib

# Or install from source (for contributors)
git clone https://github.com/AlanFokCo/EasyQuant.git
cd EasyQuant
pip install .

Verify installation and run your first backtest:

python -c "from eqlib import *; print('eqlib OK')"
python examples/03_run_backtest.py  # run in repo directory

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

New to Python? If you prefer a browser-based interface, check out Web Strategy Studio — write strategies, run backtests, and view reports without installing any Python environment. See Web Studio Docs for details.

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
Web Studio Browser-based strategy development (no Python install needed)
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.3.tar.gz (184.6 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.3-py3-none-any.whl (152.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: easyquant_eqlib-1.0.3.tar.gz
  • Upload date:
  • Size: 184.6 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.3.tar.gz
Algorithm Hash digest
SHA256 86d4d3293d333b1a663c3d51b969fdb3347bd213e09d83ff01cc4aecb3873923
MD5 00d3107458bac56d2141f82d3758a3f8
BLAKE2b-256 17b502ebeed7554b68c0698674c97b2b0cca52c0ac3a44676f0251e108177512

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for easyquant_eqlib-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 4a3928d95969cf0109f1ed6bf9de0cb18af41de927b8615d9295ca448cd62402
MD5 ed085caff722fc8b6e01b66ed7744fe0
BLAKE2b-256 abef78d36d577a724211baeaf57afa6435ff832a8099ab177f042c7bf0ae49e3

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