Spaces:
Sleeping
Sleeping
File size: 5,592 Bytes
25a020f | 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 | """
Stock data fetching module using yfinance.
Handles OHLCV data, technical indicators (RSI, MAs, Bollinger Bands),
and error handling for invalid tickers / market holidays.
"""
import pandas as pd
import yfinance as yf
import numpy as np
from datetime import datetime, timedelta
from typing import Optional
from config import DATA_PERIOD_MONTHS, MA_PERIODS, BOLLINGER_PERIOD, BOLLINGER_STD, RSI_PERIOD
def _calculate_rsi(prices: pd.Series, period: int = RSI_PERIOD) -> pd.Series:
"""Calculate RSI (Relative Strength Index)."""
delta = prices.diff()
gain = delta.where(delta > 0, 0.0)
loss = (-delta).where(delta < 0, 0.0)
avg_gain = gain.rolling(window=period, min_periods=period).mean()
avg_loss = loss.rolling(window=period, min_periods=period).mean()
rs = avg_gain / avg_loss.replace(0, np.inf)
rsi = 100 - (100 / (1 + rs))
return rsi
def _calculate_bollinger_bands(
prices: pd.Series, period: int = BOLLINGER_PERIOD, std_dev: float = BOLLINGER_STD
) -> tuple[pd.Series, pd.Series, pd.Series]:
"""Calculate Bollinger Bands (middle, upper, lower)."""
middle = prices.rolling(window=period).mean()
std = prices.rolling(window=period).std()
upper = middle + (std * std_dev)
lower = middle - (std * std_dev)
return middle, upper, lower
def fetch_stock_data(
tickers: list[str],
period_months: int | None = None,
period_days: int | None = None,
) -> dict[str, dict]:
"""
Fetch OHLCV data and technical indicators for given tickers.
Returns dict: {ticker: {df, stats, error}}
Use period_days for 1W/1M/3M; period_months as fallback.
"""
end_date = datetime.now()
if period_days is not None:
start_date = end_date - timedelta(days=period_days)
else:
months = period_months or DATA_PERIOD_MONTHS
start_date = end_date - timedelta(days=months * 31)
results = {}
for ticker in tickers:
ticker_upper = ticker.strip().upper()
if not ticker_upper:
continue
try:
stock = yf.Ticker(ticker_upper)
df = stock.history(start=start_date, end=end_date, auto_adjust=True)
if df.empty or len(df) < 5:
results[ticker_upper] = {
"df": None,
"stats": None,
"error": f"No sufficient data for {ticker_upper}. Ticker may be invalid or market closed.",
}
continue
# Ensure we have required columns
required = ["Open", "High", "Low", "Close", "Volume"]
if not all(col in df.columns for col in required):
results[ticker_upper] = {
"df": None,
"stats": None,
"error": f"Missing OHLCV columns for {ticker_upper}",
}
continue
# Calculate technical indicators
close = df["Close"]
df = df.copy()
# Moving averages
df["MA_20"] = close.rolling(window=MA_PERIODS["short"]).mean()
df["MA_50"] = close.rolling(window=MA_PERIODS["long"]).mean()
# Bollinger Bands
bb_mid, bb_upper, bb_lower = _calculate_bollinger_bands(close)
df["BB_middle"] = bb_mid
df["BB_upper"] = bb_upper
df["BB_lower"] = bb_lower
# RSI
df["RSI"] = _calculate_rsi(close)
# Compute stats for AI context
current_price = float(close.iloc[-1])
start_price = float(close.iloc[0])
return_pct = ((current_price - start_price) / start_price) * 100 if start_price else 0
volatility = float(close.pct_change().std() * 100) if len(close) > 1 else 0
high_52w = float(close.rolling(252).max().iloc[-1]) if len(close) >= 252 else float(close.max())
low_52w = float(close.rolling(252).min().iloc[-1]) if len(close) >= 252 else float(close.min())
avg_volume = int(df["Volume"].mean())
rsi_latest = float(df["RSI"].iloc[-1]) if not pd.isna(df["RSI"].iloc[-1]) else None
ma_50_latest = float(df["MA_50"].iloc[-1]) if not pd.isna(df["MA_50"].iloc[-1]) else None
if ma_50_latest:
ma_signal = "Above" if current_price > ma_50_latest else "Below"
else:
ma_signal = "N/A"
# Weekly price summary for AI prompt
weekly = df.resample("W").agg({"Close": "last"}).dropna()
weekly_prices = weekly["Close"].tolist()
weekly_dates = weekly.index.strftime("%Y-%m-%d").tolist()
weekly_table = "\n".join(
f"{d}: ${p:.2f}" for d, p in zip(weekly_dates[-12:], weekly_prices[-12:])
)
stats = {
"current_price": current_price,
"return_pct": return_pct,
"volatility": volatility,
"high_52w": high_52w,
"low_52w": low_52w,
"avg_volume": avg_volume,
"rsi": rsi_latest,
"ma_signal": ma_signal,
"start_date": start_date.strftime("%Y-%m-%d"),
"end_date": end_date.strftime("%Y-%m-%d"),
"weekly_price_table": weekly_table,
}
results[ticker_upper] = {"df": df, "stats": stats, "error": None}
except Exception as e:
results[ticker_upper] = {
"df": None,
"stats": None,
"error": str(e),
}
return results
|