Skip to main content

A-share low-frequency quantitative trading framework covering research, backtesting, and execution (formerly prism_quant)

Project description

PrismQuant

中文 | English

Version Platform Python Tests License

Professional-Grade Python Open-Source Quantitative Trading Framework — covering the full "Research → Backtest → Live Trading" lifecycle, building an industrial-grade quantitative closed-loop workflow.

Strategy Signals Backtest Overview

🎓 Official Tutorials

iMOOC - AI Quantitative System Course

Official Course: Deeply deconstructing the framework's architecture from 0 to 1, covering live trading logic and industrial-grade quantitative development. An essential course for mastering PrismQuant.

📦 Installation

pip install prism_quant

Development environment (with TimescaleDB):

git clone https://gitee.com/beauty9235/prism_quant.git
cd prism_quant
docker compose up -d              # Start PostgreSQL + TimescaleDB
pip install -e .                   # Developer mode install

For previous version source code, visit: https://pypi.org/project/prism_quant/#history

✨ Key Features

Capability Description
📥 Multi-Source Data 3 data sources (tushare / tiingo / EastMoney), covering A-shares / US / HK / Funds
💾 Smart Caching TimescaleDB (PostgreSQL) + SQLite dual backend, incremental fetch with auto-persistence, millisecond cache hits
🛡️ Anti-Block Protection IPv4 enforcement + random delay + exponential backoff retry for free data source stability
🧠 Rapid Development Signal-driven architecture, BaseStrategy template, 10 lines for a complete strategy
📉 Professional Backtest High-performance matching engine, A-share price-limit/T+1 rules, share lot rounding, minimum commission, stop-loss/take-profit, OOS testing
📊 18 Professional Charts Monthly returns heatmap / Rolling Sharpe / Strategy comparison / Volatility cone / Position heatmap / Correlation matrix / Risk dashboard / QQ plot / Waterfall / Trade timeline, and more
Event-Driven Sub-second market data distribution, millisecond Tick signal processing, LiveEngine orchestration
🤖 Live Trading Gateways Pluggable adapters (PaperTrade simulation / miniQMT live), seamless switching

⚡ Quick Start

import prism_quant as prq

# 1. Define strategy logic
class MyStrategy(prq.strategy.BaseStrategy):
    def generate_signals(self, data):
        bands = prq.indicators.TechnicalIndicators().boll(data["Close"])
        return prq.strategy.SignalGenerator().boll_signals(data["Close"], bands)

# 2. Minimal backtest & results (auto-cached)
engine = prq.backtest.BacktestEngine()
engine.set_parameters("GOOGL", "2025-07-26", "2026-01-26")
engine.load_data()                         # First run: remote fetch → auto-save; next: instant cache read
engine.add_strategy(MyStrategy(name="BOLL"))
engine.run_backtest()
engine.show_report()
engine.show_chart(use_plotly=False)        # 5-panel performance chart
# 3. Professional chart analysis
from prism_quant.charts import ReturnsChart, PortfolioChart

# Monthly returns heatmap (essential for interviews/roadshows)
ReturnsChart().plot_monthly_heatmap(returns, use_plotly=True)

# Risk dashboard (VaR backtest + volatility + max drawdown)
PortfolioChart().plot_risk_dashboard(returns, equity, use_plotly=True)

🔌 Data Sources & Integrations

Type Integration Market Status
Data tushare A-shares/HK (premium quality, token required)
Data tiingo US stocks (free API key)
Data eastmoney OTC Funds (Stock/Bond/Mixed/QDII)
Data miniQMT A-share market data (requires XunTou client)
Trade PaperTrade Local simulation, Tick-driven matching
Trade miniQMT Trade A-share live trading

Minimal miniQMT live trade setup

from prism_quant.live import LiveEngine

engine = LiveEngine(symbol="000001.SZ", signal_interval="1m")
engine.set_data_gateway("miniqmt", interval=3.0, mode="poll")
engine.set_trade_gateway(
    "miniqmt",
    userdata_mini_path=r"D:\BrokerQMT\userdata_mini",
    account_id="1234567890",
)

See details:

  • documents/LiveEngine.md
  • documents/MiniQmtTrade.md
  • documents/MiniQmtLiveEngine.md

🏗️ Project Architecture

