文档1.0 (latest)
页面算法示例集 · 10 / 37

v1.4.0 新增

算法示例集:经验法则与完整策略

QuantCraft v1.4.0 新增。 本页介绍随下一个主要版本 v1.4.0 发布的功能。当前版本为 v1.3.0,尚不包含这些功能。

适用于 QuantCraft IDE 回测的完整、经过运行测试的策略,以及生成的策略最常违反的规则。当被要求编写新算法时,请以它们为模板。API 详情见回测、策略生命周期、账户模型、输入参数和指标序列。

交付策略前的检查清单

  1. 在根文件中定义 on_init、on_bar、on_tick、on_finish 全部四个函数(空的 on_tick 没问题;缺少它则运行失败)。
  2. 防范 account is None(运行之外为 None)以及 None 历史数据:在已加载序列开始之前,bar.close[i] 为 None。
  3. 在同一行用字面量 params.NAME 读取输入(参见输入参数)。
  4. 按标的保存状态,使用以大写股票代码为键的字典;股票代码取自 symbol 参数((symbol or SYMBOL).upper())。
  5. sl_price / tp_price 会被保存,但永远不会触发:脚本必须自己检查并调用 close_trade。回测账户没有限价/止损单;您传入的价格只是一个请求,之后会由滑点和佣金调整。
  6. 用 close_all_longs(px, symbol=sym)(symbol 关键字必填)或 close_trade(position_id, px) 平仓。未平仓的仓位明细从 account.open_positions_payload() 或返回快照的 open_positions 获取;不存在 get_open_positions。
  7. 按现金/风险确定仓位:qty = int(account.cash * risk_pct / 100 / abs(entry - stop))。资金不足的做多开仓会抛出 insufficient cash for long。
  8. 绘图时,每根 K 线在同一条语句中追加 bar["t"] 和数值(预热期为 NaN),并在 on_finish 中调用一次 rt.chart_indicators.add(...);on_finish 中的每个 return 都是静默的,所以在保护分支处打印到 sys.stderr。
  9. 在辅助模块中,通过 import quantcraft.process.runtime as rt(rt.account)读取句柄,绝不要用 from ... import account。
  10. 在 on_finish 中把每个标的的最后收盘价传给 account.refresh_metrics({...}),否则未平仓头寸会按入场价估值。
  11. 多标的:某一步没有 K 线的股票代码会再次收到其上一根 K 线;计数时记住上一个 bar["t"] 以跳过重复。get_bar 只读取时钟标的。
  12. 回测基本面数据按从新到旧排列(fundamentals.current(bar["t"], symbol=sym));日历列表按从旧到新;选股器脚本中的基本面数据按从旧到新。calendar 在 forward 运行中为 None。
  13. 有两个或更多关注点 ⇒ 使用以算法命名的独立文件夹,根文件同名(rsi_meanrev/rsi_meanrev.py,仅含生命周期),并按关注点把辅助模块拆到子文件夹(rsi_meanrev/indicators/rsi.py、rsi_meanrev/risk/sizing.py);导入使用完整的点分路径(from rsi_meanrev.indicators.rsi import rsi)。参见下面的多文件项目。
  14. 从工作区文件导入的每个名称都必须存在于其中,您写入的每个文件都必须是仅使用本文档 API 的完整、有效的 Python。
  15. 应用会在您编辑后对算法进行冒烟回测并返回 Last verification;失败就是您的下一个任务,未通过时切勿声称它能正常运行。

多文件项目(有两个或更多关注点时的默认方式)

一个算法拥有自己的文件夹。根文件以算法命名(rsi_meanrev/rsi_meanrev.py,仅含生命周期),辅助模块按关注点分组到子文件夹中,每个职责一个小模块。导入使用从工作区根目录开始的完整点分路径;没有 __init__.py。每个代码块都以 # FILE: 注释开头,标明其工作区路径;该项目已端到端运行测试。

