Metadata-Version: 2.4
Name: prism_quant
Version: 1.0.6
Summary: A-share low-frequency quantitative trading framework covering research, backtesting, and execution (formerly prism_quant)
Author-email: PrismQuant <21429503@qq.com>
License: MIT
Project-URL: Homepage, https://gitee.com/beauty9235/prism_quant
Project-URL: Repository, https://gitee.com/beauty9235/prism_quant
Project-URL: Issues, https://gitee.com/beauty9235/prism_quant/issues
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.21.0
Requires-Dist: pandas>=1.3.0
Requires-Dist: scipy>=1.7.0
Requires-Dist: matplotlib>=3.4.0
Requires-Dist: requests>=2.25.0
Requires-Dist: plotly>=5.0.0
Provides-Extra: viz
Requires-Dist: plotly>=5.0.0; extra == "viz"
Provides-Extra: talib
Requires-Dist: TA-Lib>=0.4.24; extra == "talib"
Provides-Extra: dev
Requires-Dist: black>=21.0.0; extra == "dev"
Requires-Dist: flake8>=3.9.0; extra == "dev"
Requires-Dist: sphinx>=4.0.0; extra == "dev"
Requires-Dist: pytest>=7.0.0; extra == "dev"
Dynamic: license-file

# PrismQuant

<div align="center">

[中文](README.md) | [English](README_EN.md)

![Version](https://img.shields.io/badge/version-1.1.0-7C3AED.svg)
![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-D97706.svg)
![Python](https://img.shields.io/badge/python-3.9%20%7C%203.10%20%7C%203.11%20%7C%203.12-2563EB.svg)
![Tests](https://img.shields.io/badge/tests-102%20passed-10B981.svg)
![License](https://img.shields.io/badge/license-MIT-10B981.svg)

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

<p align="center">
  <img src="https://gitee.com/beauty9235/prism_quant/raw/main/assets/signals.png" width="48%" alt="Strategy Signals" />
  <img src="https://gitee.com/beauty9235/prism_quant/raw/main/assets/overview.png" width="48%" alt="Backtest Overview" />
</p>

</div>


## 🎓 Official Tutorials

#### [iMOOC - AI Quantitative System Course](https://class.imooc.com/sale/aiqwm)

> 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

```bash
pip install prism_quant
```

Development environment (with TimescaleDB):
```bash
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

```python
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
```

```python
# 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

```python
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](https://gitee.com/beauty9235/prism_quant/issues) or Pull Requests.
- WeChat Official Account: Follow `PrismQuant开源量化` for updates, strategies, and quantitative resources.

<p align="center">
  <img src="https://gitee.com/beauty9235/prism_quant/raw/main/assets/wechat_qr.png" width="150" alt="WeChat Official Account" />
</p>


## 📄 License

MIT License. See [LICENSE](LICENSE) for details.
