forecasts_filtered = forecasts[(forecasts['WeekDate'] >= cutoff_date) & (forecasts['WeekDate'] < cutoff_date + timedelta(weeks=12))]
forecasts_filtered = forecasts_filtered.with_columns([
pl.concat_str([
pl.col('MaterialID').cast(pl.Utf8),
"_",
pl.col('SalesOrg').cast(pl.Utf8),
"_",
pl.col('DistrChan').cast(pl.Utf8),
"_",
pl.col('CL4').cast(pl.Utf8)
]).alias('unique_id')
])
for record in actuals.to_dicts():
key = record['unique_id']
actual_values = record['actuals']
forecasts = forecasts_filtered[forecasts_filtered['unique_id'] == key, 'AutoARIMA'].to_lists()[0]
abs_errors = [abs(forecast - actual) for forecast, actual in zip(forecasts, actual_values)]
sum_abs_errors = sum(abs_errors)
sum_actuals = sum(actual_values)
sum_forecasts = sum(forecasts)
if sum_actuals > 0:
lag_accuracy[key] = 1 - (sum_abs_errors / sum_actuals)
lag_bias[key] = (sum_forecasts / sum_actuals) - 1
else:
lag_accuracy[key] = 0 # Set accuracy to 0 if sum_actuals is 0
lag_bias[key] = 0 # Set bias to 0 if sum_actuals is 0
return lag_accuracy, lag_bias
Assistant
It looks like there's a typo in your code related to the Polars module import and usage. In your extract_actuals_for_lag function, there's an error stemming from this line:
Set the cutoff date for lag 0 (e.g., first week of 2023)
cutoff_date = datetime(2023, 1, 2)
Calculate accuracy and bias for each lag
lag_results = {}
for lag in range(12):
actuals = extract_actuals_for_lag(crossvalidation_df, lag, cutoff_date)
lag_accuracy, lag_bias = calculate_lag_accuracy_bias(actuals, forecasts_df, cutoff_date) ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/tungnguyen/Downloads/Nestle/Nestle CL4 Low Volume ARIMAX Ensemble.ipynb Cell 26 line 5
50 lag_results = {}
51 for lag in range(12):
---> 52 actuals = extract_actuals_for_lag(crossvalidation_df, lag, cutoff_date)
53 lag_accuracy, lag_bias = calculate_lag_accuracy_bias(actuals, forecasts_df, cutoff_date)
54 lag_results[f'lag{lag}'] = {'accuracy': lag_accuracy, 'bias': lag_bias}
TypeError: 'module' object is not callable
lag_results[f'lag{lag}'] = {'accuracy': lag_accuracy, 'bias': lag_bias}
cutoff_date += timedelta(weeks=1)
Print the results along with the 12-week out forecasts
for lag, result in lag_results.items():
print(f"{lag}:")
for key, accuracy in result['accuracy'].items():
forecasts = forecasts_df[forecasts_df['unique_id'] == key, 'AutoARIMA'].to_lists()[0]
print(f" {key}: Accuracy={accuracy:.4f}, Bias={result['bias'][key]:.4f}, 12-week out forecasts={forecasts}")
The error message TypeError: 'module' object is not callable suggests that there's a misunderstanding about how you're trying to use the list function within pl.expr. If pl is supposed to refer to the Polars library, pl.expr does not have a function named list that can be called like you are attempting to. Your intent seems to be to aggregate the 'y' column values into a list per 'unique_id'.
Assuming the pl object refers to the Polars module, let's correct that line. Polars does offer functions for performing such aggregations, but the way to create a list of values per group involves using pl.col and aggregate functions such as pl.list() (without expr and correctly using the aggregation method).
First, ensure you've imported the Polars library correctly. The typical import statement for Polars looks like this:
python
import polars as pl
Then, to fix the specific issue, rewrite the aggregation line like this:
Remember that aggregations with Polars are done using its fluent API, which might look a bit different from what you might be used to with pandas if that's your background.
Given this, let me revise parts of your provided code snippet to correct and potentially clarify its implementation. Note that I'll focus on the sections where corrections or clarifications are most needed based on the initial error message and description:
python
# Assuming other parts of the code setup are correct and necessary imports are done, such as
import polars as pl
from datetime import datetime, timedelta
# Corrected function to extract actuals for a given lag and cutoff date
def extract_actuals_for_lag(df, lag, cutoff_date):
start_date = cutoff_date - timedelta(weeks=lag+4)
end_date = cutoff_date - timedelta(weeks=lag)
mask = (df['ds'] >= pl.lit(start_date)) & (df['ds'] < pl.lit(end_date))
mask_df = df.filter(mask) # Use df.filter() instead of boolean indexing
return mask_df.select(['unique_id', 'y']).groupby('unique_id').agg(pl.col('y').list().alias('actuals'))