PROSTLE commited on
Commit
9314512
Β·
unverified Β·
1 Parent(s): e695b0a

Update stock_data.py

Browse files
Files changed (1) hide show
  1. stock_data.py +195 -0
stock_data.py CHANGED
@@ -116,3 +116,198 @@ def fetch_chart_data(ticker: str, timeframe: str) -> list[dict]:
116
  "volume": int(row["Volume"]),
117
  })
118
  return records
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  "volume": int(row["Volume"]),
117
  })
118
  return records
119
+
120
+
121
+ # ─────────────────────────────────────────────────
122
+ # INTRADAY DATA & FEATURES (for Auto Trade only)
123
+ # ─────────────────────────────────────────────────
124
+
125
+ import numpy as np
126
+
127
+
128
+ def fetch_intraday_data(ticker: str, period: str = "5d", interval: str = "1m") -> pd.DataFrame:
129
+ """Fetch 1-min intraday bars (max 7 days with yfinance)."""
130
+ stock = yf.Ticker(ticker)
131
+ df = stock.history(period=period, interval=interval)
132
+ if df.empty:
133
+ raise ValueError(f"No intraday data for {ticker}")
134
+ df.reset_index(inplace=True)
135
+ col = "Datetime" if "Datetime" in df.columns else "Date"
136
+ df.rename(columns={col: "Datetime"}, inplace=True)
137
+ df["Datetime"] = pd.to_datetime(df["Datetime"])
138
+ return df
139
+
140
+
141
+ def _supertrend(df: pd.DataFrame, period: int = 10, multiplier: float = 3.0):
142
+ """Compute Supertrend indicator (period, multiplier)."""
143
+ hl2 = (df["High"] + df["Low"]) / 2
144
+ atr = ta.volatility.average_true_range(df["High"], df["Low"], df["Close"], window=period)
145
+
146
+ upper_band = hl2 + multiplier * atr
147
+ lower_band = hl2 - multiplier * atr
148
+
149
+ supertrend = pd.Series(0.0, index=df.index)
150
+ direction = pd.Series(1, index=df.index) # 1 = bullish, -1 = bearish
151
+
152
+ for i in range(1, len(df)):
153
+ if df["Close"].iloc[i] > upper_band.iloc[i - 1]:
154
+ direction.iloc[i] = 1
155
+ elif df["Close"].iloc[i] < lower_band.iloc[i - 1]:
156
+ direction.iloc[i] = -1
157
+ else:
158
+ direction.iloc[i] = direction.iloc[i - 1]
159
+ if direction.iloc[i] == 1 and lower_band.iloc[i] < lower_band.iloc[i - 1]:
160
+ lower_band.iloc[i] = lower_band.iloc[i - 1]
161
+ if direction.iloc[i] == -1 and upper_band.iloc[i] > upper_band.iloc[i - 1]:
162
+ upper_band.iloc[i] = upper_band.iloc[i - 1]
163
+
164
+ supertrend.iloc[i] = lower_band.iloc[i] if direction.iloc[i] == 1 else upper_band.iloc[i]
165
+
166
+ return supertrend, direction
167
+
168
+
169
+ def add_intraday_indicators(df: pd.DataFrame) -> pd.DataFrame:
170
+ """Add all intraday trading indicators to a DataFrame of 1-min bars."""
171
+ close = df["Close"]
172
+ high = df["High"]
173
+ low = df["Low"]
174
+ volume = df["Volume"].astype(float)
175
+
176
+ # Moving averages
177
+ df["EMA_9"] = ta.trend.ema_indicator(close, window=9)
178
+ df["EMA_21"] = ta.trend.ema_indicator(close, window=21)
179
+ df["SMA_50"] = ta.trend.sma_indicator(close, window=50)
180
+
181
+ # Price vs MAs (percentage distance)
182
+ df["price_vs_ema9"] = ((close - df["EMA_9"]) / df["EMA_9"]) * 100
183
+ df["price_vs_ema21"] = ((close - df["EMA_21"]) / df["EMA_21"]) * 100
184
+ df["price_vs_sma50"] = ((close - df["SMA_50"]) / df["SMA_50"]) * 100
185
+
186
+ # Returns
187
+ df["returns_1bar"] = close.pct_change(1) * 100
188
+ df["returns_5bar"] = close.pct_change(5) * 100
189
+ df["returns_15bar"] = close.pct_change(15) * 100
190
+
191
+ # Momentum
192
+ df["RSI"] = ta.momentum.rsi(close, window=14)
193
+ macd_obj = ta.trend.MACD(close, window_fast=12, window_slow=26, window_sign=9)
194
+ df["MACD"] = macd_obj.macd()
195
+ df["MACD_Signal"] = macd_obj.macd_signal()
196
+ df["MACD_Hist"] = macd_obj.macd_diff()
197
+
198
+ # Volatility
199
+ df["ATR"] = ta.volatility.average_true_range(high, low, close, window=14)
200
+ bb = ta.volatility.BollingerBands(close, window=20, window_dev=2)
201
+ df["BB_Upper"] = bb.bollinger_hband()
202
+ df["BB_Lower"] = bb.bollinger_lband()
203
+ df["BB_Width"] = bb.bollinger_wband()
204
+ bb_range = df["BB_Upper"] - df["BB_Lower"]
205
+ df["BB_Position"] = np.where(bb_range > 0, (close - df["BB_Lower"]) / bb_range, 0.5)
206
+
207
+ # VWAP
208
+ cumvol = volume.cumsum()
209
+ cumtp = (((high + low + close) / 3) * volume).cumsum()
210
+ df["VWAP"] = np.where(cumvol > 0, cumtp / cumvol, close)
211
+ df["price_vs_vwap"] = ((close - df["VWAP"]) / df["VWAP"]) * 100
212
+
213
+ # Volume ratio
214
+ vol_sma20 = volume.rolling(window=20).mean()
215
+ df["volume_ratio"] = np.where(vol_sma20 > 0, volume / vol_sma20, 1.0)
216
+
217
+ # Supertrend
218
+ st_val, st_dir = _supertrend(df, period=10, multiplier=3.0)
219
+ df["Supertrend"] = st_val
220
+ df["Supertrend_Dir"] = st_dir # 1=bullish, -1=bearish
221
+ df["supertrend_dist"] = ((close - st_val) / close) * 100
222
+
223
+ # Time features
224
+ if "Datetime" in df.columns:
225
+ dt = pd.to_datetime(df["Datetime"])
226
+ df["minute_of_day"] = dt.dt.hour * 60 + dt.dt.minute
227
+ df["is_first_hour"] = (dt.dt.hour == 9).astype(int)
228
+ df["is_last_hour"] = (dt.dt.hour >= 15).astype(int)
229
+ else:
230
+ df["minute_of_day"] = 0
231
+ df["is_first_hour"] = 0
232
+ df["is_last_hour"] = 0
233
+
234
+ df.dropna(inplace=True)
235
+ return df
236
+
237
+
238
+ def fetch_india_vix() -> dict:
239
+ """Fetch India VIX current level and recent change."""
240
+ try:
241
+ stock = yf.Ticker("^INDIAVIX")
242
+ hist = stock.history(period="7d")
243
+ if hist.empty:
244
+ return {"vix_level": 15.0, "vix_change_5d": 0.0, "available": False}
245
+ current = float(hist["Close"].iloc[-1])
246
+ if len(hist) >= 5:
247
+ prev = float(hist["Close"].iloc[-5])
248
+ else:
249
+ prev = float(hist["Close"].iloc[0])
250
+ change = round(current - prev, 2)
251
+ return {"vix_level": round(current, 2), "vix_change_5d": change, "available": True}
252
+ except Exception:
253
+ return {"vix_level": 15.0, "vix_change_5d": 0.0, "available": False}
254
+
255
+
256
+ def fetch_nifty_trend() -> dict:
257
+ """Fetch Nifty 50 trend vs EMA-9 and EMA-21."""
258
+ try:
259
+ stock = yf.Ticker("^NSEI")
260
+ hist = stock.history(period="1mo", interval="1d")
261
+ if len(hist) < 21:
262
+ return {"nifty_price": 0, "trend": "flat", "above_ema9": False,
263
+ "above_ema21": False, "available": False}
264
+ close = hist["Close"]
265
+ ema9 = ta.trend.ema_indicator(close, window=9)
266
+ ema21 = ta.trend.ema_indicator(close, window=21)
267
+ price = float(close.iloc[-1])
268
+ e9 = float(ema9.iloc[-1])
269
+ e21 = float(ema21.iloc[-1])
270
+
271
+ above_ema9 = price > e9
272
+ above_ema21 = price > e21
273
+
274
+ if above_ema9 and above_ema21:
275
+ trend = "bullish"
276
+ elif not above_ema9 and not above_ema21:
277
+ trend = "bearish"
278
+ else:
279
+ trend = "flat"
280
+
281
+ return {
282
+ "nifty_price": round(price, 2),
283
+ "ema9": round(e9, 2),
284
+ "ema21": round(e21, 2),
285
+ "trend": trend,
286
+ "above_ema9": above_ema9,
287
+ "above_ema21": above_ema21,
288
+ "available": True,
289
+ }
290
+ except Exception:
291
+ return {"nifty_price": 0, "trend": "flat", "above_ema9": False,
292
+ "above_ema21": False, "available": False}
293
+
294
+
295
+ def detect_ipo_stock(ticker: str) -> dict:
296
+ """Check if stock was listed recently (IPO < 180 days)."""
297
+ try:
298
+ stock = yf.Ticker(ticker)
299
+ hist = stock.history(period="max")
300
+ if hist.empty:
301
+ return {"is_ipo": False, "ipo_age_days": 999, "listing_date": None}
302
+ first_date = hist.index[0]
303
+ if hasattr(first_date, "date"):
304
+ first_date = first_date.date()
305
+ age_days = (datetime.now().date() - first_date).days
306
+ return {
307
+ "is_ipo": age_days < 180,
308
+ "ipo_age_days": age_days,
309
+ "listing_date": str(first_date),
310
+ }
311
+ except Exception:
312
+ return {"is_ipo": False, "ipo_age_days": 999, "listing_date": None}
313
+