CodeForFinance
Python

Build a Portfolio Tracker in Python

Tracking your portfolio in spreadsheets is error-prone and tedious. In this tutorial, we build a Python portfolio tracker that fetches live prices, calculates profit and loss, and visualises your allocation. You will have a tool you can run daily to see exactly where you stand.

Prerequisites

  • Basic Python
  • pip installed
  • Free API key from Alpha Vantage or Yahoo Finance

Step 1.Install dependencies

yfinance gives us free stock data, pandas for data handling, matplotlib for charts.

pip install yfinance pandas matplotlib

Step 2.Define your holdings

Store your positions with the number of shares and your average purchase price.

import pandas as pd
import yfinance as yf

holdings = {
    "AAPL": {"shares": 10, "avg_cost": 150.00},
    "MSFT": {"shares": 5, "avg_cost": 280.00},
    "GOOGL": {"shares": 3, "avg_cost": 120.00},
    "AMZN": {"shares": 8, "avg_cost": 140.00},
    "NVDA": {"shares": 15, "avg_cost": 45.00},
}

Step 3.Fetch live prices

yfinance downloads the latest closing price for each ticker in a single API call.

def get_current_prices(tickers: list) -> dict:
    data = yf.download(tickers, period="1d")["Close"]
    if len(tickers) == 1:
        return {tickers[0]: float(data.iloc[-1])}
    return {t: float(data[t].iloc[-1]) for t in tickers}

prices = get_current_prices(list(holdings.keys()))
print(prices)

Step 4.Calculate P&L

For each holding, calculate the unrealised profit or loss in both dollar and percentage terms.

rows = []
for ticker, info in holdings.items():
    current = prices[ticker]
    cost_basis = info["shares"] * info["avg_cost"]
    market_value = info["shares"] * current
    pnl = market_value - cost_basis
    pnl_pct = (pnl / cost_basis) * 100
    rows.append({
        "Ticker": ticker,
        "Shares": info["shares"],
        "Avg Cost": f"${info['avg_cost']:.2f}",
        "Current": f"${current:.2f}",
        "Market Value": f"${market_value:,.2f}",
        "P&L": f"${pnl:,.2f}",
        "P&L %": f"{pnl_pct:.1f}%"
    })

df = pd.DataFrame(rows)
print(df.to_string(index=False))

Step 5.Plot allocation pie chart

A pie chart gives you a quick visual of how concentrated or diversified your portfolio is.

import matplotlib.pyplot as plt

values = [holdings[t]["shares"] * prices[t] for t in holdings]
labels = list(holdings.keys())

plt.figure(figsize=(8, 8))
plt.pie(values, labels=labels, autopct="%1.1f%%", startangle=140)
plt.title("Portfolio Allocation")
plt.savefig("allocation.png", dpi=150, bbox_inches="tight")
plt.show()

Expected Output

Ticker  Shares  Avg Cost   Current  Market Value       P&L   P&L %
  AAPL      10   $150.00   $195.20     $1,952.00   $452.00   30.1%
  MSFT       5   $280.00   $420.50     $2,102.50   $702.50   50.2%

Next Steps

  • Add bond and ETF tracking
  • Email yourself a daily report
  • Store historical snapshots in SQLite

Recommended Reading

Quantitative Portfolio Management

As an Amazon Associate we may earn from qualifying purchases.

Browse All Tutorials →

Developer Essentials

As an Amazon Associate we may earn from qualifying purchases.