Documentation1.0 (latest)
PagesAlgo cookbook · 10 / 37

New in v1.4.0

Algo cookbook: rules of thumb and complete strategies

New in QuantCraft v1.4.0. This page describes functionality that ships with v1.4.0, the next major release. The current release is v1.3.0, which does not include it yet.

Complete, run-tested strategies for the QuantCraft IDE backtest, plus the rules a generated strategy most often breaks. Use these as the template when asked to write a new algo. API detail lives in Backtests, Strategy lifecycle, Account model, Input parameters, Indicator series.

Checklist before returning a strategy

  1. Define all four of on_init, on_bar, on_tick, on_finish in the root file (an empty on_tick is fine; a missing one fails the run).
  2. Guard account is None (it is None outside a run) and None history: bar.close[i] is None before the loaded series starts.
  3. Read inputs with a literal params.NAME on the same line (see Input parameters).
  4. Keep per-symbol state in dicts keyed by the uppercase ticker; take the ticker from the symbol argument ((symbol or SYMBOL).upper()).
  5. sl_price / tp_price are stored but never trigger: the script must check them and call close_trade. The backtest account has no limit/stop orders; the price you pass is a request that slippage and commission then adjust.
  6. Close with close_all_longs(px, symbol=sym) (the symbol keyword is required) or close_trade(position_id, px). Get open legs from account.open_positions_payload() or the returned snapshot's open_positions; there is no get_open_positions.
  7. Size by cash/risk: qty = int(account.cash * risk_pct / 100 / abs(entry - stop)). A long open raises insufficient cash for long when it cannot be afforded.
  8. Plot by appending bar["t"] and the value in the same statement every bar (NaN while warming up) and calling rt.chart_indicators.add(...) once in on_finish; every return in on_finish is silent, so print to sys.stderr at guards.
  9. In helper modules read handles through import quantcraft.process.runtime as rt (rt.account), never from ... import account.
  10. Pass the last close of every symbol to account.refresh_metrics({...}) in on_finish, otherwise open positions are valued at entry.
  11. Multi-symbol: a ticker without a bar at a step receives its previous bar again; skip repeats by remembering the last bar["t"] when counting. get_bar reads the clock symbol only.
  12. Backtest fundamentals are newest-first (fundamentals.current(bar["t"], symbol=sym)); calendar lists are oldest-first; screener-script fundamentals are oldest-first. calendar is None in forward runs.
  13. Two or more concerns ⇒ its own folder named after the algo, with the root file named the same (rsi_meanrev/rsi_meanrev.py, lifecycle only) and helpers split into subfolders by concern (rsi_meanrev/indicators/rsi.py, rsi_meanrev/risk/sizing.py); imports are the full dotted path (from rsi_meanrev.indicators.rsi import rsi). See the multi-file project below.
  14. Every name you import from a workspace file must exist in it, and every file you write must be complete, valid Python using only APIs from these docs.
  15. The app smoke-backtests the algo after your edits and returns Last verification; a failure is your next task, and you never say it works unless it passed.

Multi-file project (default for anything with two or more concerns)

An algo gets its own folder. The root file is named after the algo (rsi_meanrev/rsi_meanrev.py, lifecycle only) and helpers are grouped into subfolders by concern, one small module per responsibility. Imports are the full dotted path from the workspace root; there is no __init__.py. Every block starts with a # FILE: comment naming its workspace path; this project is run-tested end to end.

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 (inputs, risk sizing, manual 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 (time 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 across a universe (several symbols or a Screener source)

"""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 / calendar-aware entry (shape check required)

fundamentals.current(bar["t"], symbol=sym) returns the as-of snapshot dict (snap[table][period] is a dict of the latest values public at that bar). Print the snapshot once to confirm which fields a symbol carries before trading on one; a field a company does not report is simply absent or 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 ...

The snapshot shape was checked against a real BacktestFundamentals: snap["ratios"]["quarterly"] is a flat dict (periodEnd, filing_date, numeric fields as floats) and is None until a filing is public at bar["t"], so keep the or {} guards. The strategy itself was not backtested against live fundamentals data.

Screener Script patterns

See Screener for the contract. Verified patterns (rows ascending, newest last; guard 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

To drive a backtest from a screen: Run backtest → Symbol & data → Symbol source: Screener → Screener source Python script, Rank direction, Limit, Refresh interval ≥ 7 days, explicit start and end dates; on_init(symbols) then re-runs at every rebalance (module state is not reset).

Algo cookbook — Documentation (1.0 (latest)) | QuantCraft