PrinceAI / data /fetcher.py
PrinceTires's picture
Upload data/fetcher.py with huggingface_hub
25a020f verified
Raw History Blame Contribute Delete
5.59 kB
"""
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