
akquant
生成 akquant 框架的可执行量化策略代码,涵盖数据接口、事件驱动、风控与优化。当用户需要开发量化策略、配置回测环境、设置风控规则、进行参数优化、实现横截面轮动策略,或提及 akquant 时使用
- Installs
- 205
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/lzwme/finance-quant-skills --skill akquant- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads akquant automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
AKQuant 量化策略开发指南
任务目标
本 Skill 用于辅助 AI 编程智能体生成符合 akquant 框架规范的可执行量化策略代码。能力包括策略设计、回测配置、订单管理、风控规则、参数优化与横截面策略实现。
核心能力清单
- 策略类生成:继承 Strategy 基类,实现生命周期钩子
- 数据接口配置:准备 DataFrame 数据、设置预热期、访问历史数据
- 事件驱动机制:on_bar/on_tick/on_order/on_trade 等回调
- 订单管理:市价单/限价单/目标仓位/OCO/Bracket/Trailing Stop
- 风控规则:持仓限制/回撤熔断/止损阈值/行业集中度
- 参数优化:网格搜索与滚动优化(Walk-Forward)
- 多策略编排:slot 映射与策略级风控
触发条件
当用户表达以下意图时触发:
- 开发量化交易策略
- 配置回测环境与参数
- 设置风险控制规则
- 进行参数优化与调优
- 实现横截面或轮动策略
- 排查策略运行错误
策略开发工作流
阶段一:理解需求
- 识别策略类型:趋势跟踪、均值回归、横截面轮动、套利等
- 确定数据需求:时间周期、标的范围、字段要求
- 明确风控约束:持仓上限、止损止盈、回撤限制
阶段二:设计策略结构
参考 strategy-patterns.md 选择范式:
- 类风格(推荐):继承 Strategy,封装状态与逻辑
- 函数风格:initialize + on_bar,快速原型
关键决策点:
- 预热期设置:根据指标窗口长度计算
- 历史数据访问:get_history (numpy) 或 get_history_df (DataFrame)
- 执行模式:NextOpen(下一 Bar 开盘)或 CurrentClose(当前 Bar 收盘)
阶段三:编写策略代码
使用 assets/strategy-template.py 作为起点:
from akquant import Strategy, Bar
class MyStrategy(Strategy):
warmup_period = 20 # 预热数据长度
def __init__(self, param1=10):
self.param1 = param1
def on_start(self):
self.subscribe("600000")
def on_bar(self, bar: Bar):
# 核心交易逻辑
history = self.get_history(self.param1, bar.symbol, "close")
if len(history) < self.param1:
return
import numpy as np
ma = np.mean(history)
pos = self.get_position(bar.symbol)
if bar.close > ma and pos == 0:
self.buy(bar.symbol, 100)
elif bar.close < ma and pos > 0:
self.sell(bar.symbol, 100)
阶段四:配置回测环境
参考 api-reference.md 设置参数:
from akquant import run_backtest
result = run_backtest(
strategy=MyStrategy,
data=df,
symbol="600000",
initial_cash=500_000.0,
commission_rate=0.0003,
stamp_tax_rate=0.001,
t_plus_one=True, # A 股 T+1 规则
warmup_period=20,
execution_mode="NextOpen",
)
阶段五:设置风控规则
参考 risk-management.md 配置:
from akquant.config import RiskConfig
result = run_backtest(
...,
risk_config=RiskConfig(
max_position_pct=0.10, # 单标的持仓不超过 10%
max_account_drawdown=0.20, # 最大回撤 20%
max_daily_loss=0.05, # 单日亏损 5%
),
)
阶段六:参数优化
参考 optimization.md 执行:
from akquant import run_grid_search, run_walk_forward
# 网格搜索
results = run_grid_search(
strategy=MyStrategy,
param_grid={"param1": [10, 20, 30]},
data=df,
sort_by="sharpe_ratio",
)
# 滚动优化(推荐)
wfo_results = run_walk_forward(
strategy=MyStrategy,
param_grid={"param1": [10, 20, 30]},
data=df,
train_period=250,
test_period=60,
metric="sharpe_ratio",
)
横截面策略开发
参考 cross-section-guide.md 实现多标的轮动:
推荐范式:使用 on_timer 统一触发调仓
class CrossSectionStrategy(Strategy):
def __init__(self):
self.universe = ["sh600519", "sz000858", "sh601318"]
def on_start(self):
self.add_daily_timer("14:55:00", "rebalance")
def on_timer(self, payload):
if payload != "rebalance":
return
# 计算所有标分数
scores = {}
for symbol in self.universe:
history = self.get_history(20, symbol, "close")
scores[symbol] = (history[-1] - history[0]) / history[0]
# 选出最佳标的并调仓
best = max(scores, key=scores.get)
self.order_target_percent(0.95, symbol=best)
资源索引
| 资源 | 用途 | 何时读取 |
|---|---|---|
| api-reference.md | API 速查 | 查询函数签名与参数 |
| strategy-patterns.md | 策略范式 | 设计策略结构 |
| risk-management.md | 风控配置 | 设置风控规则 |
| optimization.md | 参数优化 | 调优策略参数 |
| cross-section-guide.md | 横截面策略 | 实现多标的轮动 |
| strategy-template.py | 策略模板 | 快速生成代码骨架 |
环境准备与依赖管理
使用 uv 管理项目环境(推荐)
由于 akquant 依赖 pandas>=3.0.0,全局安装可能与现有项目存在版本冲突。推荐使用 uv 创建隔离环境:
1. 安装 uv:若已安装则跳过
# macOS
brew install uv
# Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# Windows (PowerShell)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
2. 创建项目并初始化环境
# 创建项目目录
mkdir my-quant-strategy
cd my-quant-strategy
# 初始化项目(创建 pyproject.toml)
uv init
# 创建虚拟环境并安装依赖
uv venv
uv add akquant pandas numpy
3. 运行策略脚本
# 方式一:使用 uv run(推荐)
uv run python my_strategy.py
# 方式二:激活虚拟环境后运行
source .venv/bin/activate # macOS/Linux
# .venv\Scripts\activate # Windows
python my_strategy.py
4. 依赖版本锁定
uv 会自动生成 uv.lock 文件,确保团队依赖一致:
# 安装精确版本(从 lock 文件)
uv sync
# 添加新依赖
uv add scipy # 自动更新 lock 文件
5. 项目结构建议
my-quant-strategy/
├── .venv/ # 虚拟环境(uv 自动创建)
├── pyproject.toml # 项目配置
├── uv.lock # 依赖锁定文件
├── strategies/ # 策略脚本
│ ├── ma_strategy.py
│ └── cross_section.py
└── data/ # 数据文件
└── stock_data.csv
快速启动命令
# 一键创建并运行策略项目
mkdir quant-project && cd quant-project
uv init
uv venv
uv add akquant pandas numpy
# 创建策略文件(使用模板)
cat > strategy.py << 'EOF'
from akquant import Strategy, Bar, run_backtest
import pandas as pd
import numpy as np
class MyStrategy(Strategy):
warmup_period = 20
def on_bar(self, bar: Bar):
closes = self.get_history(20, bar.symbol, "close")
if len(closes) < 20:
return
ma = np.mean(closes)
pos = self.get_position(bar.symbol)
if bar.close > ma and pos == 0:
self.buy(bar.symbol, 100)
elif bar.close < ma and pos > 0:
self.sell(bar.symbol, pos)
# 准备数据并运行回测
# result = run_backtest(strategy=MyStrategy, data=df, symbol="600000")
EOF
# 运行策略
uv run python strategy.py
注意事项
- 预热期计算:确保 warmup_period >= 指标所需的最大窗口长度
- T+1 规则:A 股策略需设置 t_plus_one=True,并区分总持仓与可用持仓
- 风控优先级:显式参数 > 配置对象 > 默认值
- 数据格式:DataFrame 必须包含 date/open/high/low/close/volume/symbol 字段
- 横截面触发:优先使用 on_timer,无固定时点再考虑 timestamp 收齐方案
- 优化风险:网格搜索易过拟合,推荐使用滚动优化验证稳健性
使用示例
示例 1:双均线策略
from akquant import Strategy, Bar
import numpy as np
class DualMAStrategy(Strategy):
warmup_period = 30
def __init__(self, fast=10, slow=20):
self.fast = fast
self.slow = slow
self.warmup_period = slow + 1
def on_bar(self, bar: Bar):
fast_ma = np.mean(self.get_history(self.fast, bar.symbol, "close"))
slow_ma = np.mean(self.get_history(self.slow, bar.symbol, "close"))
pos = self.get_position(bar.symbol)
if fast_ma > slow_ma and pos == 0:
self.buy(bar.symbol, 100)
elif fast_ma < slow_ma and pos > 0:
self.sell(bar.symbol, pos)
示例 2:带风控的趋势策略
from akquant import Strategy, Bar, run_backtest
from akquant.config import RiskConfig
import numpy as np
class TrendStrategy(Strategy):
warmup_period = 20
def __init__(self, ma_window=20, stop_loss=0.05):
self.ma_window = ma_window
self.stop_loss = stop_loss
def on_bar(self, bar: Bar):
ma = np.mean(self.get_history(self.ma_window, bar.symbol, "close"))
pos = self.get_position(bar.symbol)
if bar.close > ma * 1.02 and pos == 0:
self.buy(bar.symbol, 100)
elif bar.close < ma * 0.98 and pos > 0:
self.sell(bar.symbol, pos)
# 运行回测
result = run_backtest(
strategy=TrendStrategy,
data=df,
symbol="600000",
initial_cash=1_000_000.0,
risk_config=RiskConfig(
max_position_pct=0.20,
max_account_drawdown=0.15,
stop_loss_threshold=0.85,
),
)
示例 3:横截面动量轮动
from akquant import Strategy, run_backtest
import numpy as np
class MomentumRotation(Strategy):
def __init__(self, lookback=20):
self.lookback = lookback
self.universe = ["sh600519", "sz000858", "sh601318"]
self.warmup_period = lookback + 1
def on_start(self):
for symbol in self.universe:
self.subscribe(symbol)
self.add_daily_timer("14:55:00", "rebalance")
def on_timer(self, payload):
if payload != "rebalance":
return
scores = {}
for symbol in self.universe:
closes = self.get_history(self.lookback, symbol, "close")
if len(closes) < self.lookback:
return
scores[symbol] = (closes[-1] - closes[0]) / closes[0]
# 选出最佳标的,持仓 95%
best = max(scores, key=scores.get)
self.order_target_percent(0.95, symbol=best)
FAQ
What does the akquant skill do?
生成 akquant 框架的可执行量化策略代码,涵盖数据接口、事件驱动、风控与优化。当用户需要开发量化策略、配置回测环境、设置风控规则、进行参数优化、实现横截面轮动策略,或提及 akquant 时使用
How do I install akquant?
Run npx skills add https://github.com/lzwme/finance-quant-skills --skill akquant in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/akquant/ (personal) or .claude/skills/akquant/ (project).
Which AI agents can use akquant?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is akquant safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains akquant?
It is published by lzwme in lzwme/finance-quant-skills. It has 205 recorded installs.
More from lzwme/finance-quant-skills
pywencai
lzwme/finance-quant-skills
同花顺问财数据查询:使用中文自然语言查询A股、指数、基金、港美股、可转债等市场数据;当用户需要通过自然语言从问财获取选股、财务、资金流、技术指标等数据时使用。
akshare
lzwme/finance-quant-skills
AKShare 开源金融数据接口库,提供股票、期货、期权、基金、外汇、债券、指数、加密货币等全品类金融数据;当用户需要获取各类金融市场数据时使用
baostock
lzwme/finance-quant-skills
BaoStock 免费开源 A 股数据平台,无需注册、无需 API Key,支持股票行情、K线、财务数据、行业分类、指数成分股查询。当用户提及 baostock、需要获取A股历史行情、财务报表、交易日历,或需要免费、免注册的A股数据时使用。与 tushare(数据更全但需注册)和 jqdatasdk(聚宽数据)不同,baostock 完全免费无限制,适合快速入门和低成本数据需求。
tdxquant
lzwme/finance-quant-skills
通达信量化数据获取技能。当用户提及 tdxquant、通达信、TdxQuant、tqcenter,并且需要获取A股数据(行情快照、K线、财务、板块、可转债、新股、交易数据等)、查询交易日历、执行通达信公式、订阅行情、交易下单时使用
backtrader
lzwme/finance-quant-skills
Backtrader 开源量化回测框架,支持多数据源、多策略、多周期回测与实盘交易,纯Python实现。当用户需要开发量化策略、进行回测分析、编写交易逻辑、回测参数优化,或提及 backtrader、量化回测框架时使用。若用户仅需数据获取而无回测需求,引导使用 baostock/akshare/tushare 等数据 Skill。
miniqmt
lzwme/finance-quant-skills
MiniQMT 迅投量化交易接口,基于 XtQuant Python 库(xtdata 行情 / xttrader 交易),供外部 Python 程序连接 MiniQMT 客户端,支持 A 股/期货/期权的行情获取(K线、分笔、财务数据等)和交易下单(报单、撤单、查询资产/委托/持仓)。当用户提及 miniqmt、xtquant、获取实时行情、量化交易下单、回测数据获取,或需要用外部 Python 程序连接 MiniQMT 客户端进行程序化交易时使用。若需在 QMT 客户端内编写/回测内置策略(ContextInfo/passorder),请用 qmt-strategy 技能。
Popular business & finance skills
website-builder
flowkit-labs/skills
Build and preview a hosted website for a business from a plain-language brief. Use for a new business homepage, landing page, service showcase, portfolio, online store, or customer portal, and for updates to sites hosted by this builder. Add bookings, checkout, or member accounts as needed and automate reminders, customer follow-ups, and reports after launch. Follow the user's choice when they specify another host or ask to edit an existing codebase.
sales-funnel-blueprint
autonnel/autonnel-skills
Turn an offer into a concrete multi-step sales funnel spec - page-by-page structure, price ladder, copy outline and the metrics each step must hit. Use when asked to build a sales funnel, marketing funnel, landing page flow, lead magnet funnel, webinar funnel, tripwire or VSL funnel, when planning a product launch page flow, or when someone asks "what pages do I need" for selling something online.
sales-enablement
coreyhaines31/marketingskills
When the user wants to create sales collateral, pitch decks, one-pagers, objection handling docs, or demo scripts. Also use when the user mentions 'sales deck,' 'pitch deck,' 'one-pager,' 'leave-behind,' 'objection handling,' 'deal-specific ROI analysis,' 'demo script,' 'talk track,' 'sales playbook,' 'proposal template,' 'buyer persona card,' 'battle card,' 'battlecard,' 'competitive one-pager,' 'win-loss analysis,' 'why are we losing deals,' 'loss reasons,' 'how do I respond to this objection,' 'prospect just said,' 'help my sales team,' 'sales materials,' or 'what should I give my sales reps,' 'cold call script,' or 'voicemail script.' Use this for any document or asset that helps a sales team close deals. For public competitor comparison pages, see competitors. For running buyer interviews or churn research, see customer-research. For marketing website copy, see copywriting. For cold outreach emails, see cold-email. For the offer being sold (bonuses, guarantees, pricing structure),
revops
coreyhaines31/marketingskills
When the user wants help with revenue operations, lead lifecycle management, or marketing-to-sales handoff processes. Also use when the user mentions 'RevOps,' 'revenue operations,' 'lead scoring,' 'outbound pipeline stages,' 'lead routing,' 'MQL,' 'SQL,' 'pipeline stages,' 'deal desk,' 'CRM automation,' 'marketing-to-sales handoff,' 'data hygiene,' 'leads aren't getting to sales,' 'pipeline management,' 'lead qualification,' or 'when should marketing hand off to sales.' Use this for anything involving the systems and processes that connect marketing to revenue. For cold outreach emails, see cold-email. For email drip campaigns, see emails. For pricing decisions, see pricing.
pricing
coreyhaines31/marketingskills
When the user wants help with pricing decisions, packaging, or monetization strategy. Also use when the user mentions 'pricing,' 'pricing tiers,' 'freemium,' 'free trial,' 'packaging,' 'price increase,' 'value metric,' 'Van Westendorp,' 'willingness to pay,' 'monetization,' 'how much should I charge,' 'my pricing is wrong,' 'pricing page,' 'annual vs monthly,' 'per seat pricing,' 'should I offer a free plan,' 'pricing page teardown,' 'pricing page audit,' 'is my pricing page AI-readable,' or 'can AI read my pricing.' Use this whenever someone is figuring out what to charge, how to structure their plans, or wants to audit a pricing page (for humans and for the AI agents that shortlist tools). For in-app upgrade screens, see paywalls. For offer construction (bonuses, guarantees, value framing, naming) on services/courses/coaching/high-ticket B2B, see offers.
offers
coreyhaines31/marketingskills
When the user wants to design, construct, or improve an offer — the thing they actually sell — including value framing, bonus stacking, guarantee design, scarcity/urgency, naming, and payment structure. Also use when the user mentions 'offer,' 'offer design,' 'build an offer,' 'grand slam offer,' 'irresistible offer,' 'value stack,' 'bonus stack,' 'guarantee,' 'risk reversal,' 'money-back guarantee,' 'scarcity,' 'urgency,' 'high-ticket offer,' 'productize a service,' 'naming an offer,' 'payment plan,' 'down-sell,' 'upsell offer,' or 'why isn't my offer converting.' Best for services, agencies, courses, coaching, info products, high-ticket B2B, and direct-response. If you run pure self-serve SaaS, read pricing first — tiers and packaging do more work there. For price level itself (tiers, freemium, value metric), see pricing. For the page that presents the offer, see copywriting. For the launch moment, see launch. For sales collateral, see sales-enablement.