moving_average.py
1"""A tiny trend-following "model" that needs only the Python standard library.23Use it to try the model decision method, then replace decide() with your own model.4It holds a fixed number of shares while the latest close is above the average close of5the previous ``window`` bars, and holds nothing otherwise.67Parameters (pass them as model_parameters): ``window`` (bars, default 5) and ``shares``8(target position while in the market, default 100).9"""1011from statistics import mean12from typing import Any, Dict, List, Optional1314SETTINGS: Dict[str, Any] = dict(window=5, shares=100)151617def setup(parameters: Dict[str, Any]) -> None:18 """Called once before the first decision. Load model weights here."""19 SETTINGS.update(parameters)202122def decide(23 bars: List[Dict[str, Any]], account: Dict[str, Any], context: Dict[str, Any]24) -> Optional[Dict[str, Any]]:25 """Return the number of shares to hold, or None to change nothing.2627 bars: completed bars, oldest first, each with time_ns, date, open, high, low, close28 (dollars) and volume (shares).29 account: cash, available_cash, position (shares), average_cost, equity and30 open_orders.31 context: symbol, time_ns, date, bar, bid, ask and parameters.32 """33 window = int(SETTINGS['window'])34 if len(bars) <= window:35 return None36 closes = [bar['close'] for bar in bars]37 above = closes[-1] > mean(closes[-window - 1 : -1])38 return dict(target_position=int(SETTINGS['shares']) if above else 0)