import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.statespace.sarimax import SARIMAX
from sklearn.metrics import mean_squared_error
import yfinance as yf
Download historical data
symbol = "CADJPY=X"
start_date = "2023-03-01"
end_date = "2023-06-01"
data = yf.download(symbol, start=start_date, end=end_date, interval='1d')
data = data.dropna()
Calculate daily returns
data['Return'] = data['Close'].pct_change()
data = data.dropna()
/usr/local/lib/python3.10/dist-packages/pandas/core/construction.py in _sanitize_ndim(result, data, dtype, index, allow_2d)
716 if allow_2d:
717 return result
--> 718 raise ValueError(
719 f"Data must be 1-dimensional, got ndarray of shape {data.shape} instead"
720 )
ValueError: Data must be 1-dimensional, got ndarray of shape (30, 30) instead
The error you're encountering is due to a mismatch in dimensions and indexing when trying to add a Pandas Series (forecast_values_final) and a NumPy array (combined_simulation_results).
In your code, forecast_values_final is a Pandas Series that has an index of dates corresponding to the forecasted periods. On the other hand, combined_simulation_results is a NumPy array without any index. When you attempt to add these two objects, Pandas tries to align them based on their index, but since the NumPy array doesn't have an index, it leads to ambiguity and results in the error:
code
ValueError: Data must be 1-dimensional, got ndarray of shape (30, 30) instead
To resolve this issue, you need to convert combined_simulation_results into a Pandas Series and assign it the same index as forecast_values_final. Here's how you can modify your code:
python
# Convert combined_simulation_results to a Pandas Series with the same index as forecast_values_final
combined_simulation_series = pd.Series(combined_simulation_results, index=forecast_values_final.index)
# Now you can safely compute final_combined_forecast
final_combined_forecast = (forecast_values_final + combined_simulation_series) / 2
By doing this, both forecast_values_final and combined_simulation_series have the same index, and Pandas can align them properly during the addition.
Here's the corrected and complete code snippet:
python
# Simulate Heston model
heston_simulated_prices, _ = heston_model_simulation(
data['Close'].iloc[-1],
kappa=1.5,
theta=0.04,
sigma=0.3,
rho=-0.7,
v0=0.04,
r=0.01,
T=1,
time_steps=forecast_steps_final
)
# Simulate Monte Carlo with geometric Brownian motion
monte_carlo_simulated_trajectories = monte_carlo_simulation(
data['Close'].iloc[-1],
mean_return=data['Return'].mean(),
std_return=data['Return'].std(),
forecast_steps=forecast_steps_final,
n_simulations=10000
)
# Ensure that heston_simulated_prices and monte_carlo_simulated_trajectories have the same length
common_length = min(len(heston_simulated_prices[1:]), len(monte_carlo_simulated_trajectories[0]))
# Combine Heston and Monte Carlo results
combined_simulation_results = (
heston_simulated_prices[1:common_length + 1] +
np.mean(monte_carlo_simulated_trajectories[:, :common_length], axis=0)
) / 2
# Convert combined_simulation_results to a Pandas Series with the same index as forecast_values_final
combined_simulation_series = pd.Series(combined_simulation_results, index=forecast_values_final.index)
# Combine SARIMA and simulation results
final_combined_forecast = (forecast_values_final + combined_simulation_series) / 2
# Calculate additional metrics
mse_combined_forecast = mean_squared_error(data['Close'].tail(forecast_steps_final), final_combined_forecast)
percentage_error_final_combined = np.abs(
(data['Close'].tail(forecast_steps_final).values - final_combined_forecast) /
data['Close'].tail(forecast_steps_final).values
)
Explanation:
Conversion to Pandas Series: By converting combined_simulation_results to a Pandas Series and assigning the same index as forecast_values_final, you ensure that both series have compatible dimensions and indices for arithmetic operations.
Index Alignment: Pandas relies on index labels to align data in operations. When adding two Series, Pandas matches the indices and performs element-wise addition. Without proper indices, Pandas cannot align the data correctly, leading to errors.
Additional Tips:
Consistent Indexing: Always ensure that Pandas Series or DataFrames involved in arithmetic operations have consistent and matching indices.
Debugging Dimensions: If you encounter similar errors, check the shapes and indices of the data structures involved. You can use .shape for NumPy arrays and .index for Pandas Series to inspect them.
Data Alignment in Pandas: Understanding how Pandas aligns data can help prevent and resolve errors. It’s beneficial to review Pandas documentation on data alignment for a deeper understanding.
By making these adjustments, your code should run without errors, and you'll be able to proceed with your analysis.