Jitendra12421 commited on
Commit
b07dd39
·
verified ·
1 Parent(s): 0d74aef

Delete t5_engine.py

Browse files
Files changed (1) hide show
  1. t5_engine.py +0 -168
t5_engine.py DELETED
@@ -1,168 +0,0 @@
1
- import os
2
- import json
3
- import time
4
- import requests
5
- import joblib
6
- import pandas as pd
7
- import numpy as np
8
- from datetime import datetime, date
9
- from zoneinfo import ZoneInfo
10
- from features_t5 import extract_semantic_features_t5, extract_sequential_features_t5
11
-
12
- IST = ZoneInfo("Asia/Kolkata")
13
- DATA_DIR = os.path.dirname(__file__)
14
- MODELS_DIR = os.path.join(DATA_DIR, "models")
15
- PREDICTIONS_FILE_T5 = os.path.join(DATA_DIR, "predictions_t5.json")
16
- DAILY_DATA_FILE = os.path.join(DATA_DIR, "data", "nifty50_daily.parquet")
17
-
18
- TICKERS = [
19
- 'ADANIENT', 'ADANIPORTS', 'APOLLOHOSP', 'ASIANPAINT', 'AXISBANK', 'BAJAJ-AUTO', 'BAJAJFINSV', 'BAJFINANCE',
20
- 'BHARTIARTL', 'BPCL', 'BRITANNIA', 'CIPLA', 'COALINDIA', 'DIVISLAB', 'DRREDDY', 'EICHERMOT', 'GRASIM',
21
- 'HCLTECH', 'HDFCBANK', 'HDFCLIFE', 'HEROMOTOCO', 'HINDALCO', 'HINDUNILVR', 'ICICIBANK', 'INDUSINDBK',
22
- 'INFY', 'ITC', 'JSWSTEEL', 'KOTAKBANK', 'LT', 'M&M', 'MARUTI', 'NESTLEIND', 'NTPC', 'ONGC', 'POWERGRID',
23
- 'RELIANCE', 'SBILIFE', 'SBIN', 'SUNPHARMA', 'TATACONSUM', 'TATAMOTORS', 'TATASTEEL', 'TCS', 'TECHM',
24
- 'TITAN', 'ULTRACEMCO', 'UPL', 'WIPRO'
25
- ]
26
-
27
- def fetch_groww_t5_data(ticker: str, start_ts: int, end_ts: int):
28
- url = f"https://groww.in/v1/api/charting_service/v2/chart/exchange/NSE/segment/CASH/{ticker}?endTimeInMillis={end_ts}&intervalInMinutes=1&startTimeInMillis={start_ts}"
29
- headers = {
30
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
31
- "Accept": "application/json"
32
- }
33
-
34
- try:
35
- response = requests.get(url, headers=headers, timeout=10)
36
- if response.status_code == 200:
37
- data = response.json()
38
- if data and 'candles' in data and len(data['candles']) > 0:
39
- rows = []
40
- for c in data['candles']:
41
- rows.append({
42
- "date": datetime.fromtimestamp(c[0], IST).replace(tzinfo=None),
43
- "open": float(c[1]),
44
- "high": float(c[2]),
45
- "low": float(c[3]),
46
- "close": float(c[4]),
47
- "volume": float(c[5]),
48
- "ticker": ticker
49
- })
50
- return pd.DataFrame(rows)
51
- return None
52
- except Exception as e:
53
- print(f"Error fetching T+5 for {ticker}: {e}")
54
- return None
55
-
56
- def fetch_all_t5_data(today: date):
57
- # Market open 09:15 to 09:20
58
- start_dt = datetime.combine(today, datetime.strptime("09:15", "%H:%M").time()).replace(tzinfo=IST)
59
- end_dt = datetime.combine(today, datetime.strptime("09:25", "%H:%M").time()).replace(tzinfo=IST) # fetch slightly wider just in case
60
-
61
- start_ts = int(start_dt.timestamp() * 1000)
62
- end_ts = int(end_dt.timestamp() * 1000)
63
-
64
- dfs = []
65
- for ticker in TICKERS:
66
- df_tick = fetch_groww_t5_data(ticker, start_ts, end_ts)
67
- if df_tick is not None and not df_tick.empty:
68
- dfs.append(df_tick)
69
- time.sleep(0.1)
70
-
71
- if dfs:
72
- return pd.concat(dfs, ignore_index=True)
73
- return pd.DataFrame()
74
-
75
- def generate_t5_predictions():
76
- now = datetime.now(IST)
77
- today = now.date()
78
-
79
- df_live = fetch_all_t5_data(today)
80
- if df_live.empty:
81
- print("No live data fetched for T+5.")
82
- return None
83
-
84
- df_live.set_index("date", inplace=True)
85
-
86
- # Load previous day's close for the gap feature
87
- prev_closes = {}
88
- if os.path.exists(DAILY_DATA_FILE):
89
- df_daily = pd.read_parquet(DAILY_DATA_FILE)
90
- df_daily = df_daily[df_daily['date'].dt.date < today]
91
- if not df_daily.empty:
92
- for ticker in TICKERS:
93
- t_data = df_daily[df_daily['ticker'] == ticker]
94
- if not t_data.empty:
95
- # Last row is yesterday's close
96
- t_data = t_data.sort_values("date")
97
- prev_closes[ticker] = t_data.iloc[-1]['close']
98
-
99
- predictions = {}
100
-
101
- for ticker in TICKERS:
102
- model_path = os.path.join(MODELS_DIR, f"{ticker}_t5.joblib")
103
- if not os.path.exists(model_path):
104
- continue
105
-
106
- feat_type, clf = joblib.load(model_path)
107
-
108
- # Build dummy dataframe for extraction
109
- t_data = df_live[df_live['ticker'] == ticker].copy()
110
- if t_data.empty:
111
- continue
112
-
113
- # Insert yesterday's dummy row at 15:30 to populate prev_daily_close correctly
114
- if ticker in prev_closes:
115
- yday = datetime.combine(today - pd.Timedelta(days=1), datetime.strptime("15:30", "%H:%M").time())
116
- t_data.loc[yday] = {"open": prev_closes[ticker], "high": prev_closes[ticker], "low": prev_closes[ticker], "close": prev_closes[ticker], "volume": 0, "ticker": ticker}
117
-
118
- t_data.sort_index(inplace=True)
119
-
120
- if feat_type == "semantic":
121
- X, _, _ = extract_semantic_features_t5(t_data)
122
- else:
123
- X, _, _ = extract_sequential_features_t5(t_data)
124
-
125
- if X is None or X.empty:
126
- continue
127
-
128
- # Get today's prediction
129
- if today in X.index:
130
- X_today = X.loc[[today]]
131
- prob_up = clf.predict_proba(X_today)[0][1]
132
- prob_dn = 1.0 - prob_up
133
-
134
- if prob_up > prob_dn:
135
- pred_dir = "UP"
136
- prob_val = prob_up
137
- else:
138
- pred_dir = "DOWN"
139
- prob_val = prob_dn
140
-
141
- conf = "HIGH" if prob_val >= 0.55 else "NORMAL"
142
-
143
- predictions[ticker] = {
144
- "prediction": pred_dir,
145
- "probability": round(prob_val * 100, 2),
146
- "confidence": conf
147
- }
148
-
149
- probs = [info["probability"] for info in predictions.values()]
150
- mean_accuracy = round(np.mean(probs), 2) if probs else 0.0
151
- median_accuracy = round(np.median(probs), 2) if probs else 0.0
152
-
153
- output = {
154
- "generated_at": datetime.now().isoformat(),
155
- "forecast_date": today.strftime('%Y-%m-%d'),
156
- "mean_accuracy": mean_accuracy,
157
- "median_accuracy": median_accuracy,
158
- "predictions": predictions
159
- }
160
-
161
- with open(PREDICTIONS_FILE_T5, "w") as f:
162
- json.dump(output, f, indent=4)
163
-
164
- print(f"Generated T+5 predictions. Saved to {PREDICTIONS_FILE_T5}")
165
- return output
166
-
167
- if __name__ == "__main__":
168
- generate_t5_predictions()