Skip to the content.

Build a stock portfolio tracker in Python

In this tutorial you will build a portfolio tracker that reads live quotes for all your holdings in one request. It prints each position’s value, today’s change and profit against your average cost, plus portfolio totals. It uses Yahoo Finance Turbo and about 40 lines of Python. Not investment advice.

What you need: Python 3.8+, pip install requests, and a free RapidAPI key.

1. Subscribe to the free plan

  1. Open the Yahoo Finance Turbo on RapidAPI and subscribe to the free Basic plan (20 requests a month).
  2. Copy your X-RapidAPI-Key and export it:
export RAPIDAPI_KEY=your_key

2. A small helper to call the API

The helper sends your key, retries rate limits (HTTP 429) and server errors (5xx) with a growing wait, and stops with the API’s error message on anything else.

"""Track a stock portfolio: live value, day change and profit against cost.

Uses Yahoo Finance Turbo on RapidAPI:
https://rapidapi.com/apiwren-apiwren-default/api/yahoo-finance-turbo
"""
import os, sys, time
import requests

HOST = "yahoo-finance-turbo.p.rapidapi.com"
HEADERS = {"X-RapidAPI-Key": os.environ["RAPIDAPI_KEY"], "X-RapidAPI-Host": HOST}


def get(path, **params):
    """GET one endpoint. Retries rate limits (429) and server errors (5xx)."""
    for attempt in range(4):
        r = requests.get(f"https://{HOST}{path}", headers=HEADERS, params=params, timeout=90)
        retry = r.status_code == 429 or r.status_code in range(500, 600)
        if retry and attempt != 3:
            time.sleep(float(r.headers.get("Retry-After") or 2 ** (attempt + 1)))
            continue
        if not r.ok:
            sys.exit(f"HTTP {r.status_code}: {r.text[:300]}")
        body = r.json()
        if isinstance(body, dict) and body.get("success") is False:
            sys.exit(f"API error: {body.get('error')}")
        return body

3. List your holdings

Each holding is a symbol with a share count and an average cost per share.

# symbol: (shares, average cost per share)
HOLDINGS = {"AAPL": (10, 150.00), "MSFT": (5, 310.00), "NVDA": (20, 45.00), "KO": (30, 58.00), "VOO": (4, 410.00)}

4. Value the portfolio

/market/v2/get-quotes takes up to 20 comma-separated symbols and returns quoteResponse.result with regularMarketPrice, regularMarketChange and the other Yahoo quote fields. One request values the whole portfolio.

def quotes(symbols):
    body = get("/market/v2/get-quotes", symbols=",".join(symbols), region="US")
    return {q["symbol"]: q for q in body["quoteResponse"]["result"]}


def main():
    q = quotes(HOLDINGS)
    total = cost = day = 0.0
    print("symbol    shares     price     value    day chg    profit")
    for sym, (shares, avg) in HOLDINGS.items():
        price = q[sym]["regularMarketPrice"]
        value, basis = price * shares, avg * shares
        change = (q[sym].get("regularMarketChange") or 0) * shares
        total, cost, day = total + value, cost + basis, day + change
        print(f"{sym.ljust(8)}{shares:8}{price:10.2f}{value:10,.0f}{change:+11,.0f}"
              f"{value - basis:+10,.0f} ({(value - basis) / basis:+.0%})")
    print(f"TOTAL{total:31,.0f}{day:+11,.0f}{total - cost:+10,.0f} ({(total - cost) / cost:+.0%})")


if __name__ == "__main__":
    main()

5. Run it

python yahoo_portfolio_tracker.py

Real output from a run on 2026-11-28:

symbol    shares     price     value    day chg    profit
AAPL          10    358.54     3,585        +30    +2,085 (+139%)
MSFT           5    492.85     2,464        +15      +914 (+59%)
NVDA          20    150.49     3,010        +24    +2,110 (+234%)
KO            30     97.40     2,922         -6    +1,182 (+68%)
VOO            4    669.79     2,679        +44    +1,039 (+63%)
TOTAL                         14,661       +106    +7,331 (+100%)

The complete script is in examples/yahoo_portfolio_tracker.py.

Tips

Next steps