prism_quant/
├── core/                            # Base classes, config, logging
│   ├── base.py
│   ├── config.py
│   └── logger.py
├── data/                            # Fetch, clean, store
│   ├── fetcher.py                   # 3 sources + anti-block + auto-cache
│   ├── cleaner.py                   # Missing value handling (dropna / fillna)
│   ├── storage.py                   # CSV file storage
│   ├── database.py                  # SQLite database storage
│   ├── timescale.py                 # TimescaleDB (PostgreSQL) production storage
│   ├── source_map.py                # Gateway → source name mapping
│   └── miniqmt_xtdata.py            # miniQMT / xtquant historical bars
├── indicators/                      # Technical & fundamental factors
│   ├── technical.py                 # SMA/EMA/RSI/MACD/BOLL/ATR/OBV/CCI/ADX/KDJ
│   ├── fundamental.py               # PE/PB/ROE/Dividend Yield etc.
│   └── talib_indicators.py          # TA-Lib equivalent (performance benchmark)
├── strategy/                        # Strategy base & signal generation
│   ├── base.py                      # BaseStrategy template
│   └── signals.py                   # SignalGenerator (Bollinger/CCI/ADX etc.)
├── backtest/                        # Backtest engine & metrics
│   ├── engine.py                    # BacktestEngine (A-share T+1 / price limit / OOS)
│   ├── metrics.py                   # Alpha/Beta/Sharpe/Sortino/VaR/CVaR
│   ├── performance.py               # PerformanceReporter
│   └── optimizer.py                 # Grid search parameter optimizer
├── live/                            # Event engine & live orchestration
│   ├── event_engine.py              # Event loop & priority queue
│   ├── gateways.py                  # DataGateway / TradeGateway abstractions
│   ├── gateway_registry.py          # Gateway factory & registry
│   ├── engine.py                    # LiveEngine orchestration
│   └── models.py                    # TickData / OrderRequest etc.
├── adapters/                        # Pluggable data / trade adapters
│   ├── data/                        # Data gateways (yfinance / miniQMT)
│   └── trade/                       # Trade gateways (Paper / miniQMT)
├── trader/                          # Execution engine & order management
│   ├── engine.py                    # ExecutionEngine (slippage/commission/A-share rules)
│   ├── order_manager.py             # OrderManager (order lifecycle)
│   ├── position_manager.py          # PositionManager (position tracking & T+1 freeze)
│   └── market_rules.py              # MarketRules (A-share lots/stamp tax/price limit)
├── charts/                          # 🆕 18 professional quantitative charts
│   ├── base.py                      # BaseChart (create_figure / show / save)
│   ├── theme.py                     # ChartTheme (unified colors/fonts/dark mode)
│   ├── price.py                     # Price comparison (normalized / Plotly)
│   ├── performance.py               # 5-panel backtest performance (equity/drawdown/distribution)
│   ├── signals.py                   # Bollinger/MACD/RSI + candlestick (mplfinance)
│   ├── returns.py                   # 🆕 Monthly heatmap/rolling Sharpe/QQ/waterfall/dashboard
│   ├── comparison.py                # 🆕 Strategy comparison/param heatmap/volatility cone
│   └── portfolio.py                 # 🆕 Position heatmap/correlation/risk decomp./trade timeline
└── utils/                           # Utilities
    └── check_connectivity.py        # Data source connectivity checker

Infrastructure:

├── docker-compose.yml               # PostgreSQL + TimescaleDB one-click deploy
├── Dockerfile.sync                  # Daily data sync service image
├── scripts/
│   ├── sync_daily.py                # Incremental daily data sync script
│   ├── sync.crontab                 # Crontab schedule rules
│   ├── check_data_sources.sh        # Data source connectivity check
│   └── db-init/01-init.sql          # Schema + Hypertable + Compression policy
├── tests/                           # 102 pytest unit tests
├── examples/                        # 23 examples (data/backtest/charts/live/funds)
└── documents/                       # 8 technical documents

📊 Full Chart Catalog (18 Charts)

# Chart Module Matplotlib Plotly
1 Price Comparison (normalized) PriceChart
2 5-Panel Backtest Performance PerformanceChart
3 Bollinger Band Signals SignalChart
4 MACD Panel SignalChart
5 RSI Panel SignalChart
6 Monthly Returns Heatmap ReturnsChart
7 Rolling Sharpe Ratio ReturnsChart
8 Rolling Metrics Dashboard ReturnsChart
9 Q-Q Plot vs Normal ReturnsChart
10 P&L Waterfall ReturnsChart
11 Strategy Comparison ComparisonChart
12 Parameter Sensitivity Heatmap ComparisonChart
13 Volatility Cone ComparisonChart
14 Position Heatmap PortfolioChart
15 Correlation Matrix PortfolioChart
16 Risk Decomposition (Pie) PortfolioChart
17 Trade Timeline PortfolioChart
18 Risk Dashboard PortfolioChart

Full example: python examples/21_all_charts.py or python examples/21_all_charts.py --save

🤝 Contributing

  • Feedback: Bug reports and contributions are welcome via Issue or Pull Requests.
  • WeChat Official Account: Follow PrismQuant开源量化 for updates, strategies, and quantitative resources.

WeChat Official Account

📄 License

MIT License. See LICENSE for details.

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

prism_quant-1.0.6.tar.gz (194.5 kB view details)

Uploaded Source

Built Distribution

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

prism_quant-1.0.6-py3-none-any.whl (199.3 kB view details)

Uploaded Python 3

File details

Details for the file prism_quant-1.0.6.tar.gz.

File metadata

  • Download URL: prism_quant-1.0.6.tar.gz
  • Upload date:
  • Size: 194.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.20

File hashes

Hashes for prism_quant-1.0.6.tar.gz
Algorithm Hash digest
SHA256 7865b9a9db2f974137819da9538b8aa5531f422b615dfca5fbcc58695a86a94c
MD5 9709c06077518c45593ae9312a4e2f20
BLAKE2b-256 b2ea4b654c13f3ed9fe42608133c2a72fd19a3032638b1297969c03fd12e22d0

See more details on using hashes here.

File details

Details for the file prism_quant-1.0.6-py3-none-any.whl.

File metadata

  • Download URL: prism_quant-1.0.6-py3-none-any.whl
  • Upload date:
  • Size: 199.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.20

File hashes

Hashes for prism_quant-1.0.6-py3-none-any.whl
Algorithm Hash digest
SHA256 43ee1a23650748ec0a0e1358a615be732e93e6aa01b609dea6b23a0e128291d7
MD5 10e4051d649d69a3ac4fc85e87345868
BLAKE2b-256 e563e89c3354194a7133684cd018b3d4f107f94899bc87413a9082c1ff0c6e0e

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