# Python 3.10+; NumPy required for recipes 1 and 2. Synthetic educational fixtures. # 1. Reconcile a causal signal and its costs import numpy as np def causal_net_returns(returns, signals, cost_bps=10.0): """1-D daily decimal returns; end-of-day unit exposures; one-way bps.""" r, s = np.asarray(returns, float), np.asarray(signals, float) if r.ndim != 1 or r.size == 0 or r.shape != s.shape: raise ValueError("Use equally sized nonempty 1-D arrays") if not (np.isfinite(r).all() and np.isfinite(s).all()): raise ValueError("Inputs must be finite") if not np.isfinite(cost_bps) or cost_bps < 0: raise ValueError("Costs must be finite and nonnegative") held = np.r_[0.0, s[:-1]] turnover = np.abs(np.diff(np.r_[0.0, held])) return held * r - cost_bps / 10_000 * turnover result = causal_net_returns([.01, -.02, .03], [1, 0, 1]) np.testing.assert_allclose(result, [0, -.021, -.001]) print(result) # [ 0. -0.021 -0.001] # 2. Calculate portfolio risk without hiding the covariance import numpy as np def portfolio_daily_risk(weights, covariance): """Return (daily variance, daily volatility); daily decimal covariance.""" w, cov = np.asarray(weights, float), np.asarray(covariance, float) if w.ndim != 1 or not w.size or cov.shape != (w.size, w.size): raise ValueError("Covariance must match a nonempty weight vector") if not (np.isfinite(w).all() and np.isfinite(cov).all()): raise ValueError("Inputs must be finite") if not np.allclose(cov, cov.T, rtol=0, atol=1e-12): raise ValueError("Covariance must be symmetric") if np.linalg.eigvalsh(cov).min() < -1e-12: raise ValueError("Covariance must be positive semidefinite") variance = max(0.0, float(w @ cov @ w)) return variance, variance ** .5 v, sigma = portfolio_daily_risk([.5, .5], [[.0004, .0001], [.0001, .0009]]) assert abs(v - .000375) < 1e-12 print(round(sigma, 6)) # 0.019365 # 3. Generate chronological validation windows def walk_forward(n_rows, min_train, test_size, gap=0): """Yield expanding train and fixed test index ranges, measured in rows.""" values = (n_rows, min_train, test_size, gap) if any(type(x) is not int for x in values): raise ValueError("All sizes must be integers") if min(n_rows, min_train, test_size) < 1 or gap < 0: raise ValueError("Positive sizes and a nonnegative gap are required") for start in range(min_train + gap, n_rows - test_size + 1, test_size): yield range(start - gap), range(start, start + test_size) folds = [(list(train), list(test)) for train, test in walk_forward(10, 4, 2, 1)] assert folds == [([0, 1, 2, 3], [5, 6]), ([0, 1, 2, 3, 4, 5], [7, 8])] print(folds) # Fit scalers and models on each train range only. # The incomplete final test window is deliberately excluded. # 4. Make fill replay idempotent from decimal import Decimal def replay_inventory(fills): """(unique fill id, signed quantity string) pairs; output in base units.""" seen, inventory = set(), Decimal("0") for fill_id, signed_quantity in fills: if not isinstance(fill_id, str) or not fill_id: raise ValueError("Each fill needs a nonempty string id") quantity = Decimal(signed_quantity) if not quantity.is_finite(): raise ValueError("Fill quantity must be finite") if fill_id not in seen: inventory += quantity seen.add(fill_id) return inventory fills = [("fill-a", "0.2"), ("fill-a", "0.2"), ("fill-b", "-0.05")] assert replay_inventory(fills) == Decimal("0.15") print(replay_inventory(fills)) # 0.15 base units