Introduction
In this tutorial, you'll learn how to track and analyze stock investments using Python, similar to how the US government tracks its Intel stake. We'll build a simple stock portfolio tracker that can monitor stock prices, calculate gains/losses, and display investment performance. This tutorial is perfect for beginners who want to understand how investment tracking works and how to apply basic Python programming to financial data.
Prerequisites
- Basic understanding of Python programming
- Python 3.x installed on your computer
- Internet connection to access financial data
- Optional: A free API key from a financial data provider (like Alpha Vantage or Yahoo Finance)
Step-by-Step Instructions
Step 1: Set up your Python environment
First, we need to install the required Python libraries. Open your terminal or command prompt and run:
pip install yfinance pandas
This installs two essential libraries: yfinance for fetching stock data, and pandas for data manipulation.
Step 2: Create your main Python script
Create a new file called stock_tracker.py and start with the basic imports:
import yfinance as yf
import pandas as pd
def get_stock_data(symbol):
"""Fetch stock data for a given symbol"""
stock = yf.Ticker(symbol)
return stock.info
# Example usage
if __name__ == "__main__":
data = get_stock_data("INTC")
print(data)
This code imports the necessary libraries and creates a function to fetch stock information for a given symbol. We're using Intel's ticker symbol "INTC" as an example.
Step 3: Create a portfolio class
Now we'll create a class to manage our stock portfolio:
class StockPortfolio:
def __init__(self):
self.stocks = {}
def add_stock(self, symbol, quantity, purchase_price):
"""Add a stock to our portfolio"""
self.stocks[symbol] = {
'quantity': quantity,
'purchase_price': purchase_price
}
def get_current_price(self, symbol):
"""Get current stock price"""
stock = yf.Ticker(symbol)
return stock.info.get('currentPrice', 0)
def calculate_value(self, symbol):
"""Calculate current value of a stock"""
current_price = self.get_current_price(symbol)
quantity = self.stocks[symbol]['quantity']
return current_price * quantity
def calculate_gain_loss(self, symbol):
"""Calculate gain or loss for a stock"""
current_price = self.get_current_price(symbol)
purchase_price = self.stocks[symbol]['purchase_price']
quantity = self.stocks[symbol]['quantity']
gain_loss = (current_price - purchase_price) * quantity
return gain_loss
def display_portfolio(self):
"""Display portfolio summary"""
print("\nPortfolio Summary:")
print("-" * 50)
total_value = 0
total_gain_loss = 0
for symbol, details in self.stocks.items():
current_value = self.calculate_value(symbol)
gain_loss = self.calculate_gain_loss(symbol)
total_value += current_value
total_gain_loss += gain_loss
print(f"{symbol}: ${current_value:.2f} (Gain/Loss: ${gain_loss:.2f})")
print("-" * 50)
print(f"Total Portfolio Value: ${total_value:.2f}")
print(f"Total Gain/Loss: ${total_gain_loss:.2f}")
This class handles all portfolio operations including adding stocks, calculating current values, and determining gains or losses. It's designed to be simple and educational for beginners.
Step 4: Build the main tracking function
Now we'll create the main function that puts everything together:
def main():
# Create a new portfolio
portfolio = StockPortfolio()
# Add some stocks to our portfolio (example with Intel)
portfolio.add_stock("INTC", 100, 20.47) # 100 shares at $20.47 each
# Display portfolio information
portfolio.display_portfolio()
# Show more detailed information
print("\nDetailed Stock Information:")
print("-" * 30)
for symbol in portfolio.stocks:
stock = yf.Ticker(symbol)
info = stock.info
print(f"Symbol: {symbol}")
print(f"Current Price: ${info.get('currentPrice', 'N/A')}")
print(f"Previous Close: ${info.get('previousClose', 'N/A')}")
print(f"52 Week High: ${info.get('fiftyTwoWeekHigh', 'N/A')}")
print(f"52 Week Low: ${info.get('fiftyTwoWeekLow', 'N/A')}")
print("-" * 30)
if __name__ == "__main__":
main()
This function creates a portfolio, adds stocks (in this case, Intel shares), and displays both summary information and detailed stock data. The example uses the same price ($20.47) that was mentioned in the news article for Intel's stock conversion.
Step 5: Run your stock tracker
Save your file and run it in your terminal:
python stock_tracker.py
You should see output showing your portfolio value and gain/loss calculations. The program will fetch real-time data from Yahoo Finance, which is why you need an internet connection.
Step 6: Extend your portfolio
Try adding more stocks to your portfolio to see how it handles multiple investments:
# Add more stocks to your portfolio
portfolio.add_stock("AMD", 50, 100.00) # 50 shares of AMD at $100
portfolio.add_stock("NVDA", 25, 150.00) # 25 shares of NVIDIA at $150
This demonstrates how you can track multiple investments and see how each contributes to your overall portfolio performance.
Step 7: Add error handling
Let's make our program more robust by adding error handling:
def safe_get_stock_data(symbol):
"""Safely get stock data with error handling"""
try:
stock = yf.Ticker(symbol)
return stock.info
except Exception as e:
print(f"Error fetching data for {symbol}: {e}")
return {}
def get_current_price(self, symbol):
"""Get current stock price with error handling"""
try:
stock = yf.Ticker(symbol)
return stock.info.get('currentPrice', 0)
except Exception as e:
print(f"Error getting price for {symbol}: {e}")
return 0
Error handling ensures your program doesn't crash if there are issues with data fetching or network problems.
Summary
In this tutorial, you've learned how to build a basic stock portfolio tracker using Python. You've created a system that can track multiple stocks, calculate their current values, and determine gains or losses. This is similar to how the US government tracks its Intel stake, though their system would be much more complex with additional features like regulatory compliance, detailed financial reporting, and sophisticated analytics.
The key concepts you've learned include:
- Using Python libraries to fetch financial data
- Creating classes to organize code and manage data
- Performing calculations on investment data
- Handling errors gracefully in your programs
This simple portfolio tracker demonstrates the fundamental principles behind more complex investment tracking systems used by financial institutions and government agencies. As you continue learning Python, you can expand this system to include features like historical data analysis, automated alerts, and more sophisticated financial metrics.



