-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
56 lines (42 loc) · 1.74 KB
/
Copy pathdata.py
File metadata and controls
56 lines (42 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""Market data acquisition.
Thin wrapper over yfinance that returns a normalised OHLCV frame. Isolating it
here means the rest of the system depends on a shape, not on a vendor --
swapping in a paid feed only requires reimplementing `get_data`.
"""
import datetime
import pandas as pd
import yfinance as yf
from config import LOOKBACK_CALENDAR_DAYS, MIN_BARS_REQUIRED
OHLCV_COLUMNS = ["open", "high", "low", "close", "volume"]
def get_data(ticker: str) -> pd.DataFrame:
"""Fetch daily bars for `ticker`, indexed by date.
Prices are split- and dividend-adjusted so that returns computed across a
corporate action are not spurious. Returns an empty frame when the ticker
is unavailable or has too little history to screen, letting the caller skip
it without special-casing exceptions.
"""
end_date = datetime.date.today()
start_date = end_date - datetime.timedelta(days=LOOKBACK_CALENDAR_DAYS)
try:
df = yf.download(
ticker,
start=start_date,
end=end_date,
progress=False,
auto_adjust=True,
actions=False,
)
except Exception as exc:
print(f"Error fetching {ticker}: {exc}")
return pd.DataFrame()
if df.empty or len(df) < MIN_BARS_REQUIRED:
return pd.DataFrame()
# A single-ticker download can still come back with (field, ticker) columns.
if isinstance(df.columns, pd.MultiIndex):
df.columns = df.columns.get_level_values(0)
df.columns = [str(c).lower() for c in df.columns]
missing = set(OHLCV_COLUMNS) - set(df.columns)
if missing:
print(f"Error fetching {ticker}: missing columns {sorted(missing)}")
return pd.DataFrame()
return df.loc[:, OHLCV_COLUMNS].sort_index()