ドキュメント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 の4 つすべてを定義します(空の on_tick で構いません。欠けていると実行が失敗します)。
  2. account is None(実行外では None)と、None の履歴に備えます。読み込まれた系列が始まる前は bar.close[i] が None です。
  3. 入力は、同じ行にリテラルの params.NAME を書いて読み取ります(入力パラメータを参照)。
  4. 銘柄ごとの状態は、大文字のティッカーをキーにした dict に保持します。ティッカーは 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. プロットするには、毎バー同じ文のなかで bar["t"] と値を追加し(ウォームアップ中は NaN)、on_finish で rt.chart_indicators.add(...) を 1 回呼びます。on_finish 内のすべての return は無言なので、ガード部分では sys.stderr に出力してください。
  9. ヘルパーモジュールでは、ハンドルを import quantcraft.process.runtime as rt(rt.account)で読み取り、from ... import account は使わないでください。
  10. on_finish で、すべての銘柄の最後の終値を account.refresh_metrics({...}) に渡します。そうしないと、オープン中のポジションは建値で評価されます。
  11. 複数銘柄:あるステップでバーのないティッカーには、前のバーが再度渡されます。カウント時は直前の bar["t"] を覚えておいて重複をスキップしてください。get_bar はクロック銘柄のみを読みます。
  12. バックテストのファンダメンタルズは新しい順です(fundamentals.current(bar["t"], symbol=sym))。カレンダーのリストは古い順、Screener スクリプトのファンダメンタルズは古い順です。calendar はフォワード実行では None です。
  13. 関心事が 2 つ以上 ⇒ アルゴ名のフォルダーを作り、ルートファイルも同名にします(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 を返します。失敗した場合はそれが次のタスクであり、通過していないのに動くと言ってはいけません。

マルチファイルプロジェクト(関心事が 2 つ以上ある場合の既定)

アルゴには専用のフォルダーを用意します。ルートファイルはアルゴ名にします(rsi_meanrev/rsi_meanrev.py、ライフサイクルのみ)。ヘルパーは関心事ごとにサブフォルダーにまとめ、責務ごとに小さなモジュールを 1 つ置きます。インポートはワークスペースのルートからの完全なドット区切りパスで、__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"])})

ユニバース全体でのモメンタム・ローテーション(複数銘柄または Screener ソース)

"""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) は、時点指定のスナップショット dict を返します(snap[table][period] は、そのバー時点で公開されている最新値の dict です)。ある値に基づいて取引する前に、スナップショットを一度出力して、その銘柄がどのフィールドを持つか確認してください。企業が報告しないフィールドは、存在しないか 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"] はフラットな dict(periodEnd、filing_date、数値フィールドは float)で、bar["t"] 時点で公開されている提出がなければ None なので、or {} のガードは残してください。戦略自体は、実際のファンダメンタルズデータでバックテストしたものではありません。

Screener スクリプトのパターン

契約についてはスクリーナーを参照してください。検証済みのパターン(行は昇順で最新が最後、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) はリバランスのたびに再実行されます(モジュールの状態はリセットされません)。

アルゴ クックブック — ドキュメント (1.0 (latest)) | QuantCraft