File size: 1,151 Bytes
cfafc17
 
 
4a31363
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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