Write a Python code that generates 40 random financial time series in Pandas.
Afterwards, analyze the series using Short Term Fourier Transform. Use scipy's stft function. Finally, use Self Organizing Map to cluster these series into clusters of high inflationary regime and low inflationary regimes.
Use plotly for all plotting steps
Assistant
Here's a Python script that follows your requirements using Pandas, SciPy, MiniSom (a Self-Organizing Map implementation), and Plotly. First, make sure to install the required libraries:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from scipy.signal import stft
from minisom import MiniSom
# Set random seed for reproducibility
np.random.seed(0)
# Generate 40 random financial time series
n_series = 40
n_points = 1000
data = np.random.normal(0, 1, (n_series, n_points)).cumsum(axis=1)
df = pd.DataFrame(data, columns=[f'Series_{i+1}' for i in range(n_series)])
# Calculate Short Term Fourier Transform (STFT) for each series
freqs, times, Zxx = [], [], []
for col in df.columns:
_, _, Zxx_col = stft(df[col], fs=1)
freqs.append(np.fft.fftfreq(Zxx_col.shape[1], 1))
times.append(np.linspace(0, n_points, Zxx_col.shape[0]))
Zxx.append(np.abs(Zxx_col))
# Prepare data for SOM
stft_data = np.concatenate([Zxx[i][:, np.newaxis] for i in range(n_series)], axis=1)
inflation_labels = np.random.choice(['High', 'Low'], size=n_series) # Random labels for demonstration
# Train Self-Organizing Map (SOM)
map_size = (5, 8)
som = MiniSom(map_size[0], map_size[1], stft_data.shape[1], sigma=1.0, learning_rate=0.5)
som.train_random(stft_data, 100)
# Plot SOM
plt.figure(figsize=(10, 6))
som.plot_activation_maps()
plt.title('Self-Organizing Map')
plt.show()
# Plot original time series colored by their final SOM cluster
cluster_labels = som.winner(stft_data)
df['Cluster'] = cluster_labels
fig = go.Figure()
for cluster in np.unique(cluster_labels):
series = df[df['Cluster'] == cluster].drop('Cluster', axis=1)
fig.add_trace(go.Scatter(y=series.values.T, mode='lines', name=f'Cluster {cluster}'))
fig.update_layout(title='Original Time Series by SOM Cluster')
fig.show()
# Plot inflation labels vs. final SOM cluster
fig = go.Figure()
fig.add_trace(go.Histogram(x=cluster_labels, y=inflation_labels, nbinsx=max(cluster_labels)+1, nbinsy=2, colors=['blue', 'red']))
fig.update_layout(title='Inflation Labels vs. SOM Cluster')
fig.show()
This script generates 40 random financial time series, calculates the Short Term Fourier Transform (STFT) for each series, and then uses a Self-Organizing Map (SOM) to cluster the series based on their STFT representations. Finally, it plots the original time series colored by their final SOM cluster and shows a histogram of inflation labels vs. final SOM cluster.