File size: 6,417 Bytes
bc200fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
"""
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)")