From 6efb4acb8fc89644b6c9d80b1e1120b7758708d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 27 Sep 2026 16:48:25 +0000 Subject: [PATCH 1/3] Record the GLD result and register multi-asset research (ADR-011) - ADR-010: add the one-time result on real GLD data (experiment cc6999fc32cd36f4): FAIL on R1, R2, R4; +15.6% compounded across 29 rolling windows against +158.7% for holding GLD - ADR-011: register the six-ETF universe (GLD, SLV, SPY, EFA, IEF, DBC), adjusted prices, three trend rules times two sizings (equal weight; inverse volatility capped at 35%), monthly rebalancing, costs, the ADR-010 selection method, and the strictest gate: beat both equal-weight buy-and-hold of the six and SPY, with no larger drawdown Written before any multi-asset code or result exists. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fx8W9jDiTaGhDRbiq7Hgm5 --- docs/decisions.md | 123 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) diff --git a/docs/decisions.md b/docs/decisions.md index 0c67d87..eaeaf44 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -378,6 +378,28 @@ Record the result. The next option is multi-asset trend-following, which needs new data, a new simulator, and a new registration ADR. The other option is to accept that a low-cost index fund is the better choice. +### Result (2026-09-27) + +Evaluated once on the Tiingo GLD history, 5,497 daily bars (experiment +`cc6999fc32cd36f4`). **Verdict: FAIL.** Failing checks: R1, R2, R4. R3 +passed. + +| Rolling tests before the holdout (29 windows) | Registered process | 100% GLD buy-and-hold | +|---|---|---| +| Compounded return | +15.6% | +158.7% | +| Windows with a positive return | 9 of 29 | — | +| Windows beating same-cap buy-and-hold | 10 of 29 (18 needed) | — | +| Closed trades | 64 | — | + +The final holdout selected `trend_200_volfilter`: +59.5% with an 8.3% +maximum drawdown, against +125.6% and 26.4% for buy-and-hold. It was in the +market 36% of the time. Holding about 45% GLD and 55% cash would have had the +same volatility and a similar return, so the timing added little. That +period had already been viewed and is not evidence. + +No candidate trades real money. Next step: multi-asset trend-following +(ADR-011). + ### Consequences - Changing, adding, or removing a candidate requires a new ADR, and every @@ -386,6 +408,107 @@ is to accept that a low-cost index fund is the better choice. --- +## ADR-011 — Registered Multi-Asset Trend-Following Research + +**Status:** Accepted. Registered before any multi-asset code or result +existed. + +### Context + +Trend rules on GLD alone failed the gate (ADR-010). Published evidence for +time-series momentum is much stronger across many markets, because assets +that do not move together smooth out each other's whipsaws. This ADR fixes +the assets, rules, sizing, method, and pass criteria before anything is +built or run. + +### Universe and data + +- **Six ETFs:** GLD (gold), SLV (silver), SPY (US stocks), EFA + (international stocks), IEF (US government bonds), DBC (broad + commodities). +- **History:** from the first day all six have a Tiingo bar (spring 2006) to + the latest import. The six share one calendar; a missing day for any + symbol is an error, never filled in. +- **Prices:** Tiingo's dividend- and split-adjusted OHLC for signals, + simulated fills, and valuation, so the results include dividends as total + return. Raw prices are kept for execution checks. + +### Rules and sizing (6 candidates) + +Each rule is evaluated per asset at the last close of each month, using the +point-in-time features of ADR-010 computed on adjusted prices: + +- **mom:** in when 12-1 month momentum is positive. +- **trend:** in when the close is above its 200-day average. +- **both:** in when both are true. + +Two ways to size an asset that is in: + +- **eq:** 1/6 of equity. +- **iv35:** inverse 60-day volatility, normalized across all six assets and + capped at 35% per asset, with any excess shared proportionally among the + uncapped assets. + +Assets that are out hold cash. The candidates are `mom_eq`, `trend_eq`, +`both_eq`, `mom_iv35`, `trend_iv35`, and `both_iv35`. + +### Simulation + +- Rebalance monthly: signals at the month's last close, orders at the next + open. An asset trades only if its target differs from its holding by more + than 1% of equity. +- Whole shares, sells before buys, cash never negative, never margin, total + weight at most 100%. +- Costs: $0.01 slippage per share, zero commission. The stress test uses + $0.10. +- The 10% portfolio drawdown halt is checked daily: it sells everything and + blocks new entries for the rest of the run, as in the GLD research. + +### Selection and tests + +These are the same as ADR-010. A 60/20/20 chronological split is used, and +rolling windows before the final holdout: 504 development, 126 validation, +and 126 test bars, with test blocks that do not overlap. Each window selects +the candidate with the highest validation return minus maximum drawdown, or +cash if none is positive. + +### Benchmarks and the gate (the strictest option) + +The strategy must beat **both** benchmarks: + +- **B1:** equal-weight buy-and-hold of the same six ETFs, rebalanced + monthly, with the same costs. +- **B2:** 100% SPY buy-and-hold, the "just buy an index fund" alternative. + +| Check | Requirement | +|---|---| +| R1 | Compounded return across the rolling test windows exceeds both B1's and B2's | +| R2 | Beats both B1 and B2 in at least 60% of the rolling windows | +| R3 | At least 30 closed round trips, counted per asset | +| R4 | R1 still holds with slippage at $0.10 per share | +| R5 | Maximum drawdown of the chained rolling test returns is no larger than either benchmark's, chained the same way | +| F1 | At least 252 paper sessions on one frozen strategy version | +| F2 | Paper return exceeds both B1 and B2 over those sessions | +| F3 | Paper maximum drawdown is no larger than either benchmark's | +| F4 | Mean fill cost against the simulated fill of at most 10 bps, over at least 10 fills | + +This is deliberately harder than ADR-008's single-asset gate. Trend-following +usually trails stocks in long bull markets and wins by losing less in +crashes, so beating SPY on return over 2006 onward is unlikely. That is +accepted: the rule exists to prevent investing in anything that an index +fund would beat. + +### What happens after the run + +- The result is recorded here and in the experiment log, pass or fail. +- **If R1 to R5 pass:** multi-asset paper trading is built (a separate ADR), + the dry run comes first, then a year of forward testing (F1 to F4). +- **If they fail:** stop, or register Phase 7 machine learning on this + dataset in a new ADR. The candidates and thresholds above are not tuned + and re-run. + +--- + ## ADR Template ### ADR-XXX — Title From 4a1320ea222cd67974fa45c897db7e343002cad9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 27 Sep 2026 16:54:14 +0000 Subject: [PATCH 2/3] Add the multi-symbol data pipeline (MA2) - tiingo.import_symbol: any plain ticker, with the same manifest hashes, safe refresh, and revised-history refusal as GLD; import_gld is now a thin wrapper, so paper trading is unchanged - prune_imports keeps the newest three imports of a symbol (and three superseded copies) after each import, capping disk growth; only that symbol's exact files are touched - tradenow/universe.py: the ADR-011 universe, dividend-adjusted parsing with raw closes kept, alignment trimmed to the common range with any interior missing day refused, and a combined input hash - CLI: tiingo-import --symbols/--universe (stops at the first failure and reports partial results) and an offline universe command Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fx8W9jDiTaGhDRbiq7Hgm5 --- README.md | 17 ++++- tests/test_universe.py | 146 ++++++++++++++++++++++++++++++++++++++ tradenow/__main__.py | 57 +++++++++++++-- tradenow/gld_research.py | 19 +---- tradenow/tiingo.py | 149 +++++++++++++++++++++++++++++++-------- tradenow/universe.py | 149 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 484 insertions(+), 53 deletions(-) create mode 100644 tests/test_universe.py create mode 100644 tradenow/universe.py diff --git a/README.md b/README.md index c57e13c..e126be7 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,22 @@ the result is `UNCHANGED` and nothing is written. Revised history is refused, and the earlier import is kept. The key is sent in an authorization header and never written to the data files. The import command does not run a backtest or contact a broker. -Replay the newest private import without another Tiingo request: +For the multi-asset research (ADR-011), import all six registered ETFs (GLD, +SLV, SPY, EFA, IEF, DBC) with the same protections, then check that they align: + +```powershell +python -m tradenow tiingo-import --universe --start 2004-11-18 --end 2026-09-25 +python -m tradenow universe +``` + +`--symbols SPY,IEF` imports a chosen few. Several symbols make two requests +each; the first failure (for example a rate limit) stops the run and reports +what was already imported. After every import, only the newest three imports +of that symbol are kept, which caps disk use. `universe` uses dividend-adjusted +prices, trims the six histories to the dates they all cover, and refuses any +missing day inside that range. + +Replay the newest private GLD import without another Tiingo request: ```powershell python -m tradenow gld diff --git a/tests/test_universe.py b/tests/test_universe.py new file mode 100644 index 0000000..140e726 --- /dev/null +++ b/tests/test_universe.py @@ -0,0 +1,146 @@ +import hashlib +import json +import tempfile +import unittest +from datetime import date, timedelta +from decimal import Decimal +from pathlib import Path +from unittest.mock import patch + +from tradenow.tiingo import HEADER, import_symbol, latest_import, prune_imports +from tradenow.universe import ( + MIN_COMMON_BARS, + UNIVERSE, + align, + load_universe, + parse_adjusted_csv, +) + + +def weekdays(start: date, count: int, skip: set[date] = frozenset()) -> list[date]: + days, day = [], start + while len(days) < count: + if day.weekday() < 5 and day not in skip: + days.append(day) + day += timedelta(days=1) + return days + + +def tiingo_csv(symbol: str, days: list[date], dividend_on: date | None = None) -> bytes: + """Raw prices with a dividend: adjusted prices before it are scaled down 2%.""" + rows = [",".join(HEADER)] + for index, day in enumerate(days): + close = Decimal(100 + index % 17) + factor = Decimal("0.98") if dividend_on and day < dividend_on else Decimal(1) + raw = (close, close + 1, close - 1, close) + adjusted = tuple(price * factor for price in raw) + dividend = "1.5" if day == dividend_on else "0.0" + rows.append(",".join([day.isoformat(), symbol, *map(str, raw), "5000", + *map(str, adjusted), "5000", dividend, "1.0"])) + return ("\n".join(rows) + "\n").encode() + + +def save_import(directory: Path, symbol: str, data: bytes, start: date, end: date) -> None: + stem = f"{symbol}-{start:%Y%m%d}-{end:%Y%m%d}" + (directory / f"{stem}.csv").write_bytes(data) + (directory / f"{stem}.raw.json").write_text("[]", encoding="utf-8") + (directory / f"{stem}.manifest.json").write_text(json.dumps({ + "provider": "Tiingo", "symbol": symbol, "last_bar": end.isoformat(), + "bars_sha256": hashlib.sha256(data).hexdigest()}), encoding="utf-8") + + +class ImportTests(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.directory = Path(directory.name) + + def test_any_registered_symbol_imports_with_its_own_files(self): + rows = [{"date": "2026-09-24T00:00:00.000Z", "open": 30.0, "high": 31.0, "low": 29.0, + "close": 30.5, "volume": 900, "adjOpen": 29.0, "adjHigh": 30.0, + "adjLow": 28.0, "adjClose": 29.5, "adjVolume": 900, "divCash": 0.2, + "splitFactor": 1.0}] + meta = {"ticker": "slv", "startDate": "2006-04-28", "endDate": "2026-09-24"} + with patch("tradenow.tiingo._get_json", + side_effect=[(meta, b"{}"), (rows, json.dumps(rows).encode())]) as get: + result = import_symbol("SLV", date(2026, 9, 24), date(2026, 9, 24), "k", + self.directory) + self.assertEqual(get.call_args_list[0].args[0], "https://api.tiingo.com/tiingo/daily/SLV") + self.assertEqual(result["symbol"], "SLV") + self.assertTrue(Path(result["bars_file"]).name.startswith("SLV-20260924-20260924")) + source, name = latest_import("SLV", self.directory) + self.assertIn(b",SLV,", source) + with self.assertRaises(ValueError): + latest_import("GLD", self.directory) + + def test_symbols_must_be_plain_tickers(self): + for bad in ("gld", "GLD;rm", "../GLD", "TOOLONG"): + with self.subTest(symbol=bad), self.assertRaisesRegex(ValueError, "ticker"): + import_symbol(bad, date(2026, 1, 2), date(2026, 1, 2), "k", self.directory) + + def test_pruning_keeps_the_newest_imports_of_that_symbol_only(self): + start = date(2004, 11, 18) + ends = [date(2026, 9, day) for day in (21, 22, 23, 24, 25)] + for end in ends: + save_import(self.directory, "GLD", b"x", start, end) + save_import(self.directory, "SLV", b"y", start, ends[0]) + archive = self.directory / "superseded" + archive.mkdir() + for stamp in ("20260921", "20260922", "20260923", "20260924"): + (archive / f"{stamp}-GLD-20041118-20260925.csv").write_bytes(b"old") + (archive / "20260920-SLV-20041118-20260925.csv").write_bytes(b"old") + deleted = prune_imports("GLD", self.directory, keep=3) + remaining = sorted(path.name for path in self.directory.glob("GLD-*.manifest.json")) + self.assertEqual(remaining, [f"GLD-20041118-2026092{day}.manifest.json" + for day in (3, 4, 5)]) + self.assertEqual(len(deleted), 2 * 3 + 1) + self.assertTrue((self.directory / "SLV-20041118-20260921.csv").exists()) + self.assertTrue((archive / "20260920-SLV-20041118-20260925.csv").exists()) + self.assertFalse((archive / "20260921-GLD-20041118-20260925.csv").exists()) + with self.assertRaises(ValueError): + prune_imports("GLD", self.directory, keep=0) + + +class UniverseTests(unittest.TestCase): + def test_adjusted_prices_include_dividends(self): + days = weekdays(date(2020, 1, 6), 10) + history = parse_adjusted_csv(tiingo_csv("SPY", days, dividend_on=days[5]), "SPY") + self.assertEqual(history.dividends, 1) + self.assertEqual(history.bars[0].close, Decimal(100) * Decimal("0.98")) + self.assertEqual(history.raw_close[days[0]], Decimal(100)) + self.assertEqual(history.bars[5].close, Decimal(105)) + with self.assertRaisesRegex(ValueError, "is for SPY"): + parse_adjusted_csv(tiingo_csv("SPY", days), "IEF") + + def test_alignment_trims_edges_and_refuses_gaps(self): + days = weekdays(date(2010, 1, 4), MIN_COMMON_BARS + 40) + early = parse_adjusted_csv(tiingo_csv("GLD", days), "GLD") + late = parse_adjusted_csv(tiingo_csv("SLV", days[20:]), "SLV") + short = parse_adjusted_csv(tiingo_csv("DBC", days[:-5]), "DBC") + universe = align([early, late, short]) + self.assertEqual(universe.dates, days[20:-5]) + self.assertEqual({len(universe.bars(s)) for s in universe.symbols}, {len(days) - 25}) + gap_days = [day for day in days if day != days[100]] + gappy = parse_adjusted_csv(tiingo_csv("IEF", gap_days), "IEF") + with self.assertRaisesRegex(ValueError, f"IEF is missing 1 day.*{days[100]}"): + align([early, gappy]) + tiny = parse_adjusted_csv(tiingo_csv("SPY", days[:100]), "SPY") + with self.assertRaisesRegex(ValueError, "common days"): + align([early, tiny]) + + def test_loads_every_registered_symbol_and_hashes_the_inputs(self): + days = weekdays(date(2010, 1, 4), MIN_COMMON_BARS + 10) + with tempfile.TemporaryDirectory() as name: + directory = Path(name) + for symbol in UNIVERSE: + save_import(directory, symbol, tiingo_csv(symbol, days), days[0], days[-1]) + universe = load_universe(directory) + self.assertEqual(universe.symbols, UNIVERSE) + self.assertEqual(load_universe(directory).sha256, universe.sha256) + save_import(directory, "SPY", tiingo_csv("SPY", days, days[3]), days[0], + days[-1] + timedelta(days=7)) + self.assertNotEqual(load_universe(directory).sha256, universe.sha256) + + +if __name__ == "__main__": + unittest.main() diff --git a/tradenow/__main__.py b/tradenow/__main__.py index 7b79406..a6b1390 100644 --- a/tradenow/__main__.py +++ b/tradenow/__main__.py @@ -27,6 +27,7 @@ from .paper_auto import GLD_HISTORY_START, Notices, paper_auto from .paper_trading import ( PaperStore, + _jsonable, paper_halt, paper_plan, paper_report, @@ -39,7 +40,8 @@ from .settings import load_settings from .simulation import Config, simulate from .stress import run_stress, save_stress -from .tiingo import import_complete, import_gld, load_api_key +from .tiingo import import_complete, import_gld, import_symbol, load_api_key +from .universe import UNIVERSE, describe, load_universe def _fail(run: Run, error: BaseException) -> int: @@ -133,17 +135,62 @@ def web_main(argv: list[str], run: Run) -> int: def tiingo_main(argv: list[str], run: Run) -> int: - parser = argparse.ArgumentParser(description="Manually import private GLD daily data from Tiingo") + parser = argparse.ArgumentParser(description="Manually import private daily data from Tiingo") parser.add_argument("--start", required=True, type=date.fromisoformat, help="First requested date (YYYY-MM-DD)") parser.add_argument("--end", required=True, type=date.fromisoformat, help="Last requested date (YYYY-MM-DD)") + which = parser.add_mutually_exclusive_group() + which.add_argument("--symbols", help="Comma-separated tickers (default: GLD)") + which.add_argument("--universe", action="store_true", + help=f"All registered symbols: {', '.join(UNIVERSE)}") args = parser.parse_args(argv) + symbols = (list(UNIVERSE) if args.universe else + [item.strip().upper() for item in args.symbols.split(",")] if args.symbols + else ["GLD"]) + if len(symbols) == 1: + try: + result = import_symbol(symbols[0], args.start, args.end, load_api_key()) + except (OSError, ValueError) as error: + return _fail(run, error) + _emit(run, result) + return 0 + # Several symbols: stop at the first failure (a rate limit must not be retried) + # and still report what was imported before it. + results: dict[str, object] = {} try: - result = import_gld(args.start, args.end, load_api_key()) + key = load_api_key() + for symbol in symbols: + if import_complete(args.start, args.end, symbol=symbol): + results[symbol] = {"result": "ALREADY_COMPLETE"} + continue + results[symbol] = {name: value for name, value in + import_symbol(symbol, args.start, args.end, key).items() + if name in ("result", "bars", "first_bar", "last_bar", + "pruned_files")} + except (OSError, ValueError) as error: + _emit(run, {"result": "STOPPED", "error": str(error), "symbols": results}) + run.fail(error) + return 1 + summary: dict[str, object] = {"result": "IMPORTED", "symbols": results} + if args.universe: + try: + summary["universe"] = describe(load_universe()) + except (OSError, ValueError) as error: + summary["universe"] = {"error": str(error)} + _emit(run, _jsonable(summary)) + return 0 + + +def universe_main(argv: list[str], run: Run) -> int: + """Check that the latest imports of the registered symbols align, offline.""" + argparse.ArgumentParser(prog="tradenow universe", + description="Summarize the aligned multi-asset history").parse_args(argv) + try: + result = describe(load_universe()) except (OSError, ValueError) as error: return _fail(run, error) - _emit(run, result) + _emit(run, _jsonable(result)) return 0 @@ -319,7 +366,7 @@ def notify_test_main(argv: list[str], run: Run) -> int: COMMANDS = {"offline": offline_main, "stress": stress_main, "web": web_main, "tiingo-import": tiingo_main, "gld": gld_main, "notify-test": notify_test_main, - "features": features_main} + "features": features_main, "universe": universe_main} def main(argv: list[str] | None = None) -> int: diff --git a/tradenow/gld_research.py b/tradenow/gld_research.py index ef27ca4..63b2380 100644 --- a/tradenow/gld_research.py +++ b/tradenow/gld_research.py @@ -3,7 +3,6 @@ import csv import hashlib import json -import re from datetime import date from decimal import Decimal, InvalidOperation from io import StringIO @@ -20,7 +19,7 @@ split_rows, ) from .strategies import GLD_CANDIDATES, Candidate -from .tiingo import PRIVATE_DIR +from .tiingo import PRIVATE_DIR, latest_import MAX_GLD_CSV_BYTES = 2_000_000 @@ -156,21 +155,7 @@ def run_gld_csv(source_bytes: bytes, filename: str = "GLD.csv", def latest_imported_gld(directory: Path = PRIVATE_DIR) -> tuple[bytes, str]: """Load the newest private import only if its manifest matches the CSV.""" - manifests = [path for path in directory.glob("GLD-*.manifest.json") - if re.fullmatch(r"GLD-\d{8}-\d{8}\.manifest\.json", path.name)] - if not manifests: - raise ValueError("No private GLD import found; run tiingo-import first") - manifest_path = max(manifests, key=lambda path: (path.name[13:21], path.name[4:12])) - manifest = json.loads(manifest_path.read_text(encoding="utf-8")) - if manifest.get("provider") != "Tiingo" or manifest.get("symbol") != "GLD": - raise ValueError("GLD import manifest is invalid") - csv_path = manifest_path.with_name(manifest_path.name.replace(".manifest.json", ".csv")) - if csv_path.stat().st_size > MAX_GLD_CSV_BYTES: - raise ValueError("Private GLD import exceeds size limit") - source_bytes = csv_path.read_bytes() - if hashlib.sha256(source_bytes).hexdigest() != manifest.get("bars_sha256"): - raise ValueError("Private GLD CSV does not match its import manifest") - return source_bytes, csv_path.name + return latest_import("GLD", directory, MAX_GLD_CSV_BYTES) def _na(value: str | None, suffix: str = "") -> str: diff --git a/tradenow/tiingo.py b/tradenow/tiingo.py index c3046d6..bcfe64f 100644 --- a/tradenow/tiingo.py +++ b/tradenow/tiingo.py @@ -1,4 +1,9 @@ -"""Manual, GLD-only import from Tiingo's free end-of-day endpoints.""" +"""Manual imports from Tiingo's free end-of-day endpoints, one symbol at a time. + +Each import saves the raw response, a normalized CSV with raw and adjusted +prices, and a manifest with SHA-256 hashes. Refreshing a range is allowed only +while it is incomplete, and never when earlier raw bars were revised. +""" import csv import hashlib @@ -19,6 +24,9 @@ PRIVATE_DIR = SETTINGS.tiingo_dir +SYMBOL = re.compile(r"[A-Z]{1,5}") +# Completed imports kept per symbol; older ones are deleted after each import. +KEEP_IMPORTS = 3 logger = logging.getLogger(__name__) MAX_RESPONSE_BYTES = 10_000_000 RAW_FIELDS = ("open", "high", "low", "close", "volume") @@ -92,9 +100,16 @@ def _volume(value: object, field: str) -> int: return value -def _normalize_prices(payload: object, start: date, end: date) -> tuple[bytes, int, date, date]: +def _check_symbol(symbol: str) -> str: + if not SYMBOL.fullmatch(symbol): + raise ValueError(f"Invalid ticker symbol {symbol!r}") + return symbol + + +def _normalize_prices(payload: object, start: date, end: date, + symbol: str = "GLD") -> tuple[bytes, int, date, date]: if not isinstance(payload, list) or not payload or len(payload) > 10_000: - raise ValueError("Tiingo returned no usable GLD daily bars") + raise ValueError(f"Tiingo returned no usable {symbol} daily bars") output = StringIO(newline="") writer = csv.writer(output, lineterminator="\n") writer.writerow(HEADER) @@ -102,23 +117,23 @@ def _normalize_prices(payload: object, start: date, end: date) -> tuple[bytes, i first: date | None = None for item in payload: if not isinstance(item, dict): - raise ValueError("Tiingo returned a malformed GLD bar") + raise ValueError(f"Tiingo returned a malformed {symbol} bar") bar_date = _day(item.get("date")) if (bar_date < start or bar_date > end or bar_date.weekday() >= 5 or previous is not None and bar_date <= previous): - raise ValueError("Tiingo returned an out-of-range or unordered GLD date") + raise ValueError(f"Tiingo returned an out-of-range or unordered {symbol} date") raw = [_decimal(item.get(field), field) for field in ("open", "high", "low", "close")] adjusted = [_decimal(item.get(field), field) for field in ("adjOpen", "adjHigh", "adjLow", "adjClose")] for prices in (raw, adjusted): if prices[2] > min(prices[0], prices[3]) or prices[1] < max(prices[0], prices[3]): - raise ValueError("Tiingo returned an invalid GLD OHLC range") + raise ValueError(f"Tiingo returned an invalid {symbol} OHLC range") volume = _volume(item.get("volume"), "volume") adj_volume = _volume(item.get("adjVolume"), "adjVolume") dividend = _decimal(item.get("divCash"), "divCash", positive=False) split = _decimal(item.get("splitFactor"), "splitFactor") - writer.writerow((bar_date.isoformat(), "GLD", *(str(price) for price in raw), + writer.writerow((bar_date.isoformat(), symbol, *(str(price) for price in raw), volume, *(str(price) for price in adjusted), adj_volume, str(dividend), str(split))) first = first or bar_date @@ -133,7 +148,8 @@ def _raw_rows(csv_bytes: bytes) -> dict[str, tuple[Decimal, ...]]: return {row["date"]: tuple(Decimal(row[field]) for field in RAW_FIELDS) for row in rows} -def _previous_import(paths: tuple[Path, Path, Path], end: date) -> tuple[dict, bytes] | None: +def _previous_import(paths: tuple[Path, Path, Path], end: date, + symbol: str = "GLD") -> tuple[dict, bytes] | None: """The earlier import of this exact range, if it may be refreshed. A complete import (its last bar is the requested end) is final and is @@ -151,10 +167,11 @@ def _previous_import(paths: tuple[Path, Path, Path], end: date) -> tuple[dict, b csv_bytes = bars_path.read_bytes() if (not isinstance(manifest, dict) or hashlib.sha256(csv_bytes).hexdigest() != manifest.get("bars_sha256")): - raise ValueError("The earlier GLD import does not match its manifest; " + raise ValueError(f"The earlier {symbol} import does not match its manifest; " "no API request was made") if _day(manifest.get("last_bar")) >= end: - raise ValueError("This GLD date range is already imported; no API request was made") + raise ValueError(f"This {symbol} date range is already imported; " + "no API request was made") return manifest, csv_bytes @@ -179,15 +196,17 @@ def _replace_import(paths: tuple[Path, Path, Path], contents: tuple[bytes, bytes os.replace(temporary, path) -def _paths(start: date, end: date, output_dir: Path) -> tuple[Path, Path, Path]: - stem = f"GLD-{start:%Y%m%d}-{end:%Y%m%d}" +def _paths(start: date, end: date, output_dir: Path, + symbol: str = "GLD") -> tuple[Path, Path, Path]: + stem = f"{_check_symbol(symbol)}-{start:%Y%m%d}-{end:%Y%m%d}" return (output_dir / f"{stem}.csv", output_dir / f"{stem}.raw.json", output_dir / f"{stem}.manifest.json") -def import_complete(start: date, end: date, output_dir: Path = PRIVATE_DIR) -> bool: +def import_complete(start: date, end: date, output_dir: Path = PRIVATE_DIR, + symbol: str = "GLD") -> bool: """True when this range was already imported through its end date (no request needed).""" - manifest_path = _paths(start, end, output_dir)[2] + manifest_path = _paths(start, end, output_dir, symbol)[2] try: manifest = json.loads(manifest_path.read_text(encoding="utf-8")) return _day(manifest.get("last_bar")) >= end @@ -195,32 +214,99 @@ def import_complete(start: date, end: date, output_dir: Path = PRIVATE_DIR) -> b return False +def _manifests(symbol: str, directory: Path) -> list[tuple[str, str, Path]]: + """(end, start, path) for each import of a symbol, newest range first.""" + pattern = re.compile(rf"{_check_symbol(symbol)}-(\d{{8}})-(\d{{8}})\.manifest\.json") + found = [] + for path in directory.glob(f"{symbol}-*.manifest.json"): + match = pattern.fullmatch(path.name) + if match: + found.append((match.group(2), match.group(1), path)) + return sorted(found, reverse=True) + + +def latest_import(symbol: str, directory: Path = PRIVATE_DIR, + max_bytes: int = 2_000_000) -> tuple[bytes, str]: + """The newest import of a symbol, only if its CSV matches its manifest.""" + manifests = _manifests(symbol, directory) + if not manifests: + raise ValueError(f"No private {symbol} import found; run tiingo-import first") + manifest_path = manifests[0][2] + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if manifest.get("provider") != "Tiingo" or manifest.get("symbol") != symbol: + raise ValueError(f"{symbol} import manifest is invalid") + csv_path = manifest_path.with_name(manifest_path.name.replace(".manifest.json", ".csv")) + if csv_path.stat().st_size > max_bytes: + raise ValueError(f"Private {symbol} import exceeds size limit") + source_bytes = csv_path.read_bytes() + if hashlib.sha256(source_bytes).hexdigest() != manifest.get("bars_sha256"): + raise ValueError(f"Private {symbol} CSV does not match its import manifest") + return source_bytes, csv_path.name + + +def prune_imports(symbol: str, directory: Path = PRIVATE_DIR, + keep: int = KEEP_IMPORTS) -> list[str]: + """Delete all but the newest `keep` imports of a symbol, and superseded copies + beyond the newest `keep`. Only exact files of this symbol are ever touched.""" + if keep < 1: + raise ValueError("At least one import must be kept") + deleted: list[str] = [] + for _, _, manifest_path in _manifests(symbol, directory)[keep:]: + stem = manifest_path.name[:-len(".manifest.json")] + for suffix in (".csv", ".raw.json", ".manifest.json"): + path = directory / f"{stem}{suffix}" + if path.exists(): + path.unlink() + deleted.append(path.name) + archive = directory / "superseded" + if archive.is_dir(): + pattern = re.compile(rf"(\d+|unknown)-{symbol}-\d{{8}}-\d{{8}}\.(csv|raw\.json|manifest\.json)") + groups: dict[str, list[Path]] = {} + for path in archive.iterdir(): + match = pattern.fullmatch(path.name) + if match: + groups.setdefault(path.name.split(".")[0], []).append(path) + for name in sorted(groups, reverse=True)[keep:]: + for path in groups[name]: + path.unlink() + deleted.append(f"superseded/{path.name}") + if deleted: + logger.info("pruned %d old %s import files", len(deleted), symbol) + return deleted + + def import_gld(start: date, end: date, key: str, output_dir: Path = PRIVATE_DIR) -> dict: + return import_symbol("GLD", start, end, key, output_dir) + + +def import_symbol(symbol: str, start: date, end: date, key: str, + output_dir: Path = PRIVATE_DIR) -> dict: """Fetch one symbol with two requests, validate, then save private source files. Importing a range again is allowed only while the earlier import stops short of the requested end. The new data must contain a newer bar and leave every earlier raw bar unchanged; otherwise nothing is written. """ + _check_symbol(symbol) if start > end or end > date.today(): raise ValueError("Expected start <= end <= today") - paths = _paths(start, end, output_dir) + paths = _paths(start, end, output_dir, symbol) bars_path, raw_path, manifest_path = paths - previous = _previous_import(paths, end) + previous = _previous_import(paths, end, symbol) - base_url = "https://api.tiingo.com/tiingo/daily/GLD" + base_url = f"https://api.tiingo.com/tiingo/daily/{symbol}" metadata, _ = _get_json(base_url, key) - if not isinstance(metadata, dict) or metadata.get("ticker") != "GLD": - raise ValueError("Tiingo did not confirm GLD EOD coverage") + if not isinstance(metadata, dict) or str(metadata.get("ticker", "")).upper() != symbol: + raise ValueError(f"Tiingo did not confirm {symbol} EOD coverage") available_start = _day(metadata.get("startDate")) available_end = _day(metadata.get("endDate")) if end < available_start or start > available_end: - raise ValueError("Requested range is outside Tiingo's GLD coverage") + raise ValueError(f"Requested range is outside Tiingo's {symbol} coverage") query = urlencode({"startDate": start.isoformat(), "endDate": end.isoformat()}) prices, raw = _get_json(f"{base_url}/prices?{query}", key) - csv_bytes, count, first, last = _normalize_prices(prices, start, end) - manifest = {"provider": "Tiingo", "product": "EOD", "symbol": "GLD", + csv_bytes, count, first, last = _normalize_prices(prices, start, end, symbol) + manifest = {"provider": "Tiingo", "product": "EOD", "symbol": symbol, "requested_start": start.isoformat(), "requested_end": end.isoformat(), "provider_start": available_start.isoformat(), "provider_end": available_end.isoformat(), @@ -234,17 +320,18 @@ def import_gld(start: date, end: date, key: str, output_dir: Path = PRIVATE_DIR) previous_manifest, previous_bytes = previous previous_last = _day(previous_manifest.get("last_bar")) if last <= previous_last: - logger.info("Tiingo has no GLD bar after %s yet; kept the earlier import", - previous_last) - return {"symbol": "GLD", "result": "UNCHANGED", "bars": previous_manifest.get("bars"), + logger.info("Tiingo has no %s bar after %s yet; kept the earlier import", + symbol, previous_last) + return {"symbol": symbol, "result": "UNCHANGED", + "bars": previous_manifest.get("bars"), "last_bar": previous_last.isoformat(), "previous_last_bar": previous_last.isoformat(), "bars_file": str(bars_path), - "detail": f"Tiingo has no GLD bar after {previous_last} yet; " + "detail": f"Tiingo has no {symbol} bar after {previous_last} yet; " "nothing was written. Try again later."} revised = _revised_dates(previous_bytes, csv_bytes) if revised: - raise ValueError("Tiingo revised earlier GLD bars (" + ", ".join(revised[:5]) + raise ValueError(f"Tiingo revised earlier {symbol} bars (" + ", ".join(revised[:5]) + "); the earlier import was kept. Review the change before " "importing again.") manifest["replaces_fetched_at_utc"] = previous_manifest.get("fetched_at_utc") @@ -253,10 +340,12 @@ def import_gld(start: date, end: date, key: str, output_dir: Path = PRIVATE_DIR) _replace_import(paths, (csv_bytes, raw, (json.dumps(manifest, indent=2) + "\n").encode("utf-8")), None if previous is None else previous[0]) - logger.info("GLD import %s through %s", result.lower(), last, + logger.info("%s import %s through %s", symbol, result.lower(), last, extra={"fields": {"bars": count, "bars_sha256": manifest["bars_sha256"]}}) - return {"symbol": "GLD", "result": result, "bars": count, + pruned = prune_imports(symbol, output_dir) + return {"symbol": symbol, "result": result, "bars": count, "previous_last_bar": None if previous is None else previous[0].get("last_bar"), "first_bar": manifest["first_bar"], "last_bar": manifest["last_bar"], "bars_sha256": manifest["bars_sha256"], - "bars_file": str(bars_path), "manifest_file": str(manifest_path)} + "bars_file": str(bars_path), "manifest_file": str(manifest_path), + "pruned_files": len(pruned)} diff --git a/tradenow/universe.py b/tradenow/universe.py new file mode 100644 index 0000000..1f51607 --- /dev/null +++ b/tradenow/universe.py @@ -0,0 +1,149 @@ +"""The registered multi-asset universe (ADR-011) and its aligned price history. + +Research uses Tiingo's dividend- and split-adjusted prices, so holding an ETF +earns its total return. Raw closes are kept beside them for execution checks. +All symbols must share one trading calendar: the history is trimmed to the +range every symbol covers, and a day missing for any symbol inside that range +is an error, never filled in. +""" + +import csv +import hashlib +from dataclasses import dataclass +from datetime import date +from decimal import Decimal, InvalidOperation +from io import StringIO +from pathlib import Path + +from .equity_types import EquityBar +from .tiingo import PRIVATE_DIR, latest_import + + +UNIVERSE = ("GLD", "SLV", "SPY", "EFA", "IEF", "DBC") +MAX_CSV_BYTES = 3_000_000 +# Enough for one 504/126/126-bar rolling window (ADR-011). +MIN_COMMON_BARS = 756 +REQUIRED = ("date", "symbol", "open", "high", "low", "close", "volume", + "adj_open", "adj_high", "adj_low", "adj_close", "adj_volume", + "div_cash", "split_factor") + + +@dataclass(frozen=True) +class AssetHistory: + symbol: str + bars: list[EquityBar] # adjusted OHLC, raw volume + raw_close: dict[date, Decimal] + dividends: int + splits: int + sha256: str + source_name: str + + +@dataclass(frozen=True) +class Universe: + symbols: tuple[str, ...] + dates: list[date] + assets: dict[str, AssetHistory] # every asset's bars share exactly `dates` + sha256: str # identifies the combined inputs + + def bars(self, symbol: str) -> list[EquityBar]: + return self.assets[symbol].bars + + +def parse_adjusted_csv(source_bytes: bytes, symbol: str, + source_name: str = "") -> AssetHistory: + """One symbol's Tiingo CSV as adjusted daily bars.""" + if len(source_bytes) > MAX_CSV_BYTES: + raise ValueError(f"{symbol} CSV exceeds {MAX_CSV_BYTES} bytes") + try: + reader = csv.DictReader(StringIO(source_bytes.decode("utf-8-sig"))) + except UnicodeDecodeError: + raise ValueError(f"{symbol} CSV must be UTF-8 encoded") from None + if not reader.fieldnames or not set(REQUIRED).issubset(reader.fieldnames): + raise ValueError(f"{symbol} CSV must contain Tiingo raw and adjusted daily columns") + bars: list[EquityBar] = [] + raw_close: dict[date, Decimal] = {} + dividends = splits = 0 + for number, row in enumerate(reader, start=2): + try: + day = date.fromisoformat(row["date"]) + raw = [Decimal(row[name]) for name in ("open", "high", "low", "close")] + adjusted = [Decimal(row[name]) for name in + ("adj_open", "adj_high", "adj_low", "adj_close")] + volume = int(row["volume"]) + dividend, split = Decimal(row["div_cash"]), Decimal(row["split_factor"]) + except (TypeError, ValueError, InvalidOperation): + raise ValueError(f"Invalid {symbol} CSV row {number}") from None + if row["symbol"] != symbol: + raise ValueError(f"{symbol} CSV row {number} is for {row['symbol']}") + for prices in (raw, adjusted): + if (any(not price.is_finite() or price <= 0 for price in prices) + or prices[2] > min(prices[0], prices[3]) + or prices[1] < max(prices[0], prices[3])): + raise ValueError(f"Invalid {symbol} prices on row {number}") + if volume < 0 or not dividend.is_finite() or dividend < 0 or not split > 0: + raise ValueError(f"Invalid {symbol} volume or corporate action on row {number}") + if day.weekday() >= 5 or (bars and day <= bars[-1].date): + raise ValueError(f"{symbol} dates must be increasing weekdays (row {number})") + dividends += dividend > 0 + splits += split != 1 + bars.append(EquityBar(day, symbol, adjusted[0], adjusted[1], adjusted[2], + adjusted[3], volume)) + raw_close[day] = raw[3] + if not bars: + raise ValueError(f"{symbol} CSV has no bars") + return AssetHistory(symbol, bars, raw_close, dividends, splits, + hashlib.sha256(source_bytes).hexdigest(), source_name) + + +def align(histories: list[AssetHistory]) -> Universe: + """Trim every history to the common range and require identical trading days.""" + if not histories: + raise ValueError("No symbols to align") + start = max(history.bars[0].date for history in histories) + end = min(history.bars[-1].date for history in histories) + if start > end: + raise ValueError("The symbols have no dates in common") + trimmed = {history.symbol: [bar for bar in history.bars if start <= bar.date <= end] + for history in histories} + calendar = sorted({bar.date for bars in trimmed.values() for bar in bars}) + problems = [] + for symbol, bars in trimmed.items(): + missing = sorted(set(calendar) - {bar.date for bar in bars}) + if missing: + problems.append(f"{symbol} is missing {len(missing)} day(s), first " + + ", ".join(day.isoformat() for day in missing[:3])) + if problems: + raise ValueError("Symbols do not share one trading calendar: " + "; ".join(problems)) + if len(calendar) < MIN_COMMON_BARS: + raise ValueError(f"Only {len(calendar)} common days; at least {MIN_COMMON_BARS} " + "are needed for one rolling window") + assets = {history.symbol: AssetHistory( + history.symbol, trimmed[history.symbol], + {day: close for day, close in history.raw_close.items() if start <= day <= end}, + history.dividends, history.splits, history.sha256, history.source_name) + for history in histories} + combined = hashlib.sha256("".join(f"{history.symbol}:{history.sha256}\n" + for history in histories).encode()).hexdigest() + return Universe(tuple(history.symbol for history in histories), calendar, assets, + combined) + + +def load_universe(directory: Path = PRIVATE_DIR, + symbols: tuple[str, ...] = UNIVERSE) -> Universe: + """The newest verified import of every symbol, aligned.""" + histories = [] + for symbol in symbols: + source, name = latest_import(symbol, directory, MAX_CSV_BYTES) + histories.append(parse_adjusted_csv(source, symbol, name)) + return align(histories) + + +def describe(universe: Universe) -> dict: + """A short summary for the command line.""" + return {"symbols": list(universe.symbols), "first_date": universe.dates[0], + "last_date": universe.dates[-1], "common_days": len(universe.dates), + "sha256": universe.sha256, + "assets": {symbol: {"source": asset.source_name, "sha256": asset.sha256, + "dividends": asset.dividends, "splits": asset.splits} + for symbol, asset in universe.assets.items()}} From b603cbe8bc595e5bafd2108647773fa5d07edce1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 27 Sep 2026 17:00:33 +0000 Subject: [PATCH 3/3] Add CLAUDE.md for local Claude Code sessions Records the project's non-negotiable rules (paper only, the live-trading gate, register before testing, no look-ahead, private secrets), the commands, the code map, conventions, current status including the GLD result, and where to resume: MA3, the portfolio simulator of ADR-011. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fx8W9jDiTaGhDRbiq7Hgm5 --- CLAUDE.md | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 CLAUDE.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..18bee48 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,132 @@ +# TradeNow: notes for Claude Code + +A research and **paper-trading-only** system for gold and a small ETF universe. +It imports daily bars from Tiingo, tests rule-based strategies without +look-ahead, and trades an Alpaca **paper** account. There is no live mode. + +The owner works on Windows (PowerShell) in +`C:\Users\muhammad tahub\Downloads\Projects\Tradenow`, runs the scheduled +`paper-auto` there, and prefers a plan in plain language before larger +changes. When asked for a plan only, do not implement. + +## Rules that are never broken + +1. **Paper only.** Never add a live endpoint or mode. `TRADENOW_MODE` accepts + only `paper`, and the Alpaca client accepts only the paper URL. +2. **The live-trading gate (ADR-008, `docs/decisions.md`).** No real money + unless a strategy beats plain buy-and-hold out of sample, after costs, over + enough trades, historically **and** in a year of forward paper trading. + Thresholds may be tightened, never loosened, without a new ADR written + before the results it would affect. +3. **Register before testing (ADR-010, ADR-011).** Candidates, parameters, + benchmarks, and pass criteria are fixed in an ADR before any result exists. + Never tune or re-run registered candidates after seeing their results; a + new idea needs a new ADR and counts as more trials. +4. **No look-ahead.** Strategies read history only through `History` + (`tradenow/strategies.py`), which cannot index past today. Features are + point-in-time and a test proves it. +5. **Secrets stay private.** Keys live in the ignored `.env.local`. They are + never written to logs (`logs.register_secret` redacts them), plans, reports, + commits, or notifications. `data/private/` and `artifacts/` are git-ignored. +6. **Be honest about odds.** The GLD strategies failed the gate. Do not present + anything as likely to make money, and do not give financial advice. + +## Commands + +```powershell +python -m pip install -e ".[dev,web]" # ruff and mypy are pinned in the dev extra +ruff check tradenow tests +mypy +python -m unittest discover -s tests -v # CI runs these three on Ubuntu and Windows +``` + +Main CLI (`python -m tradenow `): + +- Data: `tiingo-import --start D --end D [--symbols A,B | --universe]` and + `universe` (aligned six-ETF history). +- Research: `gld` (12 registered GLD candidates plus the gate verdict) and + `features --date D`. +- Paper trading: `paper-plan`, `paper-submit --approve ID`, `paper-status`, + `paper-report`, `paper-halt`, `paper-resume --confirm`, and + `paper-auto [--dry-run | --check]`. +- Other: `notify-test`, and `web` (the dashboard). +- `scripts/schedule-windows.ps1` registers the Windows scheduled tasks. + +Every command appends one line to `data/private/logs/runs.jsonl`. + +## Where things are + +- `data/private/` (set with `TRADENOW_DATA_DIR`) holds `tiingo/` imports, + `alpaca/` (ledger, plans, kill switch, equity history, `live_gate.json`), + `logs/`, `experiments.jsonl`, and optional `risk.toml`. Copy + `risk.example.toml` to create it. Without it the defaults apply: 50% + position, 2% daily loss, 10% drawdown, `auto_submit = false`. +- Research core: `equity_types.py`, `features.py` (`gld_features_v2`), + `strategies.py` (interface and `GLD_CANDIDATES`), `selection.py` (single + selection rule, `RESEARCH_CONFIG` at the 100% cap), `equity.py` + (single-asset simulator), `gld_research.py` and `gld_evaluation.py`, + `metrics.py`, `live_gate.py`, and `experiments.py`. +- Multi-asset data: `tiingo.py` (`import_symbol`, `prune_imports`, + `latest_import`) and `universe.py` (`UNIVERSE`, adjusted prices, + `align`, `load_universe`). +- Paper trading: `alpaca_paper.py` (adapter), `paper_rules.py` (pure rules), + `paper_trading.py` (orchestration and store), `paper_auto.py`, + `risk_config.py`, `notify.py`, and `execution_quality.py`. +- The MGC futures files (`simulation.py`, `offline.py`, `stress.py`, + `market_data.py`, `synthetic.py`) are the older synthetic workflow. Leave + them alone unless asked. + +## Conventions + +- Money and prices are `Decimal`, never float. Pure rules are separate from + I/O so they can be tested without the network. +- Every change comes with tests. `tests/test_strategies.py` holds golden + SHA-256 hashes of pre-refactor outputs, so a failure there means a result + changed. Investigate; never simply re-bless the hashes. +- Identical inputs must give byte-identical reports (tested). +- Keep ruff and mypy clean and CI green on both operating systems. +- Commits have short imperative subjects with a body explaining why. Work on a + branch and merge through a pull request. + +## Status (2026-09-27) + +- Phases 0 to 5 are done. Phase 6 (unattended paper trading) is built and + running as a dry run on the owner's PC. It passes after 20 unattended + sessions with no reconciliation failures. +- **GLD research (ADR-010) failed the gate:** +15.6% compounded across 29 + rolling windows against +158.7% for holding GLD. That is final. +- **Multi-asset research (ADR-011) is registered:** six ETFs (GLD, SLV, SPY, + EFA, IEF, DBC), dividend-adjusted prices from spring 2006, and 6 candidates + (`mom`, `trend`, `both` × `eq`, `iv35`). Rebalancing is monthly. The gate + is the strictest option: beat **both** an equal-weight buy-and-hold of the + six **and** SPY on return, with no larger drawdown (R1 to R5, then F1 to F4). +- MA1 (ADR-011) and MA2 (multi-symbol data pipeline) are done. + +## Next: MA3, the portfolio simulator (read ADR-011 first) + +Build `tradenow/portfolio.py`: + +- Cash plus up to six positions in whole shares, never margin, total weight + at most 100%. +- Monthly rebalance: target weights from the month's last close, orders at + the next open. Sells before buys. An asset trades only if its target + differs by more than 1% of equity. +- $0.01 slippage per share, zero commission (stress test $0.10), and a 10% + portfolio drawdown halt checked daily. +- Per-asset and portfolio metrics through `metrics.py`. +- Benchmarks B1 (equal-weight buy-and-hold of the six, rebalanced monthly, + same costs) and B2 (100% SPY). +- Tests use synthetic data only. No multi-asset result on real data exists + until MA5. + +Then: + +- **MA4:** the six strategies (per-asset weights, inverse-volatility sizing + over 60-day volatility capped at 35%), selection and rolling windows + (504/126/126), gate checks R1 to R5, and a `multi` command writing a report + and an experiment record. +- **MA5:** the owner runs `multi` once on real data, and the result is + recorded in ADR-011. +- **MA6:** only if R1 to R5 pass, multi-asset paper trading (a new ADR), + then a year of forward testing. If they fail, stop or register Phase 7 in + a new ADR.