pvyas96's picture
Update src/utils.py
4a31363 verified
import yfinance as yf
import pandas as pd
def fetch_financials(ticker_symbol: str, freq: str = "annual"):
"""Fetch income statement and cashflow for a given ticker."""
ticker = yf.Ticker(ticker_symbol)
# Use get_* methods if available
try:
income = ticker.get_income_stmt(freq=freq)
except AttributeError:
# fallback to older API
income = ticker.financials
try:
cash = ticker.get_cashflow(freq=freq)
except AttributeError:
cash = ticker.cashflow
# If they return dict (as_dict=True), convert to DataFrame
if isinstance(income, dict):
income = pd.DataFrame(income)
if isinstance(cash, dict):
cash = pd.DataFrame(cash)
return income, cash
def clean_financials(df: pd.DataFrame) -> pd.DataFrame:
"""Clean / transform the financials DataFrame for better plotting."""
# Transpose so dates become rows
df2 = df.T.copy()
# Optionally sort by date
try:
# If columns are strings of dates or period
df2.index = pd.to_datetime(df2.index)
df2 = df2.sort_index()
except Exception:
pass
return df2