Building a stock portfolio tracker in Python involves integrating with financial APIs to fetch stock data, implementing functionality for users to add stocks to their portfolio, and calculating performance metrics such as gains/losses and portfolio diversification. Let’s outline the key components and then delve into the code implementation.
Platform Components:
- Stock Data Retrieval: We’ll use a financial API like Alpha Vantage or Yahoo Finance to fetch real-time stock data such as prices, volumes, and historical performance.
- User Interface: We’ll create a simple command-line interface (CLI) where users can interact with the portfolio tracker, add stocks, view their portfolio, and retrieve performance metrics.
- Portfolio Management: Users should be able to add and remove stocks from their portfolio, view their current holdings, and track changes in their portfolio over time.
- Performance Analysis: We’ll calculate key performance metrics such as gains/losses, overall portfolio value, diversification across different sectors or industries, and benchmarking against market indices.
Python Code Implementation:
Let’s start by integrating with a financial API to fetch real-time stock data. We’ll use the Alpha Vantage API in this example:
import requests
API_KEY = 'YOUR_API_KEY'
def get_stock_data(symbol):
url = f'https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={symbol}&apikey={API_KEY}'
response = requests.get(url)
data = response.json()
if 'Global Quote' in data:
return data['Global Quote']
else:
return None
This function fetches real-time stock data for a given stock symbol using the Alpha Vantage API. You’ll need to replace 'YOUR_API_KEY'
with your actual API key.
Next, let’s implement functionality for users to add stocks to their portfolio:
class Portfolio:
def __init__(self):
self.stocks = {}
def add_stock(self, symbol, quantity):
if symbol in self.stocks:
self.stocks[symbol] += quantity
else:
self.stocks[symbol] = quantity
def remove_stock(self, symbol, quantity):
if symbol in self.stocks:
self.stocks[symbol] -= quantity
if self.stocks[symbol] <= 0:
del self.stocks[symbol]
def get_portfolio_value(self):
total_value = 0
for symbol, quantity in self.stocks.items():
stock_data = get_stock_data(symbol)
if stock_data:
price = float(stock_data['05. price'])
total_value += price * quantity
return total_value
This class represents the user’s portfolio and provides methods to add and remove stocks, as well as calculate the total value of the portfolio based on current stock prices.
Now, let’s calculate gains/losses and portfolio diversification:
def calculate_gain_loss(initial_value, current_value):
return current_value - initial_value
def calculate_diversification(portfolio):
sector_weights = {}
total_value = portfolio.get_portfolio_value()
for symbol, quantity in portfolio.stocks.items():
stock_data = get_stock_data(symbol)
if stock_data:
sector = stock_data['08. currency']
if sector in sector_weights:
sector_weights[sector] += quantity * float(stock_data['05. price'])
else:
sector_weights[sector] = quantity * float(stock_data['05. price'])
diversification = {sector: (value / total_value) * 100 for sector, value in sector_weights.items()}
return diversification
These functions calculate gains/losses by subtracting the initial portfolio value from the current value, and portfolio diversification by determining the percentage of total portfolio value allocated to each sector or industry.
Finally, let’s create a simple CLI interface for users to interact with the portfolio tracker:
def main():
portfolio = Portfolio()
while True:
print("1. Add stock to portfolio")
print("2. Remove stock from portfolio")
print("3. View portfolio value")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
symbol = input("Enter stock symbol: ")
quantity = int(input("Enter quantity: "))
portfolio.add_stock(symbol, quantity)
elif choice == '2':
symbol = input("Enter stock symbol: ")
quantity = int(input("Enter quantity: "))
portfolio.remove_stock(symbol, quantity)
elif choice == '3':
value = portfolio.get_portfolio_value()
print(f"Portfolio value: ${value:.2f}")
print("Gains/Losses: ${:.2f}".format(calculate_gain_loss(initial_value, value)))
print("Diversification:")
for sector, weight in calculate_diversification(portfolio).items():
print(f"{sector}: {weight:.2f}%")
elif choice == '4':
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
This code presents users with options to add or remove stocks from their portfolio, view the current value of their portfolio along with gains/losses and diversification, and exit the application.
How to test the code?
- API Integration: Ensure the Alpha Vantage API key is correctly set in the
API_KEY
variable. Fetch stock data using theget_stock_data
function with a valid stock symbol like “AAPL” for Apple Inc. - Portfolio Management: Test adding and removing stocks from the portfolio using the
add_stock
andremove_stock
methods of thePortfolio
class. For example, add 10 shares of Apple and then remove 5 shares. - Portfolio Value: View the total portfolio value and gains/losses by selecting the appropriate option in the CLI. This should display the current value of the portfolio and any changes in value since the last check.
- Diversification Analysis: Check the diversification of the portfolio by selecting the relevant option. This should display the allocation of portfolio value across different sectors or industries.
- Exiting the Program: Select the option to exit the program. This should terminate the CLI interface.
By following these steps, you can effectively test the stock portfolio tracker and observe its