rsi_meanrev/ ├── rsi_meanrev.py root: lifecycle only ├── indicators/rsi.py indicator math ├── signals/entries.py entry / exit rules └── risk/sizing.py position sizing
# FILE: rsi_meanrev/rsi_meanrev.py """RSI mean reversion. Root file: lifecycle only; logic lives in indicators/, signals/ and risk/.""" from quantcraft.inputs import params from quantcraft.process.runtime import account from rsi_meanrev.indicators.rsi import rsi from rsi_meanrev.risk.sizing import position_size from rsi_meanrev.signals.entries import should_enter, should_exit SYMBOL = "AAPL" RSI_LEN = params.RSI_LEN if hasattr(params, "RSI_LEN") else 14 BUY_BELOW = params.BUY_BELOW if hasattr(params, "BUY_BELOW") else 30 EXIT_ABOVE = params.EXIT_ABOVE if hasattr(params, "EXIT_ABOVE") else 55 MAX_HOLD_BARS = params.MAX_HOLD_BARS if hasattr(params, "MAX_HOLD_BARS") else 20 MAX_QTY = params.MAX_QTY if hasattr(params, "MAX_QTY") else 100 _entry_index = {} # symbol -> bar_index at entry def on_init(symbols=None): _entry_index.clear() def on_bar(bar_index, bar, symbol=None): if account is None: return sym = (symbol or SYMBOL).upper() px = float(bar["close"]) value = rsi(bar, RSI_LEN) if value is None: return held = [p for p in account.open_positions_payload() if p["symbol"] == sym] if not held: qty = position_size(account.cash, px, MAX_QTY) if qty > 0 and should_enter(value, BUY_BELOW): account.open_trade(sym, "long", qty, px) _entry_index[sym] = bar_index else: bars_held = bar_index - _entry_index.get(sym, bar_index) if should_exit(value, EXIT_ABOVE, bars_held, MAX_HOLD_BARS): account.close_all_longs(px, symbol=sym) def on_tick(bar_index, tick_in_bar, price, bar, symbol=None): pass def on_finish(bars, symbol=None, bars_by_symbol=None): if account is not None and bars: sym = (symbol or SYMBOL).upper() account.refresh_metrics({sym: float(bars[-1]["close"])})
# FILE: rsi_meanrev/indicators/rsi.py """RSI indicator. Pure function of the bar history.""" def rsi(bar, length): """RSI over the last `length` closes, or None while the history is still warming up.""" closes = [bar.close[i] for i in range(length + 1)] if None in closes: return None gains = sum(max(a - b, 0.0) for a, b in zip(closes, closes[1:])) losses = sum(max(b - a, 0.0) for a, b in zip(closes, closes[1:])) if losses == 0: return 100.0 return 100.0 - 100.0 / (1.0 + gains / losses)
# FILE: rsi_meanrev/signals/entries.py """Entry and exit rules. Pure functions: no orders, no globals.""" def should_enter(value, buy_below): """Oversold: RSI under the threshold.""" return value < buy_below def should_exit(value, exit_above, bars_held, max_hold): """Recovered, or held too long.""" return value > exit_above or bars_held >= max_hold
# FILE: rsi_meanrev/risk/sizing.py """Position sizing. Pure function of cash and price.""" def position_size(cash, price, max_qty): """Whole shares affordable with at most 95% of cash, capped at max_qty (0 if none).""" if price <= 0 or cash <= 0: return 0 return max(0, min(int(max_qty), int(cash * 0.95 / price)))

SMA 交叉(输入、按风险定仓、手动止损、图表叠加)

"""SMA crossover with inputs, risk-based sizing, manual stops and a chart overlay.""" import sys from quantcraft.inputs import params from quantcraft.process.runtime import account import quantcraft.process.runtime as rt SYMBOL = "AAPL" FAST = params.FAST if hasattr(params, "FAST") else 10 SLOW = params.SLOW if hasattr(params, "SLOW") else 30 RISK_PCT = params.RISK_PCT if hasattr(params, "RISK_PCT") else 1.0 STOP_PCT = params.STOP_PCT if hasattr(params, "STOP_PCT") else 0.03 _times = {} _fast_vals = {} _slow_vals = {} _prev_state = {} # symbol -> True when fast was above slow on the previous bar def sma(bar, n): vals = [bar.close[i] for i in range(n)] return None if None in vals else sum(vals) / n def open_legs(sym): return [p for p in account.open_positions_payload() if p["symbol"] == sym] def on_init(symbols=None): _prev_state.clear() def on_bar(bar_index, bar, symbol=None): if account is None: return sym = (symbol or SYMBOL).upper() px = float(bar["close"]) fast, slow = sma(bar, FAST), sma(bar, SLOW) _times.setdefault(sym, []).append(bar["t"]) _fast_vals.setdefault(sym, []).append(float("nan") if fast is None else fast) _slow_vals.setdefault(sym, []).append(float("nan") if slow is None else slow) if fast is None or slow is None: return # manual stop-loss: positions never close themselves for p in open_legs(sym): if p["sl_price"] is not None and px <= p["sl_price"]: account.close_trade(p["id"], px) above = fast > slow was_above = _prev_state.get(sym) _prev_state[sym] = above if was_above is None: return if above and not was_above and not open_legs(sym): # golden cross stop = px * (1 - STOP_PCT) qty = int(account.cash * RISK_PCT / 100.0 / (px - stop)) if qty > 0: account.open_trade(sym, "long", qty, px, sl_price=stop) elif was_above and not above: # death cross account.close_all_longs(px, symbol=sym) def on_tick(bar_index, tick_in_bar, price, bar, symbol=None): pass def on_finish(bars, symbol=None, bars_by_symbol=None): ci = rt.chart_indicators if ci is not None: for sym in sorted(_times): for label, series, color in (("fast", _fast_vals, "#22c55e"), ("slow", _slow_vals, "#f97316")): n = FAST if label == "fast" else SLOW ci.add( [{"time": t, "value": v} for t, v in zip(_times[sym], series[sym])], pane="main", render="line", line_style="solid", id=f"sma_{n}_{sym}", name=f"SMA({n}) {sym}", color=color, symbol=sym, ) if account is not None and bars: sym = (symbol or SYMBOL).upper() m = account.refresh_metrics({sym: float(bars[-1]["close"])}) print("sharpe", m["sharpe_ratio"], "max drawdown", m["max_drawdown"], file=sys.stderr)

