File size: 10,234 Bytes
d7171f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# engine/data.py
# Fetches historical OHLCV data from yfinance
# All timeframes supported with honest limitation handling

import yfinance as yf
import pandas as pd
import os
from datetime import datetime, timedelta
from tiingo import TiingoClient
from dotenv import load_dotenv

load_dotenv()

# ── Tiingo Client Setup ───────────────────────────────────────
TIINGO_API_KEY = os.getenv("TIINGO_API_KEY", "")
tiingo_config = {'api_key': TIINGO_API_KEY, 'session': True}
tiingo_client = TiingoClient(tiingo_config)

# ── Timeframe config ──────────────────────────────────────────
TIMEFRAME_CONFIG = {
    "1m": {
        "yf_interval": "1m",
        "max_period":  "7d",
        "display":     "1 Minute",
        "warning":     "⚠️ Only 7 days available for 1min data (yfinance limit)"
    },
    "5m": {
        "yf_interval": "5m",
        "max_period":  "60d",
        "display":     "5 Minutes",
        "warning":     "⚠️ Only 60 days available for 5min data (yfinance limit)"
    },
    "15m": {
        "yf_interval": "15m",
        "max_period":  "60d",
        "display":     "15 Minutes",
        "warning":     "⚠️ Only 60 days available for 15min data (yfinance limit)"
    },
    "30m": {
        "yf_interval": "30m",
        "max_period":  "60d",
        "display":     "30 Minutes",
        "warning":     "⚠️ Only 60 days available for 30min data (yfinance limit)"
    },
    "1h": {
        "yf_interval": "1h",
        "max_period":  "2y",
        "display":     "1 Hour",
        "warning":     None
    },
    "4h": {
        "yf_interval": "1h",       # fetch 1H β†’ resample to 4H
        "max_period":  "2y",
        "display":     "4 Hour",
        "warning":     "ℹ️ 4H candles resampled from 1H data"
    },
    "1d": {
        "yf_interval": "1d",
        "max_period":  "10y",
        "display":     "Daily",
        "warning":     None
    },
    "1wk": {
        "yf_interval": "1wk",
        "max_period":  "20y",
        "display":     "Weekly",
        "warning":     None
    }
}

# ── Period config ─────────────────────────────────────────────
PERIOD_CONFIG = {
    "7d":  "7d",
    "60d": "60d",
    "1y":  "1y",
    "2y":  "2y",
    "3y":  "3y",
    "5y":  "5y",
    "10y": "10y",
}

# ── Period to days mapping ────────────────────────────────────
PERIOD_DAYS = {
    "7d":  7,
    "60d": 60,
    "1y":  365,
    "2y":  730,
    "3y":  1095,
    "5y":  1825,
    "10y": 3650,
    "20y": 7300,
}


# ── Caching Config ───────────────────────────────────────────

CACHE_DIR = "/tmp/prahari_cache/data"
os.makedirs(CACHE_DIR, exist_ok=True)

def fetch_data(ticker: str, timeframe: str, period: str, market: str = "india_equity") -> pd.DataFrame:
    """
    Fetches OHLCV data with smart caching.
    Routes between Tiingo and Yahoo Finance based on detected market.
    """
    config = TIMEFRAME_CONFIG.get(timeframe)
    if not config:
        raise ValueError(f"Unsupported timeframe: {timeframe}. Supported: {list(TIMEFRAME_CONFIG.keys())}")

    # 0. Check Cache
    cache_file = f"{ticker.replace('^', '').replace('=', '')}_{timeframe}_{period}.parquet".lower()
    cache_path = os.path.join(CACHE_DIR, cache_file)
    
    if os.path.exists(cache_path):
        # Cache TTL: 4h for intraday, 24h for daily+
        mtime = datetime.fromtimestamp(os.path.getmtime(cache_path))
        ttl_hours = 4 if "m" in timeframe or "h" in timeframe else 24
        if datetime.now() - mtime < timedelta(hours=ttl_hours):
            print(f"[data.py] Loading {ticker} from cache...")
            return pd.read_parquet(cache_path)

    # 1. Routing Logic: Prioritize Tiingo for non-Indian markets
    df = None
    is_major_crypto = any(c in ticker.upper() for c in ["BTC", "ETH", "USDT", "STETH", "SOL"])
    is_intl_market = market in ("crypto", "forex", "us_equity", "commodity")
    
    if (is_intl_market or is_major_crypto) and TIINGO_API_KEY and TIINGO_API_KEY != "paste_your_tiingo_api_key_here":
        # Try Tiingo for Crypto/US/Forex
        df = _fetch_from_tiingo(ticker, timeframe, period, market)
    
    if df is None or df.empty:
        # 2. Fallback to Yahoo Finance (Always used for india_equity or if Tiingo fails)
        df = _fetch_from_yahoo(ticker, timeframe, period)

    # 3. Save to Cache if successful
    if df is not None and not df.empty:
        df.to_parquet(cache_path)
    
    return df


