CoolFace
Apppublic

hwdevelops/equitylens

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
fetcher.py83 linesDownload Raw Back to data
1"""
2fetcher.py — Centralized data layer for EquityLens.
3
4All modules should import from here instead of calling yfinance directly.
5This ensures consistent data handling and a single point of maintenance.
6"""
7
8import yfinance as yf
9import pandas as pd
10
11
12def get_price_history(ticker: str, period: str = "1y") -> pd.DataFrame:
13    """
14    Fetch historical OHLCV price data for a given ticker.
15
16    Args:
17        ticker: Stock symbol as a string, e.g. "AAPL"
18        period: How far back to fetch. Options: 1mo, 3mo, 6mo, 1y, 2y, 5y
19    
20    Returns:
21        A pandas DataFrame with columns: Open, High, Low, Close, Volume
22        Returns an empty DataFrame if the ticker is invalid or data unavailable.
23    """
24    try:
25        stock = yf.Ticker(ticker)
26        df = stock.history(period=period)
27
28        if df.empty:
29            print(f"[Warning] No price data found for ticker: {ticker}")
30            return pd.DataFrame()
31
32        return df
33
34    except Exception as e:
35        print(f"[Error] Could not fetch price data for {ticker}: {e}")
36        return pd.DataFrame()
37
38
39def get_financials(ticker: str) -> dict:
40    """
41    Fetch fundamental financial statements for a given ticker.
42
43    Args:
44        ticker: Stock symbol as a string, e.g. "AAPL"
45
46    Returns:
47        A dictionary with keys: 'income_stmt', 'balance_sheet', 'cash_flow'
48        Each value is a pandas DataFrame. Returns empty dict on failure.
49    """
50    try:
51        stock = yf.Ticker(ticker)
52
53        financials = {
54            "income_stmt":   stock.income_stmt,
55            "balance_sheet": stock.balance_sheet,
56            "cash_flow":     stock.cash_flow,
57            "info":          stock.info
58        }
59
60        return financials
61
62    except Exception as e:
63        print(f"[Error] Could not fetch financials for {ticker}: {e}")
64        return {}
65    
66def get_current_price(ticker: str):
67    """
68    Fetch the current price for a given ticker.
69
70    Args:
71        ticker: Stock symbol as a string e.g. "AAPL"
72    
73    Returns:
74        Current price as a float, or None if unavailable.
75    """
76    try:
77        stock = yf.Ticker(ticker)
78        info = stock.info
79        price = info["currentPrice"]
80        return price
81    except Exception as e:
82        print(f"[Error] Could not fetch current price for {ticker}: {e}")
83        return None