Introduction
In this tutorial, we'll explore how to analyze stock trading data using Python and common financial data libraries. This tutorial is inspired by recent news about insider trading involving Volkswagen engineers and Rivian stock. While we won't be investigating actual illegal activities, we'll learn how to work with stock market data, which is a valuable skill for understanding financial markets and building financial applications.
By the end of this tutorial, you'll be able to fetch stock data, analyze price movements, and create simple visualizations that demonstrate how stock prices change over time.
Prerequisites
Before starting this tutorial, you'll need:
- A computer with internet access
- Python 3.x installed (you can download it from python.org)
- Basic understanding of Python programming concepts
- Some familiarity with financial concepts (don't worry if you're new to this - we'll explain everything as we go)
Step-by-Step Instructions
1. Install Required Python Libraries
First, we need to install the libraries we'll use for financial data analysis. Open your terminal or command prompt and run:
pip install yfinance matplotlib pandas
This installs three key libraries:
- yfinance: For downloading financial data from Yahoo Finance
- matplotlib: For creating charts and visualizations
- pandas: For organizing and analyzing data
2. Import Libraries in Python
Now create a new Python file (e.g., stock_analysis.py) and start by importing the necessary libraries:
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd
We're importing these libraries to access financial data, create visualizations, and work with data tables.
3. Download Stock Data
Let's download stock data for a company. In our example, we'll use Rivian (RIVN) stock:
# Download Rivian stock data
rivian = yf.Ticker("RIVN")
# Get basic stock information
info = rivian.info
print("Company Name:", info.get('longName', 'N/A'))
print("Current Price:", info.get('currentPrice', 'N/A'))
This code fetches information about Rivian stock from Yahoo Finance. The yf.Ticker() function is how we access specific stock data, and .info gives us company details.
4. Get Historical Stock Data
Next, we'll get historical price data for the past year:
# Get one year of historical data
hist_data = rivian.history(period="1y")
# Display first few rows of data
print(hist_data.head())
This downloads one year of daily stock price data. The history() method is very useful for financial analysis because it gives us open, high, low, close prices, and volume for each trading day.
5. Create a Simple Stock Price Chart
Now let's visualize the stock price movement:
# Create a simple price chart
plt.figure(figsize=(12, 6))
plt.plot(hist_data.index, hist_data['Close'], label='Rivian Stock Price')
plt.title('Rivian (RIVN) Stock Price Over Time')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.grid(True)
plt.show()
This creates a line chart showing how Rivian's stock price has changed over the past year. The chart helps us see trends and patterns in the stock's performance.
6. Analyze Price Changes
Let's calculate some basic statistics about the stock:
# Calculate basic statistics
print("\nStock Statistics:")
print("Highest Price:", hist_data['High'].max())
print("Lowest Price:", hist_data['Low'].min())
print("Average Closing Price:", hist_data['Close'].mean())
print("Total Volume Traded:", hist_data['Volume'].sum())
These statistics help us understand the stock's behavior - how high and low it went, its average price, and how much trading activity occurred.
7. Compare with Another Company
Let's compare Rivian with Volkswagen (VOW.DE) to see how they perform differently:
# Download Volkswagen stock data
volkswagen = yf.Ticker("VOW.DE")
vw_data = volkswagen.history(period="1y")
# Plot both stocks together
plt.figure(figsize=(12, 6))
plt.plot(hist_data.index, hist_data['Close'], label='Rivian (RIVN)')
plt.plot(vw_data.index, vw_data['Close'], label='Volkswagen (VOW.DE)')
plt.title('Stock Price Comparison: Rivian vs Volkswagen')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.grid(True)
plt.show()
This comparison shows how different companies in the same industry (automotive) might have different stock price patterns.
8. Save Data to File
Finally, let's save our stock data for future analysis:
# Save data to CSV file
hist_data.to_csv('rivian_stock_data.csv')
print("Data saved to rivian_stock_data.csv")
Saving data to a CSV file allows us to analyze it later or share it with others. This is a standard practice in financial analysis.
Summary
In this tutorial, we've learned how to work with stock market data using Python. We:
- Installed necessary libraries for financial data analysis
- Downloaded stock data for Rivian (RIVN) and Volkswagen (VOW.DE)
- Created visualizations to see how stock prices change over time
- Calculated basic statistics about stock performance
- Compared two different companies in the automotive industry
- Saved our data for future use
This skill is valuable for understanding financial markets, building financial applications, and making informed investment decisions. While we've only scratched the surface of financial analysis, these basic techniques form the foundation for more advanced stock market analysis.
Remember, this tutorial is for educational purposes only. Always consult with financial advisors before making investment decisions.


