-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
33 lines (27 loc) · 1.41 KB
/
Copy pathdata.py
File metadata and controls
33 lines (27 loc) · 1.41 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
# -*- coding: utf-8 -*-
"""Data loading with a local cache, so results are reproducible and runs work offline."""
from __future__ import annotations
import os
import pandas as pd
def load_prices(symbols: list[str], cache_path: str = "data/prices.csv",
refresh: bool = False) -> pd.DataFrame:
"""Adjusted daily closes for ``symbols``, cached to ``cache_path``.
First run downloads from Yahoo Finance (via yfinance) and writes the cache; later runs
read the cache, so results reproduce offline after the first download — and the numbers
can't silently drift between runs. (The cache itself is gitignored, not shipped.)
"""
if os.path.exists(cache_path) and not refresh:
px = pd.read_csv(cache_path, index_col=0, parse_dates=True)
missing = [s for s in symbols if s not in px.columns]
if not missing:
return px[symbols].dropna()
import yfinance as yf # imported lazily: tests never need it
raw = yf.download(symbols, period="max", auto_adjust=True, progress=False)["Close"]
if isinstance(raw, pd.Series): # yfinance returns a 1-D Series for a single ticker
raw = raw.to_frame(symbols[0])
raw = raw[[c for c in symbols if c in raw.columns]].dropna()
if raw.empty:
raise RuntimeError("download returned no data")
os.makedirs(os.path.dirname(cache_path) or ".", exist_ok=True)
raw.to_csv(cache_path)
return raw