|
|
from statsmodels.tsa.holtwinters import ExponentialSmoothing
|
|
|
import pandas as pd
|
|
|
|
|
|
def forecast(forecast_data):
|
|
|
future_months = 12
|
|
|
|
|
|
df = pd.DataFrame(forecast_data)
|
|
|
|
|
|
df['date'] = pd.to_datetime(df['tahun'].astype(str) + '-' + df['bulan'].astype(str) + '-01')
|
|
|
df = df[['date', 'count']].sort_values('date')
|
|
|
|
|
|
max_date = df['date'].max()
|
|
|
cutoff = max_date - pd.DateOffset(years=5)
|
|
|
df = df[df['date'] >= cutoff]
|
|
|
|
|
|
df.set_index('date', inplace=True)
|
|
|
ts = df['count'].asfreq('MS').fillna(0)
|
|
|
|
|
|
|
|
|
model = ExponentialSmoothing(
|
|
|
ts,
|
|
|
trend="add",
|
|
|
seasonal="add",
|
|
|
seasonal_periods=12
|
|
|
).fit()
|
|
|
|
|
|
prediction = model.forecast(future_months)
|
|
|
|
|
|
future_index = pd.date_range(
|
|
|
ts.index[-1] + pd.DateOffset(months=1),
|
|
|
periods=future_months,
|
|
|
freq='MS'
|
|
|
)
|
|
|
|
|
|
forecast_json = [
|
|
|
{"date": str(date.date()), "forecast": float(pred)}
|
|
|
for date, pred in zip(future_index, prediction)
|
|
|
]
|
|
|
|
|
|
history_json = [
|
|
|
{"date": str(idx.date()), "count": int(val)}
|
|
|
for idx, val in ts.items()
|
|
|
]
|
|
|
|
|
|
return {
|
|
|
"history": history_json,
|
|
|
"forecast": forecast_json
|
|
|
}
|
|
|
|