The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Monitor stock portfolios using Python

Monitoring stock portfolios using Python involves fetching real-time or delayed stock data, calculating portfolio metrics, and visualizing performance. Here’s a comprehensive guide on how to build a Python script or small application for this purpose.


1. Fetching Stock Data

To monitor a stock portfolio, you first need to retrieve stock price data. Popular APIs and libraries for this include:

  • yfinance (Yahoo Finance API wrapper)

  • Alpha Vantage API

  • IEX Cloud API

  • pandas_datareader

For simplicity and free usage, yfinance is commonly used.

python
import yfinance as yf # Example: Download historical data for Apple (AAPL) data = yf.download('AAPL', period='1mo', interval='1d') print(data.tail())

2. Defining Your Portfolio

A portfolio can be represented as a dictionary, where keys are ticker symbols and values are the number of shares held.

python
portfolio = { 'AAPL': 50, 'MSFT': 30, 'TSLA': 20, 'GOOGL': 10 }

3. Fetch Current Prices for Portfolio Stocks

Using yfinance, get the latest price for each stock.

python
def get_current_prices(tickers): prices = {} for ticker in tickers: stock = yf.Ticker(ticker) prices[ticker] = stock.history(period='1d')['Close'][0] return prices tickers = list(portfolio.keys()) current_prices = get_current_prices(tickers) print(current_prices)

4. Calculate Portfolio Value and Performance

Calculate total portfolio value and individual stock contributions.

python
portfolio_value = 0 for ticker, shares in portfolio.items(): price = current_prices[ticker] value = shares * price portfolio_value += value print(f"{ticker}: {shares} shares x ${price:.2f} = ${value:.2f}") print(f"Total Portfolio Value: ${portfolio_value:.2f}")

5. Tracking Historical Portfolio Value

To analyze portfolio performance over time, download historical prices and calculate daily portfolio value.

python
import pandas as pd def get_historical_prices(tickers, start_date, end_date): data = yf.download(tickers, start=start_date, end=end_date)['Close'] return data # Example dates start_date = '2024-01-01' end_date = '2024-05-15' prices = get_historical_prices(tickers, start_date, end_date) # Multiply prices by shares owned for ticker in tickers: prices[ticker] *= portfolio[ticker] # Sum across all stocks to get daily portfolio value portfolio_history = prices.sum(axis=1) print(portfolio_history.tail())

6. Visualizing Portfolio Performance

Use matplotlib or plotly to visualize portfolio value over time.

python
import matplotlib.pyplot as plt plt.figure(figsize=(12,6)) plt.plot(portfolio_history.index, portfolio_history.values) plt.title("Portfolio Value Over Time") plt.xlabel("Date") plt.ylabel("Portfolio Value ($)") plt.grid(True) plt.show()

7. Monitoring Portfolio Metrics

You can compute key portfolio metrics such as daily returns, cumulative returns, and volatility.

python
# Daily returns daily_returns = portfolio_history.pct_change().dropna() # Cumulative returns cumulative_returns = (1 + daily_returns).cumprod() - 1 # Volatility (standard deviation of daily returns) volatility = daily_returns.std() * (252 ** 0.5) # Annualized volatility print(f"Annualized Volatility: {volatility:.2%}") plt.figure(figsize=(12,6)) plt.plot(cumulative_returns.index, cumulative_returns.values) plt.title("Cumulative Returns") plt.xlabel("Date") plt.ylabel("Cumulative Return") plt.grid(True) plt.show()

8. Automating with Alerts

You can build alerting logic, e.g., if portfolio value drops by a certain percentage, send an email or notification.

python
threshold_drop = 0.05 # 5% drop if daily_returns[-1] < -threshold_drop: print("Alert: Portfolio value dropped more than 5% today!") # Integrate with email or messaging APIs here

Summary

By combining these steps, you can build a Python script or application that:

  • Retrieves real-time or historical stock data

  • Calculates portfolio value and performance

  • Visualizes portfolio growth or losses

  • Tracks important metrics like returns and volatility

  • Sends alerts based on your custom thresholds

Python libraries such as yfinance, pandas, matplotlib, and numpy are essential tools for this task.


If you want, I can provide a complete Python script with all these functionalities combined into one file. Would you like that?

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About