RSI 均值回归(时间止损)

"""RSI mean reversion: buy oversold, exit on recovery or after a time stop.""" from quantcraft.inputs import params from quantcraft.process.runtime import account SYMBOL = "AAPL" RSI_LEN = params.RSI_LEN if hasattr(params, "RSI_LEN") else 14 BUY_BELOW = params.BUY_BELOW if hasattr(params, "BUY_BELOW") else 30 EXIT_ABOVE = params.EXIT_ABOVE if hasattr(params, "EXIT_ABOVE") else 55 MAX_HOLD_BARS = params.MAX_HOLD_BARS if hasattr(params, "MAX_HOLD_BARS") else 20 QTY = params.QTY if hasattr(params, "QTY") else 10 _entry_index = {} # symbol -> bar_index at entry def rsi(bar, n): closes = [bar.close[i] for i in range(n + 1)] if None in closes: return None gains = sum(max(a - b, 0.0) for a, b in zip(closes, closes[1:])) losses = sum(max(b - a, 0.0) for a, b in zip(closes, closes[1:])) if losses == 0: return 100.0 return 100.0 - 100.0 / (1.0 + gains / losses) def on_init(symbols=None): pass def on_bar(bar_index, bar, symbol=None): if account is None: return sym = (symbol or SYMBOL).upper() px = float(bar["close"]) value = rsi(bar, RSI_LEN) if value is None: return held = [p for p in account.open_positions_payload() if p["symbol"] == sym] if not held: if value < BUY_BELOW: account.open_trade(sym, "long", QTY, px) _entry_index[sym] = bar_index else: timed_out = bar_index - _entry_index.get(sym, bar_index) >= MAX_HOLD_BARS if value > EXIT_ABOVE or timed_out: account.close_all_longs(px, symbol=sym) def on_tick(bar_index, tick_in_bar, price, bar, symbol=None): pass def on_finish(bars, symbol=None, bars_by_symbol=None): if account is not None and bars: sym = (symbol or SYMBOL).upper() account.refresh_metrics({sym: float(bars[-1]["close"])})

跨标的池的动量轮动(多个标的或选股器来源)

