File size: 1,283 Bytes
6f10462
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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 HOLT-WINTERS
    model = ExponentialSmoothing(
        ts,
        trend="add",        # bisa juga "mul"
        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
    }