text_html_output_1.png
from datetime import datetime

from gluonts.dataset.common import ListDataset

from gluonts.dataset.common import ListDataset

from gluonts.evaluation import Evaluator

from gluonts.evaluation import Evaluator

from tqdm.autonotebook import tqdm

import matplotlib.pyplot as plt

import matplotlib.pyplot as plt

import pandas as pd

import pandas as pd

def convert_to_date(x):
    return datetime.strptime(x, '%Y %m')
make = pd.read_csv('../input/newcarsalesnorway/norway_new_car_sales_by_make.csv', parse_dates=[['Year', 'Month']], date_parser=convert_to_date)
make = make[['Year_Month', 'Quantity', 'Make']]

def subset_data(dataframe=make, subset=['Toyota', 'Ford', 'BMW', 'Honda', 'Peugeot']):
    """
    Function to subset the data 
    INPUT : dataframe to subset and car type list 
    OUTPUT : 5 different dataframes with the subset data
    """
    dataframe.set_index('Year_Month', inplace=True)
    toyota = dataframe[dataframe['Make'] == subset[0]]
    ford = dataframe[dataframe['Make'] == subset[1]]
    honda = dataframe[dataframe['Make'] == subset[3]]
    BMW = dataframe[dataframe['Make'] == subset[2]]
    peugeot = dataframe[dataframe['Make'] == subset[4]]
    df = pd.concat([toyota['Quantity'], ford['Quantity'], BMW['Quantity'], honda['Quantity'], peugeot['Quantity']], axis=1)
    df.columns = [subset[0], subset[1], subset[2], subset[3], subset[4]]
    return df
df = subset_data()

### How the time series is for each Car model 
### Some show upward trend some show downward trend 

fig, axs = plt.subplots(2, 2, figsize=(20, 20), sharex=True)
axx = axs.ravel()
for i in range(0, 4):
    df[df.columns[i]].plot(ax=axx[i])
    axx[i].set_xlabel("date")    
    axx[i].set_ylabel(f"{df.columns[i]} Car Sales")   
    axx[i].grid(which='minor', axis='x')

df_input = df.reset_index(drop=True).T.reset_index()
ts_code = df_input['index'].astype('category').cat.codes.values
df_train = df_input.iloc[:, 1:116].values
df_test = df_input.iloc[:, 116:].values

df_test.shape

freq = 'M'
start_train = pd.Timestamp('2007-01-01', freq=freq)
start_test = pd.Timestamp('2016-07-01', freq=freq)
prediction_length = 2

from tqdm.autonotebook import tqdm
tss = list(tqdm(ts_it, total=len(df_test)))
forecasts = list(tqdm(forecast_it, total=len(df_test)))

from gluonts.evaluation import Evaluator
evaluator = Evaluator(quantiles=[0.1, 0.5, 0.9])
agg_metrics, item_metrics = evaluator(iter(tss), iter(forecasts), num_series=len(df_test))

def convert_to_date(x):
    return datetime.strptime(x, '%Y %m')
make = pd.read_csv('../input/newcarsalesnorway/norway_new_car_sales_by_make.csv', parse_dates=[['Year', 'Month']], date_parser=convert_to_date)
make = make[['Year_Month', 'Quantity', 'Make']]

make = make[make['Make'] == 'Ford']

df_input = make[['Year_Month', 'Quantity']]

df_input = df_input.set_index('Year_Month')

train_time = '2016-08-01'
prediction_length = 6

from gluonts.dataset.common import ListDataset
training_data = ListDataset([{'start': df_input.index[0], 'target': df_input.Quantity[:train_time]}], freq='1M')

test_data = ListDataset([{'start': df_input.index[0], 'target': df_input.Quantity[:'2017-01-01']}], freq='1M')

forecasts = list(forecast_it)
tss = list(ts_it)

from gluonts.evaluation import Evaluator
evaluator = Evaluator(quantiles=[0.1, 0.5, 0.9])
agg_metrics, item_metrics = evaluator(iter(tss), iter(forecasts), num_series=len(test_data))