Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro

fix/nan-prices-cli-demo-mode
py 57 lines 1.76 KB
Raw
1 """Market data fetching and caching."""
2
3 from __future__ import annotations
4
5 import numpy as np
6 import pandas as pd
7 import yfinance as yf
8
9
10 def fetch_ohlcv(
11 symbol: str,
12 period: str = "1y",
13 interval: str = "1d",
14 ) -> pd.DataFrame:
15 """Fetch OHLCV data for a symbol via yfinance.
16
17 Args:
18 symbol: Ticker symbol (e.g. "AAPL", "BTC-USD").
19 period: Data period ("1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max").
20 interval: Bar interval ("1m", "5m", "15m", "1h", "1d", "1wk", "1mo").
21
22 Returns:
23 DataFrame with columns: Open, High, Low, Close, Volume.
24 """
25 ticker = yf.Ticker(symbol)
26 raw = ticker.history(period=period, interval=interval, auto_adjust=True)
27 if raw.empty:
28 raise ValueError(f"No data returned for symbol: {symbol}")
29 df = pd.DataFrame(raw)
30 df.index = pd.DatetimeIndex(df.index).tz_localize(None)
31 df = clean_ohlcv(df)
32 if df.empty:
33 raise ValueError(f"No valid price rows for symbol: {symbol}")
34 return df
35
36
37 def clean_ohlcv(df: pd.DataFrame) -> pd.DataFrame:
38 """Drop rows with missing or non-finite OHLC values.
39
40 Providers sometimes return bars with no valid price (for example an
41 incomplete current session). Those rows must never reach the engines,
42 or trades get recorded at NaN prices.
43 """
44 cols = [c for c in ("Open", "High", "Low", "Close") if c in df.columns]
45 if not cols:
46 return df
47 values = df[cols].to_numpy(dtype=float, na_value=np.nan)
48 finite_mask = np.isfinite(values).all(axis=1)
49 result: pd.DataFrame = df[finite_mask]
50 return result
51
52
53 def add_returns(df: pd.DataFrame) -> pd.DataFrame:
54 """Add a simple daily returns column."""
55 result = df.copy()
56 result["Return"] = result["Close"].pct_change()
57 return result