Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

QKA — 快量化

Quant Kit for A-shares

PyPI Python License

简洁易用的 A 股量化回测框架。


安装

包安装

pip install qka

需要 Python 3.10+。

AI 技能安装

为 Claude Code、Cursor 等 AI 编程工具安装 QKA 技能:

npx skills add zsrl/qka

安装后,AI 助手即可自动加载 QKA 框架的 API 文档,生成符合规范的量化策略代码。

快速上手

数据

from qka import Data

data = Data(
    symbols=['000001.SZ', '600000.SH'],
    factors={
        'sma_5':  ('ta.trend.sma_indicator', 'close', 5),
        'rsi_14': ('ta.momentum.rsi', 'close', 14),
    },
)
df = data.get()  # 返回宽表 DataFrame,列名 {symbol}|{factor}

factors= 也可写作 indicators=(旧名,完全等价、保留兼容);两者只能传一个。

策略

from qka import Strategy

class MyStrategy(Strategy):
    def __init__(self):
        super().__init__()
        self.lookback = 20  # 自定义参数

    def on_bar(self, date):
        close = self.get('close')            # 当前横截面
        hist = self.history('close', 20)     # 历史窗口
        # 交易逻辑:self.broker.buy / self.broker.sell
        # 仓位计算:self.sizing.percent / self.sizing.fixed_shares

回测

from qka import Backtest

strategy = MyStrategy()
bt = Backtest(data, strategy)
bt.run(cash=200000, start_date='2024-01-01', benchmark='000300.SH')
print(bt.metrics['total_return_pct'])   # 总收益率
print(bt.metrics['sharpe_ratio'])        # 夏普比率

核心能力

  • 数据获取 — 写个股票代码就能取到本地,自动缓存、自动补齐最新数据,重复使用秒读
  • 多数据源 — 内置 tickflow、baostock、tdx 三个行情源,改一个 source= 即可切换,各源缓存分目录存放、互不干扰
  • 技术指标 — 均线、MACD、RSI、ATR 等 ta 库全部指标,外加 α/β、夏普、最大回撤等内置指标,声明一下即可,策略里不用自己 rolling
  • 估值字段 — 换手率、涨跌幅、停牌与 ST 标记、市盈率、市净率等,需要哪些就取哪些
  • 模拟行情 — 一条 Simulate 就能造出单边上涨、单边下跌、来回震荡的走势,不必等真实行情,用来验证策略是不是真在按逻辑交易
  • 多标的回测 — 一次传一篮子股票,self.get() 取当日横截面,self.history() 取历史窗口
  • 仓位管理 — 按资金比例、按金额、按股数、按 ATR 风险四种算法
  • 交易成本 — 佣金、印花税、滑点均已内置,也可自行调整
  • 绩效指标 — 总收益、年化、夏普、最大回撤、Calmar、胜率、盈亏比等 13 项,跑完即有
  • 回测报告 — 净值曲线、回撤曲线、月度收益热力图、逐笔交易明细,一键生成 HTML,浏览器直接打开
  • 基准对比 — 传入基准指数即可对比收益、计算 β / α

文档

框架 API 完整文档见 skills/qka/SKILL.md——所有类的方法签名、参数、返回值和约束都在里面。

完整示例

from qka import Data, Strategy, Backtest

data = Data(
    symbols=['000001.SZ'],
    factors={
        'sma_5':  ('ta.trend.sma_indicator', 'close', 5),
        'sma_20': ('ta.trend.sma_indicator', 'close', 20),
    },
)

class MaCross(Strategy):
    def __init__(self):
        super().__init__()
        self.pct = 0.2

    def on_bar(self, date):
        close = self.get('close')
        fast = self.get('sma_5')
        slow = self.get('sma_20')
        for sym in close.index:
            price = float(close[sym])
            if price <= 0:
                continue
            if fast[sym] > slow[sym]:
                size = self.sizing.percent(self.pct, price)
                if size > 0:
                    self.broker.buy(sym, price, size)
            else:
                pos = self.broker.positions.get(sym, {}).get('size', 0)
                if pos > 0:
                    self.broker.sell(sym, price, pos)

strategy = MaCross()
bt = Backtest(data, strategy)
bt.run(cash=200000, start_date='2024-01-01')
print(bt.metrics['total_return_pct'])

许可证

MIT

致谢

  • tickflow — 免费 A 股 / ETF / 可转债行情(默认数据源)
  • baostock — 免费 A 股数据(估值等扩展字段)
  • 通达信 — 本机「TQ 版」客户端的行情(source='tdx',仅 Windows)
  • ta — 技术指标库

⚠️ 量化交易存在风险,请充分了解后再使用本框架。

Metadata

Release files for qka 2.5.4.dev3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for qka 2.5.4.dev3
File Size Uploaded Provenance Actions
qka-2.5.4.dev3.tar.gz 95.3 kB Without provenance Details for qka-2.5.4.dev3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for qka 2.5.4.dev3
File Interpreter ABI Platform Actions
qka-2.5.4.dev3-py3-none-any.whl Python 3 none any Details for qka-2.5.4.dev3-py3-none-any.whl

Total release size: 196.9 kB

Release files / qka-2.5.4.dev3.tar.gz

Download URL qka-2.5.4.dev3.tar.gz
Size 95.3 kB
Tags Source
SHA-256 checksum
How to use checksums
10ed00c0c7766f630e240b3b2a26bf7b998abb4398f25712073c90b8b195b54f
BLAKE2b-256 checksum
How to use checksums
b73ce21875e02429ffab20a215ada2e173f80dbd5672e98fe80dc34db3aab7c4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / qka-2.5.4.dev3-py3-none-any.whl

Download URL qka-2.5.4.dev3-py3-none-any.whl
Size 101.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ddb53eb6ac1683134cf000d514aefe0507a050ba3d764def2dd5634140aa9c58
BLAKE2b-256 checksum
How to use checksums
a6825309d0edc9ec1a62bdfc1ea591c3f41036bcc1d99147e99174a2e48cc3c6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for qka 2.5.4.dev3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page