# import yfinance as yf # DEPRECATED due to Hugging Face IP blocks from yahooquery import Ticker from datetime import datetime, timedelta from sqlalchemy.orm import Session from ..models import Stock, StockPrice from ..database import SessionLocal import pandas as pd import requests def get_session(): """Create a high-availability session for yahooquery.""" s = requests.Session() # Random browser-like headers (use a slightly older Chrome to ensure curl_cffi compatibility) s.headers.update({ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "Connection": "keep-alive" }) return s def get_ticker_history(ticker_symbol, period="1y"): """ Enhanced helper to get history using yahooquery. """ try: t = Ticker(ticker_symbol, session=get_session()) df = t.history(period=period) if df is None: return pd.DataFrame() if isinstance(df, dict): # YahooQuery returns a dictionary of errors if failed print(f"DEBUG: YahooQuery error for {ticker_symbol}: {df}") return pd.DataFrame() # Reset index to extract date and symbol if isinstance(df, pd.DataFrame): df = df.reset_index() # Case 1: Multi-indexed (symbol, date) if 'symbol' in df.columns and 'date' in df.columns: # Filter for the symbol we wanted (in case of batch) df = df[df['symbol'] == ticker_symbol] df.set_index('date', inplace=True) # Case 2: Single-indexed (just date) elif 'date' in df.columns: df.set_index('date', inplace=True) # Case 3: Current index is the date (typical for single ticker) else: pass return df except Exception as e: print(f"ERROR: Fetching history for {ticker_symbol}: {e}") return pd.DataFrame() def get_ticker_info(ticker_symbol): """ Helper to get ticker info from yahooquery. """ try: t = Ticker(ticker_symbol, session=get_session()) price = t.price summary = t.summary_profile price_dict = price.get(ticker_symbol, {}) if isinstance(price, dict) else {} summary_dict = summary.get(ticker_symbol, {}) if isinstance(summary, dict) else {} return { 'longName': price_dict.get('longName', ticker_symbol), 'exchange': price_dict.get('exchangeName', 'UNKNOWN'), 'sector': summary_dict.get('sector', 'Unknown'), 'industry': summary_dict.get('industry', 'Unknown') } except Exception as e: print(f"ERROR: Fetching info for {ticker_symbol}: {e}") return { 'longName': ticker_symbol, 'exchange': 'UNKNOWN', 'sector': 'Unknown', 'industry': 'Unknown' } def fetch_and_store_stock_data(ticker: str, period: str = "1y"): """ Fetches stock data from Yahoo Finance and stores it in the database. """ # We'll try to fetch as is first, unless it's obviously a malformed ticker. # We will handle normalization inside the fetching logic if empty. original_ticker = ticker.upper() print(f"Fetching data for {original_ticker}...") hist = get_ticker_history(original_ticker, period=period) # If empty, try to normalize for Indian stocks (e.g., RELIANCE -> RELIANCE.NS) if hist.empty and not any(suffix in original_ticker for suffix in [".NS", ".BO", "=", "^", "-"]): if len(original_ticker) >= 3 and original_ticker.isalpha(): normalized_ticker = original_ticker + ".NS" print(f"No data for {original_ticker}, trying normalized: {normalized_ticker}") hist = get_ticker_history(normalized_ticker, period=period) if not hist.empty: ticker = normalized_ticker else: # Try .BO as last resort for Indian stocks normalized_ticker = original_ticker + ".BO" print(f"No data for .NS, trying .BO: {normalized_ticker}") hist = get_ticker_history(normalized_ticker, period=period) if not hist.empty: ticker = normalized_ticker else: ticker = original_ticker if hist.empty: print(f"No data found for {ticker}") return None db: Session = SessionLocal() try: # Check if stock exists stock = db.query(Stock).filter(Stock.ticker == ticker).first() if not stock: # Try to get info from yahooquery si = get_ticker_info(ticker) name = si.get('longName', ticker) exchange = si.get('exchange', 'UNKNOWN') sector = si.get('sector', 'Unknown') industry = si.get('industry', 'Unknown') # Use nested try for atomic insertion try: stock = Stock(ticker=ticker, name=name, exchange=exchange, sector=sector, industry=industry) db.add(stock) db.commit() db.refresh(stock) except Exception as inner_e: db.rollback() # Re-query in case it was created by another thread stock = db.query(Stock).filter(Stock.ticker == ticker).first() if not stock: raise inner_e # Update sector/industry if missing for existing stock if not stock.sector or not stock.industry or stock.sector == 'Unknown': si = get_ticker_info(ticker) stock.sector = si.get('sector', 'Unknown') stock.industry = si.get('industry', 'Unknown') db.commit() # Store prices for date, row in hist.iterrows(): # Skip if any essential price is NaN try: # yahooquery uses lowercase o = row.get('open') h = row.get('high') l = row.get('low') c = row.get('close') v = row.get('volume', 0) if pd.isna(o) or pd.isna(h) or pd.isna(l) or pd.isna(c): continue # Check if price exists for this date # Normalize date to date object if hasattr(date, 'date'): price_date = date.date() else: price_date = pd.to_datetime(date).date() existing_price = db.query(StockPrice).filter( StockPrice.stock_id == stock.id, StockPrice.date == price_date ).first() if not existing_price: new_price = StockPrice( stock_id=stock.id, date=price_date, open=float(o), high=float(h), low=float(l), close=float(c), volume=int(v) ) db.add(new_price) except Exception as e: print(f"Error processing row for {ticker} at {date}: {e}") continue db.commit() print(f"Successfully stored data for {ticker}") return hist except Exception as e: print(f"Error storing data: {e}") db.rollback() return None finally: db.close() if __name__ == "__main__": # Test fetch_and_store_stock_data("AAPL", period="1mo") fetch_and_store_stock_data("RELIANCE.NS", period="1mo")