""" Yahoo Finance Data Downloader for Financial Time Series Research. Downloads OHLCV data for external validation of prediction models. Data is used to test generalization across different markets. Supported prediction tasks: - pred5: 96 days input -> 5 days prediction - pred20: 96 days input -> 20 days prediction - pred60: 120 days input -> 60 days prediction """ import yfinance as yf import pandas as pd from pathlib import Path from datetime import datetime # ============================================================================= # Configuration # ============================================================================= DATA_DIR = Path("data/yahoo") DATA_DIR.mkdir(parents=True, exist_ok=True) # External validation tickers (stocks only, BTC removed for fair comparison) # BTC has different market mechanics (24/7 trading, higher volatility) STOCK_TICKERS = [ "SPY", # S&P 500 ETF - market benchmark "AAPL", # Apple - tech giant "MSFT", # Microsoft - tech giant "GOOGL", # Alphabet - tech giant (added) "AMZN", # Amazon - e-commerce/cloud (added) ] # Optional: crypto tickers for separate experiment CRYPTO_TICKERS = [ "BTC-USD", # Bitcoin "ETH-USD", # Ethereum (added) ] # Download settings START_DATE = "2018-01-01" # Match training data start END_DATE = None # None = today # ============================================================================= # Download Functions # ============================================================================= def download_ticker(ticker: str, interval: str = "1d", start: str = START_DATE, end: str = None) -> pd.DataFrame: """ Download OHLCV data for a single ticker. Args: ticker: Yahoo Finance ticker symbol interval: Data interval (1d for daily) start: Start date (YYYY-MM-DD) end: End date (YYYY-MM-DD), None for today Returns: DataFrame with OHLCV data """ print(f"Downloading {ticker}...", end=" ") try: df = yf.download( ticker, start=start, end=end, interval=interval, auto_adjust=True, progress=False ) if df.empty: print("FAILED (empty data)") return pd.DataFrame() # Flatten multi-level columns if present if isinstance(df.columns, pd.MultiIndex): df.columns = df.columns.get_level_values(0) # Ensure standard column order: Open, High, Low, Close, Volume expected_cols = ['Open', 'High', 'Low', 'Close', 'Volume'] df = df[expected_cols] # Reset index to have Date as column df = df.reset_index() df = df.rename(columns={'index': 'Date', 'Datetime': 'Date'}) # Ensure Date is in standard format if 'Date' in df.columns: df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d') print(f"OK ({len(df)} days, {df['Date'].iloc[0]} to {df['Date'].iloc[-1]})") return df except Exception as e: print(f"FAILED ({e})") return pd.DataFrame() def save_data(df: pd.DataFrame, ticker: str, interval: str = "1d"): """ Save DataFrame to CSV with clean format. Args: df: DataFrame with OHLCV data ticker: Ticker symbol for filename interval: Interval for filename """ if df.empty: return out_path = DATA_DIR / f"{ticker}_{interval}.csv" df.to_csv(out_path, index=False) print(f" Saved: {out_path}") def print_statistics(tickers: list, data_type: str = "stocks"): """Print download statistics.""" print(f"\n{'='*60}") print(f"Yahoo {data_type.upper()} Data Statistics") print(f"{'='*60}") total_days = 0 for ticker in tickers: filepath = DATA_DIR / f"{ticker}_1d.csv" if filepath.exists(): df = pd.read_csv(filepath) days = len(df) total_days += days print(f" {ticker}: {days} days") else: print(f" {ticker}: NOT FOUND") print(f"\nTotal: {total_days} days across {len(tickers)} tickers") # Estimate samples for prediction tasks min_days = (datetime.now() - datetime.strptime(START_DATE, "%Y-%m-%d")).days print(f"\nEstimated samples per ticker:") print(f" - pred5: 96d -> 5d = ~{max(0, min_days - 101)} samples") print(f" - pred20: 96d -> 20d = ~{max(0, min_days - 116)} samples") print(f" - pred60: 120d -> 60d = ~{max(0, min_days - 180)} samples") print(f"{'='*60}") # ============================================================================= # Main Entry Point # ============================================================================= if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Download Yahoo Finance data") parser.add_argument('--stocks-only', action='store_true', help='Download only stock data (exclude crypto)') parser.add_argument('--crypto-only', action='store_true', help='Download only crypto data') parser.add_argument('--all', action='store_true', help='Download both stocks and crypto (default)') args = parser.parse_args() print("="*60) print("Yahoo Finance Data Downloader") print("For Financial Time Series Research") print("="*60) print(f"Date range: {START_DATE} to today") print(f"Output: {DATA_DIR.absolute()}") print("="*60) # Download stocks if not args.crypto_only: print("\n[1/2] Downloading STOCK data...") for ticker in STOCK_TICKERS: df = download_ticker(ticker) save_data(df, ticker) print_statistics(STOCK_TICKERS, "stocks") # Download crypto (optional) if not args.stocks_only: print("\n[2/2] Downloading CRYPTO data...") for ticker in CRYPTO_TICKERS: df = download_ticker(ticker) save_data(df, ticker) print_statistics(CRYPTO_TICKERS, "crypto") print("\nDone!") print("\nUsage for your research:") print(" - Stocks (AAPL, MSFT, SPY, GOOGL, AMZN): External validation") print(" - Crypto (BTC, ETH): Separate experiment (different market)")