from statsforecast import StatsForecast
from statsforecast.models import AutoARIMA, SimpleExponentialSmoothing, HistoricAverage, Naive, RandomWalkWithDrift, SeasonalNaive
from statsforecast.utils import ConformalIntervals
import numpy as np
import polars as pl

# Polars option to display all rows
pl.Config.set_tbl_rows(None)

# Initialize the models
models = [
    AutoARIMA(season_length=12),
    SimpleExponentialSmoothing(alpha=0.8),
    HistoricAverage(),
    Naive(),
    RandomWalkWithDrift(),
    SeasonalNaive(season_length=12)
]

# Initialize the StatsForecast model
sf = StatsForecast(models=models, freq='1w', n_jobs=-1)

# Perform cross-validation with a step size of 1 to mimic an expanding window
crossvalidation_df = sf.cross_validation(df=y_cl4_filtered, h=2, step_size=1, n_windows=8, sort_df=True)

# Calculate the ensemble mean
ensemble = crossvalidation_df[['AutoARIMA', 'SimpleExponentialSmoothing', 'HistoricAverage', 'Naive', 'RandomWalkWithDrift', 'SeasonalNaive']].mean(axis=1)

# Create a Series for the ensemble mean
ensemble_series = pl.Series('Ensemble', ensemble)

# Add the ensemble mean as a new column to the DataFrame
crossvalidation_df = crossvalidation_df.with_columns(ensemble_series)

def wmape(y_true, y_pred):
    return np.abs(y_true - y_pred).sum() / np.abs(y_true).sum()

# Calculate the WMAPE for the ensemble model
wmape_value = wmape(crossvalidation_df['y'], crossvalidation_df['Ensemble'])
print('Average WMAPE for Ensemble: ', round(wmape_value, 4))

# Calculate the errors for the ensemble model
errors = crossvalidation_df['y'] - crossvalidation_df['Ensemble']

# For an individual forecast
individual_accuracy = 1 - (abs(crossvalidation_df['y'] - crossvalidation_df['Ensemble']) / crossvalidation_df['y'])
individual_bias = (crossvalidation_df['Ensemble'] / crossvalidation_df['y']) - 1

# Add these calculations as new columns to DataFrame
crossvalidation_df = crossvalidation_df.with_columns([
    individual_accuracy.alias("individual_accuracy"),
    individual_bias.alias("individual_bias")
])

# Print the individual accuracy and bias for each week
for row in crossvalidation_df.to_dicts():
    id = row['unique_id']
    date = row['ds'] 
    accuracy = row['individual_accuracy']
    bias = row['individual_bias']
    print(f"{id}, {date}, Individual Accuracy: {accuracy:.4f}, Individual Bias: {bias:.4f}")

# For groups of forecasts
group_accuracy = 1 - (errors.abs().sum() / crossvalidation_df['y'].sum())
group_bias = (crossvalidation_df['Ensemble'].sum() / crossvalidation_df['y'].sum()) - 1

# Print the average group accuracy and group bias over all folds for the ensemble model
print('Average Group Accuracy: ', round(group_accuracy, 4))
print('Average Group Bias: ', round(group_bias, 4))


--------------------------------------------------------------------------
ColumnNotFoundError                       Traceback (most recent call last)
/var/folders/fb/wc6gnylj4cl033fkktj66zrc0000gn/T/ipykernel_11107/154608881.py in ?()
     23 # Perform cross-validation with a step size of 1 to mimic an expanding window
     24 crossvalidation_df = sf.cross_validation(df=y_cl4_filtered, h=2, step_size=1, n_windows=8, sort_df=True)
     25 
     26 # Calculate the ensemble mean
---> 27 ensemble = crossvalidation_df[['AutoARIMA', 'SimpleExponentialSmoothing', 'HistoricAverage', 'Naive', 'RandomWalkWithDrift', 'SeasonalNaive']].mean(axis=1)
     28 
     29 # Create a Series for the ensemble mean
     30 ensemble_series = pl.Series('Ensemble', ensemble)

~/anaconda3/lib/python3.10/site-packages/polars/dataframe/frame.py in ?(self, item)
   1738 
   1739         if is_str_sequence(item, allow_str=False):
   1740             # select multiple columns
   1741             # df[["foo", "bar"]]
-> 1742             return self._from_pydf(self._df.select(item))
   1743         elif is_int_sequence(item):
   1744             item = pl.Series("", item)  # fall through to next if isinstance
   1745 

ColumnNotFoundError: SimpleExponentialSmoothing