Trump bought SpaceX shares two weeks after blockbuster IPO
Back to Tutorials
techTutorialbeginner

Trump bought SpaceX shares two weeks after blockbuster IPO

August 24, 20268 views5 min read

Learn to track SpaceX stock prices and analyze trends using Python, creating a simple stock tracking tool that demonstrates real-world financial data analysis.

Introduction

In this tutorial, you'll learn how to track stock prices and analyze trading data using Python and publicly available financial APIs. We'll focus on creating a simple stock tracking tool that can monitor SpaceX (SPXU) stock prices, similar to what investors like former President Trump might use. This beginner-friendly guide will teach you how to fetch real-time stock data, analyze price movements, and visualize trends - all without needing advanced financial knowledge.

Prerequisites

  • Basic computer knowledge
  • Python installed on your system (Python 3.6 or higher recommended)
  • Internet connection
  • Text editor or Python IDE (like VS Code or Jupyter Notebook)

Step-by-Step Instructions

1. Setting Up Your Python Environment

1.1 Install Required Python Libraries

First, we need to install the libraries that will help us fetch and analyze stock data. Open your terminal or command prompt and run:

pip install yfinance matplotlib pandas

This installs three essential libraries: yfinance for fetching stock data, matplotlib for creating charts, and pandas for data manipulation.

1.2 Create Your Python File

Create a new file called stock_tracker.py in your preferred directory. This will be our main script for tracking stock information.

2. Fetching Stock Data

2.1 Basic Stock Data Retrieval

Let's start by writing code to fetch SpaceX stock data. Open your stock_tracker.py file and add this code:

import yfinance as yf

# Fetch SpaceX stock data
spacex = yf.Ticker("SPXU")

# Get basic information about the stock
info = spacex.info
print("Stock Information:")
print(f"Company: {info['longName']}")
print(f"Current Price: ${info['currentPrice']}")
print(f"Previous Close: ${info['previousClose']}")

This code uses the yfinance library to access Yahoo Finance data. The Ticker function creates an object for our specific stock symbol (SPXU for SpaceX). The info dictionary contains various details about the stock, including current price and previous closing price.

2.2 Getting Historical Data

Now let's fetch more detailed historical data to analyze price movements:

# Get historical stock data for the last 30 days
hist_data = spacex.history(period="30d")

print("\nLast 30 Days of Data:")
print(hist_data[["Open", "High", "Low", "Close"]].tail())

The history() method retrieves stock price data for a specified period. We're asking for the last 30 days of data, which shows opening, high, low, and closing prices for each trading day.

3. Analyzing Price Trends

3.1 Calculate Price Changes

Let's add some analysis to understand how the stock price has moved:

# Calculate price change
latest_price = hist_data['Close'][-1]
previous_price = hist_data['Close'][-2]
price_change = latest_price - previous_price
change_percent = (price_change / previous_price) * 100

print(f"\nPrice Analysis:")
print(f"Latest Close: ${latest_price:.2f}")
print(f"Previous Close: ${previous_price:.2f}")
print(f"Change: ${price_change:.2f} ({change_percent:.2f}%)")

This code calculates the difference between the latest closing price and the previous day's closing price, then converts it to a percentage change. This helps us understand how volatile the stock is.

3.2 Find Maximum and Minimum Prices

Let's also identify the highest and lowest prices during our selected period:

# Find highest and lowest prices
max_price = hist_data['High'].max()
min_price = hist_data['Low'].min()

print(f"\nPrice Range:")
print(f"Highest Price: ${max_price:.2f}")
print(f"Lowest Price: ${min_price:.2f}")

These calculations show the full range of price movements, which is useful for understanding the stock's volatility.

4. Creating Visual Charts

4.1 Plotting Stock Prices

Visualizing data makes it easier to understand trends. Let's create a simple chart:

import matplotlib.pyplot as plt

# Create a simple price chart
plt.figure(figsize=(10, 6))
plt.plot(hist_data.index, hist_data['Close'], marker='o')
plt.title('SpaceX (SPXU) Stock Price Over Time')
plt.xlabel('Date')
plt.ylabel('Price ($)')
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

This code creates a line chart showing how the stock price has changed over the past 30 days. The chart helps visualize trends that might not be obvious from raw numbers alone.

4.2 Adding Multiple Data Points

Let's enhance our analysis by plotting both opening and closing prices:

# Create a more detailed chart
plt.figure(figsize=(12, 6))
plt.plot(hist_data.index, hist_data['Open'], label='Opening Price')
plt.plot(hist_data.index, hist_data['Close'], label='Closing Price')
plt.title('SpaceX (SPXU) Opening vs Closing Prices')
plt.xlabel('Date')
plt.ylabel('Price ($)')
plt.legend()
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

This enhanced chart compares opening and closing prices, helping identify patterns in daily trading behavior.

5. Complete Stock Tracker Program

5.1 Combining Everything

Here's the complete program that puts everything together:

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

print("=== SpaceX Stock Tracker ===\n")

# Fetch SpaceX stock data
spacex = yf.Ticker("SPXU")
info = spacex.info

# Display basic information
print("Company Information:")
print(f"Company: {info['longName']}")
print(f"Current Price: ${info['currentPrice']}")
print(f"Previous Close: ${info['previousClose']}")
print(f"Market Cap: ${info['marketCap']:,}")

# Get historical data
hist_data = spacex.history(period="30d")

# Calculate price changes
latest_price = hist_data['Close'][-1]
previous_price = hist_data['Close'][-2]
price_change = latest_price - previous_price
change_percent = (price_change / previous_price) * 100

print(f"\nPrice Analysis:")
print(f"Latest Close: ${latest_price:.2f}")
print(f"Previous Close: ${previous_price:.2f}")
print(f"Change: ${price_change:.2f} ({change_percent:.2f}%)")

# Find price range
max_price = hist_data['High'].max()
min_price = hist_data['Low'].min()

print(f"\nPrice Range:")
print(f"Highest Price: ${max_price:.2f}")
print(f"Lowest Price: ${min_price:.2f}")

# Create charts
plt.figure(figsize=(10, 6))
plt.plot(hist_data.index, hist_data['Close'], marker='o', color='blue')
plt.title('SpaceX (SPXU) Stock Price Over Time')
plt.xlabel('Date')
plt.ylabel('Price ($)')
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

6. Running Your Program

6.1 Execute the Script

Save your file and run it using:

python stock_tracker.py

When executed, this program will display SpaceX stock information, perform calculations, and show charts - just like an investor might do when analyzing their holdings.

Summary

In this tutorial, you've learned how to create a simple stock tracking tool using Python. You've discovered how to fetch real-time stock data, analyze price movements, and visualize trends. The program we built can track SpaceX stock prices similar to what investors use to make informed decisions. While this is a basic tool, it demonstrates fundamental programming concepts like data fetching, calculations, and visualization that form the foundation of more advanced financial analysis tools.

Remember that stock markets involve risks, and this tutorial is for educational purposes only. Always do your own research before making investment decisions.

Related Articles