def _fetch_from_yahoo(ticker: str, timeframe: str, period: str) -> pd.DataFrame:
    config = TIMEFRAME_CONFIG.get(timeframe)
    actual_period = _cap_period(period, config["max_period"])

    try:
        df = yf.download(
            tickers=ticker,
            period=actual_period,
            interval=config["yf_interval"],
            auto_adjust=True,
            progress=False
        )

        if df is None or df.empty:
            return None

        if isinstance(df.columns, pd.MultiIndex):
            df.columns = df.columns.get_level_values(0)

        df = df[["Open", "High", "Low", "Close", "Volume"]].copy()
        df.dropna(inplace=True)

        if timeframe == "4h":
            df = _resample_to_4h(df)

        return df

    except Exception as e:
        print(f"[data.py] Yahoo Finance failed for {ticker}: {e}")
        return None


def _fetch_from_tiingo(ticker: str, timeframe: str, period: str, market: str) -> pd.DataFrame:
    """Fetch from Tiingo API with proper market-specific ticker normalization"""
    # 1. Normalize Ticker for Tiingo
    t = ticker.upper()
    if market == "crypto":
        t = t.replace("-USD", "usd").replace("-", "").lower()
    elif market == "forex":
        t = t.replace("=X", "").lower()
    else:
        t = t.upper() # Stocks use upper case typically

    # 2. Map timeframe to Tiingo resampleFreq
    resample_map = {
        "1m": "1min", "5m": "5min", "15m": "15min", 
        "30m": "30min", "1h": "1hour", "1d": "daily"
    }
    freq = resample_map.get(timeframe, "1hour")
    
    # 3. Handle periods
    days_map = PERIOD_DAYS.get(period, 730)
    start_date = (datetime.now() - timedelta(days=days_map)).strftime('%Y-%m-%d')
    
    try:
        price_data = []
        if market == "crypto":
             price_data = tiingo_client.get_crypto_price_history(
                tickers=[t], startDate=start_date, resampleFreq=freq
            )
        elif market == "forex":
            price_data = tiingo_client.get_forex_price_history(
                tickers=[t], startDate=start_date, resampleFreq=freq
            )
        else:
            # US Stocks / Commodities
            price_data = tiingo_client.get_ticker_price(
                t, startDate=start_date, resampleFreq=freq
            )

        if not price_data: return None
        
        # Tiingo returns data specifically for the ticker
        # If multiple tickers requested, it's a list of dicts with 'ticker' key
        # If single, it's a list of bars
        if isinstance(price_data, list) and len(price_data) > 0 and 'priceData' in price_data[0]:
            actual_bars = price_data[0]['priceData']
        else:
            actual_bars = price_data

        df = pd.DataFrame(actual_bars)
        if df.empty: return None

        # Clean columns
        df['date'] = pd.to_datetime(df['date'])
        df.set_index('date', inplace=True)
        
        # Map Tiingo columns to Prahari columns
        # Tiingo: open, high, low, close, volume (sometimes adjClose)
        rename_map = {
            'open': 'Open', 'high': 'High', 'low': 'Low', 
            'close': 'Close', 'volume': 'Volume'
        }
        df = df.rename(columns=rename_map)
        
        # Ensure only core columns
        valid = ["Open", "High", "Low", "Close", "Volume"]
        df = df[[c for c in valid if c in df.columns]]
        df.dropna(inplace=True)

        print(f"[data.py] Successfully fetched {len(df)} bars from Tiingo for {ticker}")
        return df

    except Exception as e:
        print(f"[data.py] Tiingo failed for {ticker}: {e}")
        return None


def get_warnings(timeframe: str, period: str) -> list:
    """Returns data limitation warnings for this timeframe/period combo"""
    warnings = []
    config = TIMEFRAME_CONFIG.get(timeframe, {})

    if config.get("warning"):
        warnings.append(config["warning"])

    # Warn if period was capped
    max_days = PERIOD_DAYS.get(config.get("max_period", "2y"), 730)
    req_days = PERIOD_DAYS.get(period, 730)
    if req_days > max_days:
        warnings.append(
            f"⚠️ Requested {period} but only {config['max_period']} "
            f"available for {timeframe} timeframe"
        )

    return warnings


def get_available_periods(timeframe: str) -> list:
    """Returns available backtest periods for a given timeframe"""
    config = TIMEFRAME_CONFIG.get(timeframe, {})
    max_period = config.get("max_period", "2y")
    max_days = PERIOD_DAYS.get(max_period, 730)

    available = []
    for period, days in PERIOD_DAYS.items():
        if days <= max_days:
            available.append(period)
    return available


# ── Private helpers ───────────────────────────────────────────

def _resample_to_4h(df: pd.DataFrame) -> pd.DataFrame:
    """Resample 1H candles into 4H candles"""
    df_4h = df.resample("4H").agg({
        "Open":   "first",
        "High":   "max",
        "Low":    "min",
        "Close":  "last",
        "Volume": "sum"
    }).dropna()
    return df_4h


def _cap_period(requested: str, max_available: str) -> str:
    """Cap requested period to what yfinance supports"""
    req_days = PERIOD_DAYS.get(requested, 730)
    max_days = PERIOD_DAYS.get(max_available, 730)
    if req_days > max_days:
        return max_available
    return requested