How to do a Fourier Decomposition in Python

1 min

A Fourier decomposition is a mathematical method used to represent a function as the sum of simpler trigonometric functions. In finance, it is used to analyze and predict prices by breaking down complex price patterns into simpler components. The idea is that these components can be easier to understand and analyze, allowing for more accurate predictions.

Here's a simple example of how to perform a Fourier decomposition in Python:

import numpy as np
import matplotlib.pyplot as plt

# Define the time range and signal
T = 100
f = 2
t = np.linspace(0, T, T * f, endpoint=False)
signal = np.sin(2 * np.pi * f * t) + 0.5 * np.sin(4 * np.pi * f * t)

# Perform the Fourier decomposition
ft = np.fft.rfft(signal)
frequency = np.fft.rfftfreq(len(signal), d=1/f)

# Plot the original signal and its components
plt.plot(t, signal, label='Signal')
plt.plot(frequency, np.abs(ft), label='Fourier components')
plt.legend()
plt.show()

In this example, the signal is a simple sum of two sine waves with different frequencies. The Fourier decomposition is performed using the numpy.fft.rfft function, which returns the real-valued Fourier transform. The frequencies of the components are then obtained using numpy.fft.rfftfreq. Finally, the original signal and its Fourier components are plotted using matplotlib.