Dokumentation1.0 (latest)
SeitenAlgo-Rezepte · 10 / 37

Neu in v1.4.0

Algo-Rezepte: Faustregeln und vollständige Strategien

Neu in QuantCraft v1.4.0. Diese Seite beschreibt Funktionen, die mit v1.4.0, dem nächsten Hauptrelease, erscheinen. Die aktuelle Version ist v1.3.0 und enthält sie noch nicht.

Vollständige, laufzeitgetestete Strategien für den Backtest der QuantCraft-IDE sowie die Regeln, die eine generierte Strategie am häufigsten verletzt. Nutzen Sie sie als Vorlage, wenn ein neuer Algo geschrieben werden soll. API-Details stehen unter Backtests, Lebenszyklus einer Strategie, Kontomodell, Eingabeparameter und Indikatorreihen.

Checkliste, bevor Sie eine Strategie abgeben

  1. Definieren Sie alle vier Funktionen on_init, on_bar, on_tick, on_finish in der Stammdatei (ein leeres on_tick ist in Ordnung; fehlt es, scheitert der Lauf).
  2. Fangen Sie account is None (außerhalb eines Laufs ist es None) und eine None-Historie ab: bar.close[i] ist None, bevor die geladene Reihe beginnt.
  3. Lesen Sie Eingaben mit einem literalen params.NAME in derselben Zeile (siehe Eingabeparameter).
  4. Halten Sie den Zustand pro Symbol in Dicts, die nach dem großgeschriebenen Ticker indiziert sind; entnehmen Sie den Ticker dem Argument symbol ((symbol or SYMBOL).upper()).
  5. sl_price / tp_price werden gespeichert, lösen aber nie aus: Das Skript muss sie prüfen und close_trade aufrufen. Das Backtest-Konto hat keine Limit-/Stop-Orders; der übergebene Preis ist eine Anforderung, die Slippage und Kommission anschließend anpassen.
  6. Schließen Sie mit close_all_longs(px, symbol=sym) (das Schlüsselwort symbol ist Pflicht) oder close_trade(position_id, px). Offene Teilpositionen erhalten Sie aus account.open_positions_payload() oder aus open_positions des zurückgegebenen Snapshots; ein get_open_positions gibt es nicht.
  7. Dimensionieren Sie nach Kasse/Risiko: qty = int(account.cash * risk_pct / 100 / abs(entry - stop)). Eine Long-Eröffnung löst insufficient cash for long aus, wenn sie nicht finanzierbar ist.
  8. Zum Zeichnen hängen Sie bar["t"] und den Wert in derselben Anweisung bei jedem Balken an (NaN während der Einlaufphase) und rufen rt.chart_indicators.add(...) einmal in on_finish auf; jedes return in on_finish ist stumm, schreiben Sie daher an Schutzbedingungen auf sys.stderr.
  9. Lesen Sie in Hilfsmodulen die Handles über import quantcraft.process.runtime as rt (rt.account), nie über from ... import account.
  10. Übergeben Sie den letzten Schlusskurs jedes Symbols in on_finish an account.refresh_metrics({...}), sonst werden offene Positionen zum Einstiegspreis bewertet.
  11. Mehrere Symbole: Ein Ticker ohne Balken in einem Schritt erhält seinen vorherigen Balken erneut; vermeiden Sie Wiederholungen, indem Sie sich beim Zählen das letzte bar["t"] merken. get_bar liest nur das Taktsymbol.
  12. Backtest-Fundamentaldaten sind neueste zuerst (fundamentals.current(bar["t"], symbol=sym)); Kalenderlisten sind älteste zuerst; Fundamentaldaten in Screener-Skripten sind älteste zuerst. calendar ist in Forward-Läufen None.
  13. Zwei oder mehr Belange ⇒ ein eigener, nach dem Algo benannter Ordner mit gleichnamiger Stammdatei (rsi_meanrev/rsi_meanrev.py, nur Lebenszyklus) und nach Belang in Unterordner aufgeteilten Hilfsmodulen (rsi_meanrev/indicators/rsi.py, rsi_meanrev/risk/sizing.py); Importe verwenden den vollständigen gepunkteten Pfad (from rsi_meanrev.indicators.rsi import rsi). Siehe das Mehrdatei-Projekt unten.
  14. Jeder aus einer Workspace-Datei importierte Name muss dort existieren, und jede von Ihnen geschriebene Datei muss vollständiges, gültiges Python sein, das nur APIs aus dieser Dokumentation nutzt.
  15. Die App führt nach Ihren Änderungen einen Smoke-Backtest des Algos aus und liefert Last verification; ein Fehlschlag ist Ihre nächste Aufgabe, und Sie behaupten nie, es funktioniere, wenn es nicht bestanden hat.

Mehrdatei-Projekt (Standard bei zwei oder mehr Belangen)

Ein Algo bekommt einen eigenen Ordner. Die Stammdatei heißt wie der Algo (rsi_meanrev/rsi_meanrev.py, nur Lebenszyklus), und Hilfsmodule werden nach Belang in Unterordnern gruppiert, je ein kleines Modul pro Verantwortung. Importe verwenden den vollständigen gepunkteten Pfad ab dem Workspace-Stamm; es gibt keine __init__.py. Jeder Block beginnt mit einem # FILE:-Kommentar mit seinem Workspace-Pfad; dieses Projekt ist durchgängig laufzeitgetestet.

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-Crossover (Eingaben, Risikodimensionierung, manueller Stop, Chart-Overlay)

"""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-Mean-Reversion (Zeit-Stop)

"""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"])})

Momentum-Rotation über ein Universum (mehrere Symbole oder eine Screener-Quelle)

"""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)

Einstieg mit Fundamentaldaten / Kalender (Formprüfung erforderlich)

fundamentals.current(bar["t"], symbol=sym) gibt das Stichtags-Snapshot-Dict zurück (snap[table][period] ist ein Dict mit den neuesten bis zu diesem Balken öffentlichen Werten). Geben Sie den Snapshot einmal aus, um zu bestätigen, welche Felder ein Symbol führt, bevor Sie auf eines handeln; ein Feld, das ein Unternehmen nicht meldet, fehlt einfach oder ist 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 ...

Die Snapshot-Form wurde an einem echten BacktestFundamentals geprüft: snap["ratios"]["quarterly"] ist ein flaches Dict (periodEnd, filing_date, numerische Felder als Floats) und None, bis zu bar["t"] eine Einreichung öffentlich ist; behalten Sie daher die or {}-Absicherungen bei. Die Strategie selbst wurde nicht mit echten Fundamentaldaten gebacktestet.

Screener-Skript-Muster

Den Vertrag finden Sie unter Screener. Verifizierte Muster (Zeilen aufsteigend, neueste zuletzt; None abfangen):

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

Einen Backtest aus einem Screen zu steuern: Run backtest → Symbol & data → Symbol source: Screener → Screener source Python script, Rank direction, Limit, Refresh interval ≥ 7 days, explizite Start- und Enddaten; on_init(symbols) läuft dann bei jeder Neugewichtung erneut (der Modulzustand wird nicht zurückgesetzt).

Algo-Rezepte — Dokumentation (1.0 (latest)) | QuantCraft