Python Beginner

Financial Statement Analyzer

Fetch and display a company's income statement, balance sheet, and cash flow data from SEC filings.

Note: The code examples in this tutorial have not yet been verified against the live API. If you encounter issues, please let us know.

Prerequisites

  • Python 3.8 or later
  • The requests library (pip install requests)
  • A stockdata.dev API key — get one free

This tutorial builds on the Company Lookup CLI. If you haven't already, start there to learn the basics of calling the API.

The Code

Create a file called financials.py. This script fetches the most recent annual financial statements for a company and formats the numbers for easy reading. Use the --history flag to compare multiple years side by side.

Python
import sys
import requests

API_KEY = "your_api_key_here"
BASE_URL = "https://api.stockdata.dev/v1"
HEADERS = {"X-API-Key": API_KEY}


def fmt(value):
    """Format a number as $X.XB, $X.XM, or $X.XK."""
    if value is None:
        return "N/A"
    if abs(value) >= 1e12:
        return f"${value / 1e12:.1f}T"
    if abs(value) >= 1e9:
        return f"${value / 1e9:.1f}B"
    if abs(value) >= 1e6:
        return f"${value / 1e6:.1f}M"
    return f"${value / 1e3:.1f}K"


def get_financials(ticker, limit=1):
    """Fetch financial statements from the API."""
    resp = requests.get(
        f"{BASE_URL}/company/{ticker}/financials",
        headers=HEADERS,
        params={"period": "annual", "limit": limit},
    )
    if resp.status_code != 200:
        print(f"Error: {resp.json().get('error', resp.text)}")
        sys.exit(1)
    return resp.json()


def show_single(data):
    """Display the most recent period's financials."""
    f = data["financials"][0]
    inc = f["income_statement"]
    bal = f["balance_sheet"]
    cf = f["cash_flow"]

    print(f"{data['ticker']} - FY {f['fiscal_year']}")
    print("─" * 33)
    print("Income Statement")
    print(f"  Revenue:        {fmt(inc.get('revenue')):>10}")
    print(f"  Net Income:     {fmt(inc.get('net_income')):>10}")
    eps = inc.get("eps_diluted")
    print(f"  EPS (diluted):  {f'${eps:.2f}' if eps else 'N/A':>10}")
    print()
    print("Balance Sheet")
    print(f"  Total Assets:   {fmt(bal.get('total_assets')):>10}")
    print(f"  Cash:           {fmt(bal.get('cash')):>10}")
    print(f"  Total Liab:     {fmt(bal.get('total_liabilities')):>10}")
    print()
    print("Cash Flow")
    print(f"  Operating CF:   {fmt(cf.get('operating_cash_flow')):>10}")


def show_history(data):
    """Display multiple periods as a comparison table."""
    periods = data["financials"]
    years = [f"FY {p['fiscal_year']}" for p in periods]

    print(f"{data['ticker']} - Financial History")
    print("─" * (20 + 12 * len(years)))

    # Header row
    print(f"{'':<20}" + "".join(f"{y:>12}" for y in years))
    print()

    rows = [
        ("Revenue", "income_statement", "revenue"),
        ("Net Income", "income_statement", "net_income"),
        ("Total Assets", "balance_sheet", "total_assets"),
        ("Cash", "balance_sheet", "cash"),
        ("Total Liabilities", "balance_sheet", "total_liabilities"),
        ("Operating CF", "cash_flow", "operating_cash_flow"),
    ]

    for label, section, field in rows:
        vals = [fmt(p[section].get(field)) for p in periods]
        print(f"{label:<20}" + "".join(f"{v:>12}" for v in vals))


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python financials.py AAPL")
        print("       python financials.py AAPL --history")
        sys.exit(1)

    ticker = sys.argv[1].upper()
    history = "--history" in sys.argv

    if history:
        data = get_financials(ticker, limit=4)
        show_history(data)
    else:
        data = get_financials(ticker, limit=1)
        show_single(data)

How It Works

The script calls a single endpoint that returns all three financial statements in one response:

Financials Endpoint: GET /v1/company/{ticker}/financials

HTTP
GET https://api.stockdata.dev/v1/company/AAPL/financials?period=annual&limit=4
X-API-Key: your_api_key_here

The response contains a financials array. Each element represents one filing period and contains three nested objects:

  • income_statement — revenue, net income, EPS, cost of revenue, operating expenses
  • balance_sheet — total assets, cash, total liabilities, equity, current assets
  • cash_flow — operating cash flow, capital expenditures, free cash flow
JSON
{
  "ticker": "AAPL",
  "financials": [
    {
      "fiscal_year": 2025,
      "fiscal_period": "FY",
      "filed": "2025-10-31",
      "income_statement": {
        "revenue": 383285000000,
        "net_income": 96995000000,
        "eps_diluted": 6.13
      },
      "balance_sheet": {
        "total_assets": 364980000000,
        "cash": 29943000000,
        "total_liabilities": 287123000000
      },
      "cash_flow": {
        "operating_cash_flow": 110543000000
      }
    }
  ]
}

The period parameter accepts annual or quarterly. The limit parameter controls how many periods to return, up to 10.

The fmt() helper function converts raw numbers like 383285000000 into human-readable strings like $383.3B. It picks the right suffix (T, B, M, or K) based on magnitude.

Running It

Run the script with a ticker to see the most recent annual financials:

Shell
$ python financials.py AAPL

Apple Inc. (AAPL) - FY 2025
─────────────────────────────────
Income Statement
  Revenue:          $383.3B
  Net Income:        $97.0B
  EPS (diluted):      $6.13

Balance Sheet
  Total Assets:     $365.0B
  Cash:              $29.9B
  Total Liab:       $287.1B

Cash Flow
  Operating CF:     $110.5B

Comparing Periods

Add the --history flag to see up to four years side by side. This makes it easy to spot revenue growth or changes in cash position:

Shell
$ python financials.py AAPL --history

AAPL - Financial History
────────────────────────────────────────────────────────────────────
                         FY 2025      FY 2024      FY 2023      FY 2022

Revenue                  $383.3B      $391.0B      $383.9B      $394.3B
Net Income                $97.0B      $101.0B       $97.0B       $99.8B
Total Assets             $365.0B      $352.6B      $352.6B      $352.8B
Cash                      $29.9B       $29.9B       $30.7B       $23.6B
Total Liabilities        $287.1B      $279.4B      $290.4B      $302.1B
Operating CF             $110.5B      $118.3B      $110.5B      $122.2B

The table format makes year-over-year trends immediately visible. For example, you can quickly see how Apple's cash position changed or whether revenue is growing.

Enhancements

Here are a few ways to extend this tool:

  • Quarterly data — Change period=annual to period=quarterly and add a --quarterly flag. This gives you four quarters per year instead of annual totals.
  • Export to CSV — Add a --csv flag that writes the data to a CSV file. Use Python's built-in csv module to write the same rows and columns to a file.
  • More fields — The API returns many more fields in each section. Add gross profit, operating income, R&D expenses, debt, and equity for a more complete picture.
  • Calculated ratios — Compute margins (net income / revenue), debt-to-equity, current ratio, and other metrics from the raw numbers.
  • Environment variable for API key — Read the key from STOCKDATA_API_KEY instead of hardcoding it: os.environ.get("STOCKDATA_API_KEY").

Ready to build?

Get your free API key and start coding in minutes.

Get Free API Key