Coverage for data_pipeline/fetch.py: 100%

46 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Ad-hoc historical OHLCV fetch for tickers not (yet) in config.json. 

2 

3Distinct responsibility from yfinance_backfill.py: that module fills gaps in 

4already-configured assets via a config.json "backfill" block, and 

5deliberately never touches config.json (widening an *existing*, already 

6-trained asset's date range is a decision a human should make explicitly). 

7This module fetches an explicit date range for *any* ticker, including ones 

8with no config.json entry at all, and — on --apply — *does* add a new asset 

9block to config.json, because adding a brand-new ticker to the universe is 

10this module's entire purpose, not an accidental side effect. 

11 

12Reuses yfinance_backfill.py's config.json-independent pure functions 

13(fetch_yahoo_ohlcv, scale_for_lean, write_lean_zip, and - V4.10 - the forex 

14sibling write_lean_forex_zip) - no duplicated logic. 

15 

16Never runs `train.py` itself - preparing a ticker for training (fetching 

17its data, formatting it for Lean, wiring it into config.json's universe) is 

18this module's job; actually training on it stays a deliberate, separate 

19step (`python train.py`). 

20""" 

21 

22from __future__ import annotations 

23 

24import json 

25from collections.abc import Callable 

26from pathlib import Path 

27 

28from data_pipeline.yfinance_backfill import ( 

29 fetch_yahoo_ohlcv, 

30 scale_for_lean, 

31 write_lean_forex_zip, 

32 write_lean_zip, 

33) 

34from json_safety import atomic_write_json 

35 

36ROOT = Path(__file__).resolve().parents[1] 

37CONFIG_PATH = ROOT / "config.json" 

38 

39 

40def _crypto_yahoo_symbol(ticker: str) -> str: 

41 """BTCUSD -> BTC-USD, DOGEUSD -> DOGE-USD: strip a trailing USD and join 

42 with a hyphen, matching Yahoo Finance's crypto pair naming convention.""" 

43 base = ticker[:-3] if ticker.upper().endswith("USD") else ticker 

44 return f"{base}-USD" 

45 

46 

47def _forex_yahoo_symbol(ticker: str) -> str: 

48 """EURUSD -> EURUSD=X: Yahoo Finance's FX ticker convention.""" 

49 return f"{ticker}=X" 

50 

51 

52# One entry per asset class - V3's "futures"/"options" entries below prove 

53# the docstring's original claim (adding a class is one new dict entry, not 

54# a redesign): both route through data_pipeline/ib_backfill.py instead of 

55# Yahoo Finance (yahoo_symbol_fn stays identity - not a real Yahoo symbol 

56# for these two, just this dict's "instrument identifier passed to 

57# fetch_fn" slot, reused as-is rather than renamed) and carry an 

58# extra_asset_fields block (asset_class/data_source) merged into the 

59# config.json asset entry fetch_adhoc_asset() writes on --apply, since IB- 

60# backed assets need to be identified by the feature/risk layer 

61# (risk/asset_class_router.py) independently of Lean's own security_type. 

62ASSET_CLASS_CONFIG = { 

63 "crypto": { 

64 "security_type": "crypto", 

65 "market": "coinbase", 

66 "data_path_fn": lambda ticker: ROOT / "data" / "crypto" / "coinbase" / "daily" / f"{ticker.lower()}_trade.zip", 

67 "yahoo_symbol_fn": _crypto_yahoo_symbol, 

68 }, 

69 "stock": { 

70 "security_type": "equity", 

71 "market": "usa", 

72 "data_path_fn": lambda ticker: ROOT / "data" / "equity" / "usa" / "daily" / f"{ticker.lower()}.zip", 

73 "yahoo_symbol_fn": lambda ticker: ticker, 

74 }, 

75 "futures": { 

76 "security_type": "future", 

77 "market": "cme", 

78 "data_path_fn": lambda ticker: ROOT / "data" / "future" / "cme" / "daily" / f"{ticker.lower()}.zip", 

79 "yahoo_symbol_fn": lambda ticker: ticker, 

80 "extra_asset_fields": {"asset_class": "future", "data_source": "ib"}, 

81 }, 

82 "options": { 

83 "security_type": "option", 

84 "market": "usa", 

85 "data_path_fn": lambda ticker: ROOT / "data" / "option" / "usa" / "daily" / f"{ticker.lower()}.zip", 

86 "yahoo_symbol_fn": lambda ticker: ticker, 

87 "extra_asset_fields": {"asset_class": "option", "data_source": "ib"}, 

88 }, 

89 "forex": { 

90 # V4.10 - yfinance-backed (default fetch_fn below, no IB closure 

91 # needed - forex is a fully-wired Lean asset class already, only 

92 # ever blocked by "zero live tickers configured", not IB). market 

93 # standardized on "oanda" - local sample data exists identically 

94 # for both oanda/fxcm today, an arbitrary/low-stakes choice. 

95 # write_fn overrides write_lean_zip() below: Lean's real forex 

96 # daily format is a 10-column bid/ask CSV 

97 # (data/forex/readme.md), not the 5-column mid-price OHLCV shape 

98 # every other asset class here uses. 

99 "security_type": "forex", 

100 "market": "oanda", 

101 "data_path_fn": lambda ticker: ROOT / "data" / "forex" / "oanda" / "daily" / f"{ticker.lower()}.zip", 

102 "yahoo_symbol_fn": _forex_yahoo_symbol, 

103 "write_fn": write_lean_forex_zip, 

104 }, 

105} 

106ASSET_CLASSES = tuple(ASSET_CLASS_CONFIG.keys()) 

107 

108 

109def add_asset_to_config(config_path: Path, asset_block: dict) -> str: 

110 """Appends asset_block to config.json's phase1.universe.assets[] unless 

111 a block with the same ticker already exists there. Returns "added" or 

112 "already_exists". Preserves the file's existing exact formatting 

113 (4-space indent, trailing newline). V5.4.7 (Problems.md #123): the 

114 rewrite is now atomic (temp file + os.replace) - a crash mid-write of 

115 the whole system's config previously left a truncated config.json 

116 behind.""" 

117 config = json.loads(config_path.read_text(encoding="utf-8")) 

118 assets = config["phase1"]["universe"]["assets"] 

119 

120 if any(existing["ticker"] == asset_block["ticker"] for existing in assets): 

121 return "already_exists" 

122 

123 assets.append(asset_block) 

124 atomic_write_json(config_path, config, indent=4) 

125 # Match the historical trailing-newline formatting exactly. 

126 with config_path.open("a", encoding="utf-8") as handle: 

127 handle.write("\n") 

128 return "added" 

129 

130 

131def fetch_adhoc_asset( 

132 asset_class: str, 

133 ticker: str, 

134 start: str, 

135 end: str, 

136 *, 

137 apply: bool, 

138 fetch_fn: Callable = fetch_yahoo_ohlcv, 

139 config_path: Path = CONFIG_PATH, 

140 extra_metadata: dict | None = None, 

141) -> dict: 

142 """apply=False (default): dry run - fetches but writes nothing (no zip, 

143 no config.json edit). apply=True: writes the Lean zip via 

144 write_lean_zip(), then adds a new config.json asset block if this 

145 ticker isn't already configured. fetch_fn is the injection point for 

146 tests (never real yfinance in tests), matching 

147 yfinance_backfill.run_backfill()'s exact convention. 

148 

149 extra_metadata is merged into the written config.json asset block, on 

150 top of class_config["extra_asset_fields"] - the per-fetch-call 

151 complement to that per-asset-class static dict. Used by futures/options 

152 fetches (aq_cli.py::cmd_fetch()) to store strike/expiry/right (options) 

153 and family_ticker (both - defaults to the ticker itself when the 

154 caller doesn't group multiple dated contracts under one family), so 

155 train.py::build_derivatives_macro_features_by_date() can later 

156 recognize and group them for real historical term-structure/put-call- 

157 ratio computation. Ignored (None) for crypto/stock, which need no such 

158 metadata.""" 

159 ticker = ticker.upper() 

160 class_config = ASSET_CLASS_CONFIG[asset_class] 

161 yahoo_symbol = class_config["yahoo_symbol_fn"](ticker) 

162 output_zip = class_config["data_path_fn"](ticker) 

163 security_type = class_config["security_type"] 

164 

165 rows = fetch_fn(yahoo_symbol, start, end) 

166 scaled_rows = scale_for_lean(rows, security_type) 

167 

168 dates = [row["date"] for row in rows] 

169 suggested_from = min(dates) if dates else None 

170 suggested_to = max(dates) if dates else None 

171 

172 config_status = "not_attempted" 

173 if not scaled_rows: 

174 action = "no_data_returned" 

175 elif apply: 

176 write_fn = class_config.get("write_fn", write_lean_zip) 

177 write_fn(output_zip, ticker, scaled_rows, merge_with_existing=True) 

178 action = "written" 

179 config_status = add_asset_to_config( 

180 config_path, 

181 { 

182 "ticker": ticker, 

183 "security_type": security_type, 

184 "market": class_config["market"], 

185 "data_path": output_zip.relative_to(ROOT).as_posix(), 

186 "available_from": suggested_from.isoformat(), 

187 "available_to": suggested_to.isoformat(), 

188 **class_config.get("extra_asset_fields", {}), 

189 **(extra_metadata or {}), 

190 }, 

191 ) 

192 else: 

193 action = "dry_run" 

194 

195 return { 

196 "ticker": ticker, 

197 "asset_class": asset_class, 

198 "yahoo_symbol": yahoo_symbol, 

199 "data_path": str(output_zip), 

200 "action": action, 

201 "rows_fetched": len(rows), 

202 "suggested_available_from": suggested_from.isoformat() if suggested_from else None, 

203 "suggested_available_to": suggested_to.isoformat() if suggested_to else None, 

204 "config_status": config_status, 

205 }