"""Cross-symbol momentum rotation: hold the N strongest tickers, rebalance every K bars.""" from quantcraft.inputs import params from quantcraft.process.runtime import account LOOKBACK = params.LOOKBACK if hasattr(params, "LOOKBACK") else 20 TOP_N = params.TOP_N if hasattr(params, "TOP_N") else 2 REBALANCE_EVERY = params.REBALANCE_EVERY if hasattr(params, "REBALANCE_EVERY") else 5 CASH_PER_NAME = params.CASH_PER_NAME if hasattr(params, "CASH_PER_NAME") else 20000 _momentum = {} # symbol -> latest LOOKBACK-bar return _price = {} # symbol -> latest close _universe = [] def on_init(symbols=None): _universe[:] = [s.upper() for s in (symbols or [])] # re-runs at every screener rebalance def on_bar(bar_index, bar, symbol=None): if account is None or not symbol: return sym = symbol.upper() old = bar.close[LOOKBACK] px = float(bar["close"]) _price[sym] = px _momentum[sym] = None if old in (None, 0) else px / old - 1.0 # Rebalance once per step, when the LAST ticker of the step has been seen. # _universe can be empty (a screener window that matched nothing while a held ticker still ticks). if not _universe or sym != _universe[-1] or bar_index % REBALANCE_EVERY != 0: return ranked = sorted( (s for s in _universe if _momentum.get(s) is not None), key=lambda s: _momentum[s], reverse=True, ) winners = set(ranked[:TOP_N]) held = {p["symbol"]: p for p in account.open_positions_payload()} for s, p in held.items(): if s not in winners: account.close_trade(p["id"], _price[s]) for s in winners: if s not in held: qty = int(CASH_PER_NAME / _price[s]) if qty > 0: account.open_trade(s, "long", qty, _price[s]) def on_tick(bar_index, tick_in_bar, price, bar, symbol=None): pass def on_finish(bars, symbol=None, bars_by_symbol=None): if account is None: return # bars_by_symbol ({symbol: chronological rows}) is passed only on multi-symbol runs; # a single-symbol run gets bars/symbol instead, and a screener run has bars == []. if bars_by_symbol: marks = {s.upper(): float(rows[-1]["close"]) for s, rows in bars_by_symbol.items() if rows} elif bars and symbol: marks = {symbol.upper(): float(bars[-1]["close"])} else: marks = {} if marks: account.refresh_metrics(marks)

结合基本面 / 日历的入场(需要核对数据结构)

fundamentals.current(bar["t"], symbol=sym) 返回按时点截取的快照字典(snap[table][period] 是在该 K 线时已公开的最新值字典)。请先打印一次快照,确认某个标的带有哪些字段,再基于其中的字段交易;公司没有披露的字段只是缺失或为 None。

def on_bar(bar_index, bar, fundamentals=None, calendar=None, symbol=None): sym = (symbol or "AAPL").upper() if calendar is not None: days = calendar.days_to_earnings(bar["t"], sym) if days is not None and days <= 2: return # sit out the earnings print snap = (fundamentals.current(bar["t"], symbol=sym) if fundamentals is not None else None) or {} margin = ((snap.get("ratios") or {}).get("quarterly") or {}).get("netProfitMargin") quality_ok = margin is not None and margin > 0.10 ...

快照的结构已用真实的 BacktestFundamentals 核对过:snap["ratios"]["quarterly"] 是一个扁平字典(periodEnd、filing_date,数值字段为浮点数),在 bar["t"] 时尚无公开申报则为 None,因此请保留 or {} 的保护。策略本身并未使用真实基本面数据回测过。

选股器脚本模式

契约请参阅选股器。已验证的模式(行按升序,最新的在最后;防范 None):

def filter(fundamentals, symbol): # ROE with low leverage r = (fundamentals.get("ratios") or {}).get("quarterly") or [] if not r: return {"result": False} roe, de = r[-1].get("returnOnEquity"), r[-1].get("debtToEquityRatio") if roe is None or de is None: return {"result": False} return {"result": roe > 0.15 and de < 1.0, "value": roe}
def filter(fundamentals, symbol): # value: multiples are None for loss-makers v = (fundamentals.get("valuation") or {}).get("quarterly") or [] if not v: return {"result": False} pe, ps = v[-1].get("priceToEarningsRatio"), v[-1].get("priceToSalesRatio") if pe is None or ps is None: return {"result": False} return {"result": 0 < pe < 15 and 0 < ps < 2, "value": {"pe": pe, "ps": ps}} def rank(value, symbol): return -value["pe"] # lower P/E ranks higher
def filter(fundamentals, symbol): # composite score: keep all, let rank() decide from statistics import mean rat = (fundamentals.get("ratios") or {}).get("quarterly") or [] if not rat: return {"result": False} row = rat[-1] def z(v, lo, hi): return None if v is None else max(0.0, min(1.0, (v - lo) / (hi - lo))) parts = [z(row.get("returnOnEquity"), 0.0, 0.30), z(row.get("netProfitMargin"), 0.0, 0.25), z(row.get("currentRatio"), 0.8, 2.5)] parts = [p for p in parts if p is not None] if len(parts) < 3: return {"result": False} return {"result": True, "value": mean(parts)} def rank(value, symbol): return value * 100.0

用选股结果驱动回测:Run backtest → Symbol & data → Symbol source: Screener → Screener source Python script、Rank direction、Limit、Refresh interval ≥ 7 days、明确的开始和结束日期;之后每次再平衡时都会重新运行 on_init(symbols)(模块状态不会重置)。

阅读约 9 分钟建议修改 ↗
算法示例集 — 文档 (1.0 (latest)) | QuantCraft