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ance.
|
| 3 |
+
Handles OHLCV data, technical indicators (RSI, MAs, Bollinger Bands),
|
| 4 |
+
and error handling for invalid tickers / market holidays.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import yfinance as yf
|
| 9 |
+
import numpy as np
|
| 10 |
+
from datetime import datetime, timedelta
|
| 11 |
+
from typing import Optional
|
| 12 |
+
|
| 13 |
+
from config import DATA_PERIOD_MONTHS, MA_PERIODS, BOLLINGER_PERIOD, BOLLINGER_STD, RSI_PERIOD
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _calculate_rsi(prices: pd.Series, period: int = RSI_PERIOD) -> pd.Series:
|
| 17 |
+
"""Calculate RSI (Relative Strength Index)."""
|
| 18 |
+
delta = prices.diff()
|
| 19 |
+
gain = delta.where(delta > 0, 0.0)
|
| 20 |
+
loss = (-delta).where(delta < 0, 0.0)
|
| 21 |
+
avg_gain = gain.rolling(window=period, min_periods=period).mean()
|
| 22 |
+
avg_loss = loss.rolling(window=period, min_periods=period).mean()
|
| 23 |
+
rs = avg_gain / avg_loss.replace(0, np.inf)
|
| 24 |
+
rsi = 100 - (100 / (1 + rs))
|
| 25 |
+
return rsi
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _calculate_bollinger_bands(
|
| 29 |
+
prices: pd.Series, period: int = BOLLINGER_PERIOD, std_dev: float = BOLLINGER_STD
|
| 30 |
+
) -> tuple[pd.Series, pd.Series, pd.Series]:
|
| 31 |
+
"""Calculate Bollinger Bands (middle, upper, lower)."""
|
| 32 |
+
middle = prices.rolling(window=period).mean()
|
| 33 |
+
std = prices.rolling(window=period).std()
|
| 34 |
+
upper = middle + (std * std_dev)
|
| 35 |
+
lower = middle - (std * std_dev)
|
| 36 |
+
return middle, upper, lower
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def fetch_stock_data(
|
| 40 |
+
tickers: list[str],
|
| 41 |
+
period_months: int | None = None,
|
| 42 |
+
period_days: int | None = None,
|
| 43 |
+
) -> dict[str, dict]:
|
| 44 |
+
"""
|
| 45 |
+
Fetch OHLCV data and technical indicators for given tickers.
|
| 46 |
+
Returns dict: {ticker: {df, stats, error}}
|
| 47 |
+
Use period_days for 1W/1M/3M; period_months as fallback.
|
| 48 |
+
"""
|
| 49 |
+
end_date = datetime.now()
|
| 50 |
+
if period_days is not None:
|
| 51 |
+
start_date = end_date - timedelta(days=period_days)
|
| 52 |
+
else:
|
| 53 |
+
months = period_months or DATA_PERIOD_MONTHS
|
| 54 |
+
start_date = end_date - timedelta(days=months * 31)
|
| 55 |
+
|
| 56 |
+
results = {}
|
| 57 |
+
|
| 58 |
+
for ticker in tickers:
|
| 59 |
+
ticker_upper = ticker.strip().upper()
|
| 60 |
+
if not ticker_upper:
|
| 61 |
+
continue
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
stock = yf.Ticker(ticker_upper)
|
| 65 |
+
df = stock.history(start=start_date, end=end_date, auto_adjust=True)
|
| 66 |
+
|
| 67 |
+
if df.empty or len(df) < 5:
|
| 68 |
+
results[ticker_upper] = {
|
| 69 |
+
"df": None,
|
| 70 |
+
"stats": None,
|
| 71 |
+
"error": f"No sufficient data for {ticker_upper}. Ticker may be invalid or market closed.",
|
| 72 |
+
}
|
| 73 |
+
continue
|
| 74 |
+
|
| 75 |
+
# Ensure we have required columns
|
| 76 |
+
required = ["Open", "High", "Low", "Close", "Volume"]
|
| 77 |
+
if not all(col in df.columns for col in required):
|
| 78 |
+
results[ticker_upper] = {
|
| 79 |
+
"df": None,
|
| 80 |
+
"stats": None,
|
| 81 |
+
"error": f"Missing OHLCV columns for {ticker_upper}",
|
| 82 |
+
}
|
| 83 |
+
continue
|
| 84 |
+
|
| 85 |
+
# Calculate technical indicators
|
| 86 |
+
close = df["Close"]
|
| 87 |
+
df = df.copy()
|
| 88 |
+
|
| 89 |
+
# Moving averages
|
| 90 |
+
df["MA_20"] = close.rolling(window=MA_PERIODS["short"]).mean()
|
| 91 |
+
df["MA_50"] = close.rolling(window=MA_PERIODS["long"]).mean()
|
| 92 |
+
|
| 93 |
+
# Bollinger Bands
|
| 94 |
+
bb_mid, bb_upper, bb_lower = _calculate_bollinger_bands(close)
|
| 95 |
+
df["BB_middle"] = bb_mid
|
| 96 |
+
df["BB_upper"] = bb_upper
|
| 97 |
+
df["BB_lower"] = bb_lower
|
| 98 |
+
|
| 99 |
+
# RSI
|
| 100 |
+
df["RSI"] = _calculate_rsi(close)
|
| 101 |
+
|
| 102 |
+
# Compute stats for AI context
|
| 103 |
+
current_price = float(close.iloc[-1])
|
| 104 |
+
start_price = float(close.iloc[0])
|
| 105 |
+
return_pct = ((current_price - start_price) / start_price) * 100 if start_price else 0
|
| 106 |
+
volatility = float(close.pct_change().std() * 100) if len(close) > 1 else 0
|
| 107 |
+
high_52w = float(close.rolling(252).max().iloc[-1]) if len(close) >= 252 else float(close.max())
|
| 108 |
+
low_52w = float(close.rolling(252).min().iloc[-1]) if len(close) >= 252 else float(close.min())
|
| 109 |
+
avg_volume = int(df["Volume"].mean())
|
| 110 |
+
rsi_latest = float(df["RSI"].iloc[-1]) if not pd.isna(df["RSI"].iloc[-1]) else None
|
| 111 |
+
ma_50_latest = float(df["MA_50"].iloc[-1]) if not pd.isna(df["MA_50"].iloc[-1]) else None
|
| 112 |
+
|
| 113 |
+
if ma_50_latest:
|
| 114 |
+
ma_signal = "Above" if current_price > ma_50_latest else "Below"
|
| 115 |
+
else:
|
| 116 |
+
ma_signal = "N/A"
|
| 117 |
+
|
| 118 |
+
# Weekly price summary for AI prompt
|
| 119 |
+
weekly = df.resample("W").agg({"Close": "last"}).dropna()
|
| 120 |
+
weekly_prices = weekly["Close"].tolist()
|
| 121 |
+
weekly_dates = weekly.index.strftime("%Y-%m-%d").tolist()
|
| 122 |
+
weekly_table = "\n".join(
|
| 123 |
+
f"{d}: ${p:.2f}" for d, p in zip(weekly_dates[-12:], weekly_prices[-12:])
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
stats = {
|
| 127 |
+
"current_price": current_price,
|
| 128 |
+
"return_pct": return_pct,
|
| 129 |
+
"volatility": volatility,
|
| 130 |
+
"high_52w": high_52w,
|
| 131 |
+
"low_52w": low_52w,
|
| 132 |
+
"avg_volume": avg_volume,
|
| 133 |
+
"rsi": rsi_latest,
|
| 134 |
+
"ma_signal": ma_signal,
|
| 135 |
+
"start_date": start_date.strftime("%Y-%m-%d"),
|
| 136 |
+
"end_date": end_date.strftime("%Y-%m-%d"),
|
| 137 |
+
"weekly_price_table": weekly_table,
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
results[ticker_upper] = {"df": df, "stats": stats, "error": None}
|
| 141 |
+
|
| 142 |
+
except Exception as e:
|
| 143 |
+
results[ticker_upper] = {
|
| 144 |
+
"df": None,
|
| 145 |
+
"stats": None,
|
| 146 |
+
"error": str(e),
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
return results
|