Last active
February 5, 2024 21:00
-
-
Save fuwiak/ef31bc9e867d6d1213af810be5ee8090 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
from statsmodels.tsa.holtwinters import SimpleExpSmoothing | |
from sklearn.metrics import mean_squared_error | |
# Assuming df_list[100]['y_lag'] is your time series data | |
# Ensure it's a pandas Series for compatibility with SimpleExpSmoothing | |
data = pd.Series(df_list[100]['y_lag']) | |
N = 20 # Forecasting 20 steps into the future | |
# Range of alphas to explore | |
alphas = np.linspace(0.01, 1, 100) | |
mse_errors = [] | |
# Try fitting models with different alphas | |
for alpha in alphas: | |
model = SimpleExpSmoothing(data).fit(smoothing_level=alpha) | |
predictions = model.fittedvalues | |
mse = mean_squared_error(data, predictions) | |
mse_errors.append(mse) | |
# Find the alpha with the lowest MSE | |
min_mse = min(mse_errors) | |
best_alpha = alphas[mse_errors.index(min_mse)] | |
print(f"Best Alpha: {best_alpha} with MSE: {min_mse}") | |
# Fit model with the best alpha | |
best_model = SimpleExpSmoothing(data).fit(smoothing_level=best_alpha) | |
forecast = best_model.forecast(steps=N) | |
# Add forecast to the plot | |
plt.figure(figsize=(10, 6)) | |
plt.plot(data.index, data, label='Original Data') | |
plt.plot(best_model.fittedvalues.index, best_model.fittedvalues, label='Fitted Values') | |
forecast_index = np.arange(len(data), len(data) + N) | |
plt.plot(forecast_index, forecast, label='Forecast', marker='o', linestyle='--', color='red') | |
plt.legend() | |
plt.title("Simple Exponential Smoothing Forecast") | |
plt.xlabel("Time") | |
plt.ylabel("Value") | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
from statsmodels.tsa.holtwinters import ExponentialSmoothing
Assuming data is your time series
model_holt = ExponentialSmoothing(data, trend='add').fit()
forecast_holt = model_holt.forecast(20)
Plotting
plt.figure(figsize=(10, 6))
plt.plot(data.index, data, label='Original Data')
plt.plot(forecast_holt.index, forecast_holt, label='Holt’s Linear Trend Forecast', marker='o', linestyle='--', color='green')
plt.legend()
plt.title("Holt’s Linear Trend Method Forecast")
plt.xlabel("Time")
plt.ylabel("Value")
plt.show()