项目 / fasiondog/hikyuu
An open-source, high-performance quantitative trading framework in C++/Python focused on strategy analysis and backtesting Trading model R&D · Ultra-fast engine · Efficient backtesting
本站整理,非 GitHub 官方 description。
官方快照(gh_history.db,2026-11-25):总榜 未进 Top50 · 日榜 未进 Top50 · 周榜未满 7 天基线(官方不生成) · 月榜暂无官方口径;下方四卡为站内趋势聚合(周卡按上榜次数,非官方 7 日增量窗)。
以下三段按该项目自己的 GitHub README 章节摘录(可合理截断并标明);README 没有对应章节的留空,不编造。
官方预编译包仅支持 Python 3.10 至 3.13,平台为 Windows、Linux(Ubuntu 24.04+)和 macOS,国内下载慢可用镜像。
框架按交易理论、交易规则和计算约定分层,策略需回答市场状态、条件、信号、仓位、退出与成交价,组合需回答选样、资金分配与评分。源文写明有三种组合运行模式,以及 HDF5、MySQL、ClickHouse、SQLite 四种存储方式。部件可独立替换,替换后仍按同一套结算与校验约定执行。项目首页见[hikyuu.org](https://hikyuu.org/)。
Hikyuu 官方安装包仅覆盖 Python 3.10 至 3.13,支持 Windows、Linux(需 Ubuntu 24.04 及以上)和 macOS 三个平台。
来自 GitHub 仓库 README / 主页介绍正文,正文较长,已截断:保留前 20000 字符(原始 37,343 字节),完整内容见 GitHub 仓库。
<p align="center">
<img src="docs/en/_static/00000-title.png" width="200" alt="title">
</p>
<p align="center">
An open-source quantitative research framework in C++/Python — a high-performance engine that puts financial and trading correctness first, with portfolios isomorphic to strategies, nestable to any depth, and freely replaceable components
</p>
<p align="center">
<img src="https://github.com/fasiondog/hikyuu/workflows/win-build/badge.svg" alt="Windows build">
<img src="https://github.com/fasiondog/hikyuu/workflows/ubuntu-build/badge.svg" alt="Ubuntu build">
<img src="https://img.shields.io/github/license/fasiondog/hikyuu.svg" alt="License">
<img src="https://static.pepy.tech/badge/hikyuu" alt="Downloads">
</p>
<p align="center">
<b>English</b> | <a href="readme.zh.md">简体中文</a>
</p>
**Hikyuu's kernel is the completeness and correctness of trading theory and financial semantics**: how a
trade should financially come into existence — when it fills, which items make up its cost, how positions
and cash change on ex-rights / ex-dividend dates, which convention performance follows, how nulls and
non-finite values propagate — is **complete and explicit** in the framework: no missing links, rules that
are actually executed, and results that can be verified item by item, rather than left to the user to
guarantee.
**Its purpose, in two sentences: never let a strategy that "runs" but does not hold up be taken as a
conclusion; and never let a full-market validation become waiting.**
* **Within controllable cost and performance constraints, speed is the core foundation for full-market,
multi-strategy research**: on an Orange Pi 5 Plus (an ARM single-board computer), a full `SYS_Simple` run
for each of the 3,547 currently valid non-index securities over the eleven years 2015–2026 — the EMA5
self-cross with its own EMA10 from `SG_Flex(EMA(C, 5), slow_n=10)` plus `MM_FixedCount(100)`, each on its
own ledger, on warm data and walking them in a single serial process — takes about 13 seconds.
* **Across the complete trade chain, the computation and rules of financial semantics are what safeguard
strategy correctness**: under arbitrarily complex strategy compositions, every link — fills, costs,
ex-rights adjustments and performance conventions — still runs by the real rules and is booked trade by
trade; no matter how deep the composition nests, the financial semantics of each trade are still upheld
as a whole.
Two means serve the first sentence: **splitting the structure along theoretical questions** — a strategy must
answer market environment, condition, signal, position sizing, exit and fill price; a portfolio must
answer who participates, how much money each gets and by what score — each is a theoretical must-answer
question, not an engineering module; and **portfolio as strategy** — making the portfolio a first-class
citizen (`SE` / `AF` / `MF`) is what lets the kernel extend from a single strategy to multi-asset,
multi-strategy. Every link can then be replaced and evaluated independently, and every trade is recorded
in a queryable ledger; the value of the framework is not exhaustive coverage, but **getting every slot
right and keeping the contract intact after replacement** (see "🏛️ Trading theory and financial
semantics" and "🧬 Portfolio as strategy" below); speed comes from the same C++ kernel — the same
ledger, the same guards, only without an interpreter in between.
> ⚠️ **Disclaimer**: This project is an open-source financial technology research tool. It is intended
> for personal study, academic research and data analysis only. It does not constitute any investment
> advice or trading guidance, and it does not provide or embed any securities trading service. The
> framework only offers generic interface extension capability; users are advised to connect only to
> compliant trading terminals provided by licensed institutions. Any trading interface, extension or
> actual operation added or developed by the user is entirely at the user's own risk and legal
> responsibility. Connecting to illegal trading channels or using the framework for non-compliant
> trading scenarios is strictly prohibited.
---
## 📊 Key Metrics
<p align="center">
<table>
<tr>
<td align="center" width="25%">
<strong><code>⚡ 6s / 166ms</code></strong><br>
<sub>Loading 19.13M daily bars + summing the 20-day MA: first run / after warm-up (AMD 7950x, <a href="https://mp.weixin.qq.com/s?__biz=MzkwMzY1NzYxMA==&mid=2247483768&idx=1&sn=33e40aa9633857fa7b4c7ded51c95ae7">benchmark details</a>)</sub>
</td>
<td align="center" width="25%">
<strong><code>🏛️ 3 layers</code></strong><br>
<sub>Built-in financial semantics (trading theory / trading rules / calculation)</sub>
</td>
<td align="center" width="25%">
<strong><code>🧬 3 modes</code></strong><br>
<sub>Portfolio run modes (A signal aggregation / B fund allocation / C shared account)</sub>
</td>
<td align="center" width="25%">
<strong><code>💾 4 types</code></strong><br>
<sub>Storage backends (HDF5 / MySQL / ClickHouse / SQLite)</sub>
</td>
</tr>
</table>
</p>
---
## 🔗 Quick Links
| Item | Link |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 🏠 **Project home page** | [https://hikyuu.org/](https://hikyuu.org/) |
| 📚 **Documentation** | [https://hikyuu-en.readthedocs.io/en/latest/](https://hikyuu-en.readthedocs.io/en/latest/) |
| 🚀 **Getting started** | [Jupyter Notebook tutorial series](https://nbviewer.org/github/fasiondog/hikyuu/blob/master/hikyuu/examples/notebook/en/000-Index.ipynb?flush_cache=True) |
| 🧰 **Strategy part library** | [https://gitee.com/fasiondog/hikyuu_hub](https://gitee.com/fasiondog/hikyuu_hub) |
---
## 🧭 Before you start: what it is, and what it is not
> **It is not an automated trading tool, nor an order execution system**: it does not embed broker
> connectivity, promise automatic order placement, or do tick-level matching or low-latency execution;
> `OrderBroker` is merely a pluggable interface — whether to connect one, and to which channel, is your
> decision and your compliance responsibility. It advances bar by bar and executes the financial semantics
> of a trade in full according to real rules; the decisions remain yours. Matching microstructure (partial
> fills, cancellations, order queues) and modern portfolio optimization (mean-variance, risk parity) are
> no exception: the framework does not pick such algorithms for you, but it keeps the slots ready —
> matching plugs in via `OrderBroker` and fill models; portfolio optimization takes an `AF` subclass, and
> the same applies to `SE` / `MF` / `MM` / `ST`. **The point of the framework is not to write all the
> algorithms, but to keep every slot right: each slot is replaceable, and settlement and validation still
> hold after replacement.**
**The barrier is kept on purpose**: the framework will not use a pretty curve to make up for the premises
you never thought of. You have to understand these links yourself — otherwise all you get is the illusion
of something that runs.
From another angle, it works more like a map: it lists item by item what building a strategy should take
into account (environment → condition → signal → sizing → exit → slippage → cost; portfolio layer:
selection → fund allocation → risk control). Fill it in item by item and the path itself is the way in.
**It suits people who want to study systematic trading seriously** — self-learners and students included —
not those who want a return curve in two days.
> "If you don't bet, you can't win. If you lose all your chips, you can't bet." — Larry Hite
A few words for beginners and self-learners:
- **Get the flow running first; talk about returns later**: a backtest return is not proof of ability —
being able to explain why every trade filled is.
- **Change one part at a time**: keep the other links fixed as a control, or you cannot tell where a
change in results came from.
- **Get costs and equity adjustments right before tuning parameters**: parameters "optimized" without
cost constraints are usually just fitting noise.
- **Care about "in what environment it fails"**: that is more useful than "how much it made
historically"; test with out-of-sample and walk-forward validation (`SYS_WalkForward`) instead of
re-tuning on the same window.
- **Be careful with what is off by default**: leverage and short selling are deliberately disabled by
default; understand margin, forced liquidation and borrow costs before turning them on explicitly.
---
## ⚡ Quick Start (run your first backtest)
### Requirements
- **Python 3.10+** (official packages are built for Python 3.10 – 3.13 only)
- Windows / Linux / macOS (Linux: Ubuntu 24.04+)
### Step 1: Install
```bash
pip install hikyuu
```
If the download is slow (for users in China), use a mirror:
```bash
pip install hikyuu -i https://pypi.tuna.tsinghua.edu.cn/simple
```
### Step 2: Import market data
Import historical A-share market data with either method:
```bash
# Graphical interface (recommended for first use; it generates the configuration file)
HikyuuTDX
# Command line (requires having run HikyuuTDX once to generate the configuration)
importdata
```
> ℹ️ **Data coverage**: HikyuuTDX downloads **China A-share** historical data only and needs a one-time
> initial configuration in the GUI. Overseas markets (US stocks, etc.) are not available yet and will be
> supported gradually.
### Step 3: Run your first backtest
```python
from hikyuu.interactive import *
# Create a simulated trading account for backtesting, with initial capital of 300,000
my_tm = crtTM(init_cash=300000)
# Create a signal generator (fast line: 5-day EMA; slow line: 10-day EMA)
# Buy when the fast line crosses above the slow line, sell otherwise
my_sg = SG_Flex(EMA(CLOSE(), n=5), slow_n=10)
# Buy a fixed 1000 shares each time
my_mm = MM_FixedCount(1000)
# Create the trading system and run it
sys = SYS_Simple(tm=my_tm, sg=my_sg, mm=my_mm)
sys.run(sm['sz000001'], Query(-150))
```
<p align="center">
<img src="docs/en/_static/10000-overview.png" alt="Backtest result" width="900">
</p>
> 📖 See the [Jupyter Notebook tutorial series](https://nbviewer.org/github/fasiondog/hikyuu/blob/master/hikyuu/examples/notebook/en/000-Index.ipynb?flush_cache=True)
> for the complete example.
>
> Once a single system works, the next step is combining several strategies into one portfolio: see
> "🧬 Portfolio as strategy" below.
---
## 🏛️ Trading theory and financial semantics: complete and correct
> Three layers, each owning one thing — miss one and it does not hold: **trading theory** — no missing
> link; without the portfolio layer, multiple strategies are just parallel backtests. **trading rules** —
> the rules must be right; without equity adjustments and itemized costs, ex-rights days and cross-year
> returns are distorted, and without filling-time constraints, a signal filled on its own bar is
> look-ahead. **calculation** — null semantics must be consistent; left to each indicator, one `inf`
> pollutes every downstream window aggregation. All three are explicit objects and global conventions in
> the framework — enforced by the framework and guarded at the entry points, not by a reminder in the
> docs.
| Layer | What it answers |
| :------------- | :---------------------------------------------------------------------------------- |
| Trading theory | Which parts make up a strategy; which layers organize a portfolio |
| Trading rules | How a trade fills, pays fees, adjusts for equity events and is priced in the market |
| Calculation | How nulls and numbers stay consistent along the whole computation chain |
**Trading theory**: the split follows theoretical structure, not code responsibilities — a strategy must
answer market environment (`EV`), condition (`CN`), signal (`SG`), position sizing (`MM`), exit (`ST` /
`TP` / `PG`) and fill price (`SP`); a portfolio must answer who participates (`SE`), how much money each
gets (`AF`: L1 weights / L2 conversion / L3 risk control) and by what score (`MF`). Each is a theoretical
must-answer question; miss one and the strategy is incomplete.
**Trading rules**: fills are delayed to the next bar's open by default (`buy_delay` / `sell_delay`); a
one-price board (high == low) or a trading suspension defers the fill, and it is abandoned beyond
`max_delay_count`; the slippage price is clamped to the day's `[low, high]`. Costs are itemized per
`CostRecord` (commission / stamp duty / transfer fee) and computed separately for buys and sells;
`updateWithWeight` adjusts positions and cash on ex-rights / ex-dividend events; margin financing and
securities lending are off by default; performance is annualized on net assets and calendar days
(`duration / 365`).
**Calculation**: undefined states (division by zero / zero variance / all-missing / zero benchmark)
produce `Null` (NaN), not `0.0` or `inf` — `0.0` collides with a legitimate zero and `inf` pollutes
downstream aggregation; aggregations accumulate only finite values and count only valid entries in the
denominator (one for a mean, two for dispersion), producing `Null` only when everything is missing;
serialization stores IEEE bit patterns, so NaN / ±Inf / signed zero round-trip losslessly. Trading inputs
are constrained the same way: a non-finite or non-positive size, or a non-positive fill price, is
discarded; a negative rebalance cycle raises immediately. Nulls and finite values are a **global contract
rather than a per-part choice** — new parts inherit the same convention automatically.
These three layers are not documentation promises: 1,300+ explicit guards in the core code catch rule and
input-boundary violations; 1,600+ doctest cases with 16,000+ assertions are organized "one suite per
module, one case per boundary", covering empty inputs, `Null<T>()`, non-finite values and out-of-range
exceptions; `small-test` runs on the three-platform CI without real market data.
> To bypass these rules you can only change parameters explicitly — **the framework takes the side of
> "holding up as a trade" rather than "being the least trouble to run"**. This is also a common reason
> why the same strategy shows different returns across frameworks: whatever is left unmodeled depends on
> the user remembering to make it up.
> The trade-off has a cost: the same strategy usually shows lower returns than an idealized backtest —
> fees deducted, fills waited for, equity events adjusted. Better an ugly backtest number than letting a
> runnable-but-wrong result pass as a usable strategy.
---
## 🧬 Portfolio as strategy: one engine covering systematic trading / asset allocation / multi-factor
**A portfolio and a strategy are the same thing**: a portfolio node is not "a set of weights" — it holds
a full set of trading semantics of its own. The sub-systems' `EV` / `CN` / `SG` / `MM` / `ST` / `TP` /
`PG` / `SP` decide *how to trade*; the ledger (`TM`) records fills and positions trade by trade, computes
costs item by item (commission / stamp duty / transfer fee) and adjusts for equity events; the execution
layer handles next-bar fills, retries on failure and trading suspensions — these three layers still hold
on the portfolio node, merged into a single account only at the outermost level.
The portfolio layer therefore answers only the two questions a portfolio should answer: **who
participates** (`SE` selection, `MF` multi-factor scoring) and **how much money each gets** (`AF`: L1
weights / L2 conversion / L3 portfolio risk control).
This is not a naming refinement but three directly usable consequences:
- **A node is a complete trading system, not a money-allocation slot** — a single system, a walk-forward
system, a custom Python system, or a portfolio itself can all be attached as a node of a parent
portfolio, with no adapter layer; there is no depth limit (duplicate additions and circular references
are rejected).
- **Financial semantics sit on every node** — stop-loss, itemized costs, equity adjustments and delayed
fills in a sub-system keep working unchanged after joining a portfolio; they are merged into a single
account only at the outermost level.
- **The three layers of `AF` are independently replaceable (mode A)** — swapping the weight source
(`AF_EqualWeight` / `AF_FixedWeightList` / `AF_MultiFactor`) does not touch L3 risk control, and
changing L3 does not touch the L1 weights; mode B allocates quotas with sub-manager autonomy and skips
the L3 clipping. See "🏗️ Core parts of the systematic trading architecture" below for the full list.
```python
from hikyuu.interactive import *
# 1. Each sub-system is a complete systematic trading system: its own SG / MM / ST and ledger
def make_leaf(code, sg):
sys = SYS_Simple(tm=crtTM(init_cash=100000), sg=sg,
mm=MM_FixedPercent(0.5), st=ST_FixedPercent(0.05))
sys.to = sm[code].get_kdata(Query(-500)) # bind its own K-line
return sys
trend = make_leaf("sh600000", SG_Cross(EMA(CLOSE(), n=5), MA(CLOSE(), n=60)))
grid = make_leaf("sh600004", SG_Cross(EMA(CLOSE(), n=3), MA(CLOSE(), n=10)))
# 2. The portfolio factory does only what a portfolio should do: who participates (SE) + how much
# money each gets (AF)
group = PF_SignalAggregate(tm=crtTM(Datetime(202001010000), 300000), adjust_cycle=5)
group.add(trend)
group.add(grid)
# 3. This portfolio can itself participate as a node of a larger portfolio (layer-by-layer aggregation
# across instruments and strategies)
top = PF_Simple(tm=crtTM(Datetime(202001010000), 1000000),
af=AF_FixedWeightList([0.6, 0.4]), adjust_cycle=5)
top.add(group)
top.add(make_leaf("sh600005", SG_Cross(EMA(CLOSE(), n=10), MA(CLOSE(), n=30))))
# 4. One run: the whole portfolio settles in a single account
top.run(Query(-500))
print(top.tm.get_funds().total_assets)
```
The same engine supports three portfolio run modes, each with its own factory (an existing portfolio can
also switch explicitly via `set_mode`):
| Factory | Account topology and money flow | Methodology | Typical scenarios |
| :---------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------- |
| `PF_SignalAggregate` (mode A) | Sub-systems run on fixed shadow accounts purely as signal sources; the parent converts their intents into execution orders through the AF's L2 conversion, applies L3 portfolio risk control and orders uniformly | Signal / view aggregation and portf