Skip to content

Instantly share code, notes, and snippets.

@cbaragao
Created March 7, 2025 23:44
Show Gist options
  • Select an option

  • Save cbaragao/dd73754f7fa7b4378c33590f0a93e8d0 to your computer and use it in GitHub Desktop.

Select an option

Save cbaragao/dd73754f7fa7b4378c33590f0a93e8d0 to your computer and use it in GitHub Desktop.
(
// table to pass in
tbl as table,
// name of the date column
date_column as text,
// name of the column you are projecting on
projection_column as text,
// "add", "mul", "None"
trend as text,
// "add", "mul", "None"
seasonal as text,
// how many forecast periods you want to project
forecast_periods as number,
// how many periods constitute a season (e.g. if the data is monthly, then 12 periods could be a year)
seasonal_periods as number
)=>
let
python =
"
import pandas as pd
from statsmodels.tsa.holtwinters import ExponentialSmoothing
# Ensure dataset is sorted
dataset[""" & date_column & """] = pd.to_datetime(dataset[""" & date_column & """])
dataset = dataset.sort_values(""" & date_column & """)
# Define the forecast period (e.g., next 6 months)
forecast_periods = " & Text.From(forecast_periods) & "
# Fit the Holt-Winters model (Triple Exponential Smoothing)
model = ExponentialSmoothing(dataset[""" & projection_column& """], trend=""" & trend & """, seasonal=""" & seasonal & """, seasonal_periods=" & Text.From(seasonal_periods) & ")
fitted_model = model.fit()
# Create forecast
future_dates = pd.date_range(start=dataset[""" & date_column & """].max(), periods=forecast_periods + 1, freq=""M"")[1:]
forecast_values = fitted_model.forecast(forecast_periods)
# Create DataFrame with forecast
forecast_df = pd.DataFrame({""" & date_column & """: future_dates, "" ForecastedPayroll "": forecast_values})
# Append forecast to original dataset
output_df = pd.concat([dataset[[""" & date_column & """, """ & projection_column & """]], forecast_df], ignore_index=True)
# Return the result to Power BI
output_df",
run = Python.Execute(python,[dataset=tbl])
in
run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment