Build a Simple Stock Portfolio Tracker in Python

Hussnain Akbar
4 min readDec 24, 2024

In today’s article, we’ll build a basic stock portfolio tracker using Python. This tool will allow you to input the stocks in your portfolio, fetch their real-time market prices, and calculate important statistics such as the total portfolio value and percentage allocation of each stock. We’ll also display a pie chart to visualize your portfolio allocation. The process is easy to follow, even for those who are new to Python programming.

Let’s dive into the code by importing essential libraries!

import pandas as pd
import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt

Fetch Stock Price using yfinance: The get_stock_price() function allows us to fetch the real-time price of a stock by using its ticker symbol. We use the yfinance library to do this. The function will return the last closing price of the stock.

def get_stock_price(ticker):
"""
Fetches the latest stock price using yfinance.
"""
try:
stock = yf.Ticker(ticker)
price = stock.history(period="1d")['Close'].iloc[-1]
return price
except Exception as e:
print(f"Error fetching price for {ticker}: {e}")
return None

Portfolio Tracker Function The main function, portfolio_tracker(), is where all the action happens. For example, this function will help us to gather user input for the number of stocks and their details (ticker and quantity). It will then fetch stock prices in real time to calculate the total value of each stock in the portfolio and the total portfolio value. In the last, it will display the portfolio in a table, and also create a pie chart to visualize the portfolio allocation.

def portfolio_tracker():
# Step 1: Gather user input with error handling
while True:
try:
num_stocks = int(input("Enter the number of stocks in your portfolio: "))
if num_stocks <= 0:
raise ValueError("Number of stocks must be greater than 0.")
break
except ValueError as e:
print(f"Invalid input: {e}")

# Initialize an empty list to store portfolio data
portfolio_data = []

for i in range(num_stocks):
while True:
try:
stock = input(f"Enter the ticker symbol of stock {i + 1}: ").upper()
quantity = int(input(f"Enter the quantity of {stock}: "))
if quantity <= 0:
raise ValueError("Quantity must be greater than 0.")

# Fetch real-time stock price
price = get_stock_price(stock)
if price is None:
raise ValueError(f"Unable to fetch price for {stock}.")

portfolio_data.append({'Stock': stock, 'Quantity': quantity, 'Price': price})
break
except ValueError as e:
print(f"Invalid input: {e}")

# Step 2: Create a DataFrame
portfolio_df = pd.DataFrame(portfolio_data)

# Step 3: Calculate Total Value of Each Stock
portfolio_df['Value'] = portfolio_df['Quantity'] * portfolio_df['Price']

# Step 4: Calculate Total Portfolio Value
total_portfolio_value = portfolio_df['Value'].sum()

# Step 5: Calculate Percentage Allocation
portfolio_df['Allocation (%)'] = (portfolio_df['Value'] / total_portfolio_value) * 100

# Step 6: Display Results
print("\nPortfolio Summary:")
print(portfolio_df)
print(f"\nTotal Portfolio Value: ${total_portfolio_value:,.2f}")

# Step 7: Visualization
plt.figure(figsize=(8, 6))
plt.pie(portfolio_df['Allocation (%)'], labels=portfolio_df['Stock'], autopct='%1.1f%%', startangle=140)
plt.title("Portfolio Allocation")
plt.show()

# Run the Portfolio Tracker
portfolio_tracker()

Explanation of Key Steps:

  • User Input & Error Handling: We first ask the user how many stocks are in their portfolio. We ensure that the input is valid (i.e., it’s a positive integer). We then collect the stock ticker symbols and quantities for each stock.
  • Fetching Stock Data: The function get_stock_price() is used to retrieve real-time stock prices using the yfinance library. We handle any errors in case the stock data cannot be fetched (e.g., due to an incorrect ticker).
  • Data Calculation: After gathering the stock details, we calculate the total value of each stock by multiplying the quantity of the stock by its price. We also calculate the percentage allocation of each stock in the portfolio by dividing its value by the total portfolio value.
  • Visualization: The portfolio allocation is displayed in a pie chart using matplotlib. This provides a quick visual representation of how much each stock contributes to the total portfolio value.

Running the Portfolio Tracker:

When you run the program, it will prompt you to enter the number of stocks in your portfolio. Then, for each stock, you’ll be asked to enter the ticker symbol and the quantity of shares you hold. The program will fetch the latest price for each stock, calculate the total portfolio value, and display the result in a table format. Finally, it will show a pie chart representing the portfolio allocation.

Example Output:

After running the code and entering stock details (e.g., Apple, Tesla, and Amazon), you’ll see something like this:

Portfolio Summary:
Stock Quantity Price Value Allocation (%)
0 AAPL 10 150.00 1500.00 15.00
1 TSLA 5 650.00 3250.00 32.50
2 AMZN 7 3300.00 23100.00 52.50

Total Portfolio Value: $27,850.00

A pie chart will be also be displayed to visually represent how your portfolio is distributed across the different stocks.

Feel free to share your thoughts or improvements in the comments! Happy coding!

--

--

Hussnain Akbar
Hussnain Akbar

Written by Hussnain Akbar

Web Developer with Flask/Django, and Quantitative Analyst with experience of Python, Machine Learning and R.

No responses yet