File size: 2,776 Bytes
1bf63f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
Multi-Asset Data Acquisition
Downloads ETF, commodity, and international market OHLCV from Yahoo Finance.
Supports daily and intraday intervals.

For HFT integration: replace download() with your broker/exchange feed.
Pipeline accepts any DataFrame with Open/High/Low/Close/Volume columns.
"""
import yfinance as yf
import pandas as pd
import os, warnings
from config import cfg
warnings.filterwarnings('ignore')

CACHE_DIR = "asset_data_cache"
os.makedirs(CACHE_DIR, exist_ok=True)

# Human-readable names for display
TICKER_NAMES = {
    "QQQ": "Invesco QQQ (Nasdaq 100)",
    "SPY": "SPDR S&P 500",
    "GLD": "SPDR Gold Shares",
    "SLV": "iShares Silver Trust",
    "USO": "US Oil Fund (Crude)",
    "EEM": "iShares Emerging Markets",
    "EFA": "iShares MSCI EAFE (Dev. non-US)",
    "EWJ": "iShares MSCI Japan",
    "EWG": "iShares MSCI Germany",
    "EWU": "iShares MSCI United Kingdom",
    "FXI": "iShares China Large-Cap",
    "INDA": "iShares MSCI India",
    "EWZ": "iShares MSCI Brazil",
    "KWEB": "KraneShares China Internet",
    "RSX": "VanEck Russia",
}

def download(ticker=None, period=None, interval=None):
    ticker = ticker or cfg.primary_ticker
    period = period or cfg.period
    interval = interval or cfg.interval
    if interval in ('1m','5m','15m','30m','1h','90m'):
        period = '730d'  # yfinance intraday limit
    cache_file = os.path.join(CACHE_DIR, f"{ticker}_{period}_{interval}.parquet")
    if os.path.exists(cache_file):
        df = pd.read_parquet(cache_file)
        print(f"  [cache] {ticker}: {len(df)} bars, {df.index[0]} → {df.index[-1]}")
        return df
    name = TICKER_NAMES.get(ticker, ticker)
    print(f"  [download] {ticker} ({name}) period={period} interval={interval} ...")
    df = yf.download(ticker, period=period, interval=interval, auto_adjust=True, progress=False)
    if df.empty:
        raise ValueError(f"No data for {ticker}")
    if isinstance(df.columns, pd.MultiIndex):
        df.columns = df.columns.get_level_values(0)
    keep = [c for c in ['Open','High','Low','Close','Volume'] if c in df.columns]
    df = df[keep].copy().dropna(subset=['Close'])
    for col in df.columns:
        df[col] = pd.to_numeric(df[col], errors='coerce')
    df = df.dropna()
    df.to_parquet(cache_file)
    print(f"  [saved]  {ticker}: {len(df)} bars, {df.index[0]} → {df.index[-1]}")
    return df

def download_all(tickers=None, interval=None):
    tickers = tickers or cfg.tickers
    data = {}
    print(f"Downloading {len(tickers)} assets...")
    for t in tickers:
        try:
            data[t] = download(t, interval=interval)
        except Exception as e:
            print(f"  [ERROR] {t}: {e}")
    return data

def get_asset_name(ticker):
    return TICKER_NAMES.get(ticker, ticker)