Certainly! Below is a Python script that calculates the month-on-month percentage changes of a stock price and performs a Fourier Transform on those changes. The script also plots the original changes and their frequency spectrum using matplotlib.
Before running the script, make sure you have the required libraries installed:
pip install pandas numpy matplotlib yfinance
Here's the code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf
# Parameters
ticker = 'AAPL' # You can change this to any stock symbol
start_date = '2010-01-01'
end_date = '2023-10-01'
# Fetch historical stock data
data = yf.download(ticker, start=start_date, end=end_date, interval='1mo')
# Ensure data is sorted by date
data.sort_index(inplace=True)
# Calculate month-on-month percentage change
data['Monthly Change'] = data['Adj Close'].pct_change()
# Drop NaN values resulting from the percentage change calculation
monthly_changes = data['Monthly Change'].dropna()
# Prepare data for FFT
# Subtract mean to center the data
changes_centered = monthly_changes - monthly_changes.mean()
# Perform Fourier Transform
fft_result = np.fft.fft(changes_centered)
# Compute the frequencies
num_samples = len(changes_centered)
freq = np.fft.fftfreq(num_samples)
# Get the magnitude of the FFT
fft_magnitude = np.abs(fft_result)
# Plot the monthly changes
plt.figure(figsize=(14, 6))
plt.subplot(1, 2, 1)
plt.plot(monthly_changes.index, monthly_changes.values)
plt.title(f'{ticker} Monthly Percentage Changes')
plt.xlabel('Date')
plt.ylabel('Percentage Change')
# Plot the frequency spectrum
plt.subplot(1, 2, 2)
plt.stem(freq[:num_samples // 2], fft_magnitude[:num_samples // 2], use_line_collection=True)
plt.title('Frequency Spectrum')
plt.xlabel('Frequency')
plt.ylabel('Magnitude')
plt.tight_layout()
plt.show()
Explanation:
-
Import Libraries: We import the necessary libraries for data manipulation, numerical computations, and plotting.
-
Parameters:
ticker: The stock symbol you want to analyze (e.g., 'AAPL' for Apple Inc.).
start_date and end_date: The date range for the historical data.
-
Fetch Historical Stock Data:
- We use the
yfinance library to download monthly adjusted closing prices for the specified stock.
-
Calculate Monthly Percentage Changes:
- We calculate the month-on-month percentage change using the
pct_change() method.
-
Prepare Data for FFT:
- We center the data by subtracting the mean to remove any offset, which can improve the FFT analysis.
-
Perform Fourier Transform:
- We use
np.fft.fft() to compute the FFT of the centered monthly changes.
- Frequencies corresponding to the FFT components are obtained using
np.fft.fftfreq().
-
Plotting:
- The left subplot shows the time series of monthly percentage changes.
- The right subplot displays the frequency spectrum (magnitude of the FFT) to identify dominant frequencies.
Notes:
-
Interpretation:
- Peaks in the frequency spectrum can indicate cyclical patterns in the stock's monthly changes.
- The frequencies are in units of cycles per sample (month). To convert to cycles per year, multiply by 12.
-
Data Availability:
- The script uses adjusted closing prices to account for stock splits and dividends.
- Ensure that the date range and ticker symbol are valid; otherwise, the script may return errors.
-
Customization:
- You can change the
ticker variable to analyze different stocks.
- Adjust the
start_date and end_date to focus on different time periods.
Sample Output:
When you run the script, it will display two plots:
-
Monthly Percentage Changes: A line plot showing how the stock's price has changed month over month.
-
Frequency Spectrum: A stem plot illustrating the magnitude of different frequency components present in the monthly changes.
Feel free to ask if you need further assistance or modifications to the script!