ahead.DynamicRegressor.DynamicRegressor

  1import numpy as np
  2
  3from ..Base import Base
  4from ..utils import univariate as uv
  5from ..utils import unimultivariate as umv
  6from .. import config
  7
  8
  9class DynamicRegressor(Base):
 10    """Dynamic Regression Model adapted from R's `forecast::nnetar`
 11
 12    Parameters:
 13
 14        h: an integer;
 15            forecasting horizon
 16
 17        level: an integer;
 18            Confidence level for prediction intervals
 19
 20        type_pi: a string;
 21            Type of prediction interval (currently "gaussian",
 22            ETS: "E", Arima: "A" or Theta: "T")
 23
 24        date_formatting: a string;
 25            Currently:
 26            - "original": yyyy-mm-dd
 27            - "ms": milliseconds
 28
 29    Attributes:
 30
 31        fcast_: an object;
 32            raw result from fitting R's `ahead::dynrmf` through `rpy2`
 33
 34        averages_: a list;
 35            mean forecast in a list
 36
 37        ranges_: a list;
 38            lower and upper prediction intervals in a list
 39
 40        output_dates_: a list;
 41            a list of output dates (associated to forecast)
 42
 43        mean_: a numpy array
 44            contains series mean forecast as a numpy array
 45
 46        lower_: a numpy array
 47            contains series lower bound forecast as a numpy array
 48
 49        upper_: a numpy array
 50            contains series upper bound forecast as a numpy array
 51
 52        result_df_: a data frame;
 53            contains 3 columns, mean forecast, lower + upper
 54            prediction intervals, and a date index
 55
 56    Examples:
 57
 58    ```python
 59    import pandas as pd
 60    from ahead import DynamicRegressor
 61
 62    # Data frame containing the time series
 63    dataset = {
 64    'date' : ['2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01'],
 65    'value' : [34, 30, 35.6, 33.3, 38.1]}
 66
 67    df = pd.DataFrame(dataset).set_index('date')
 68    print(df)
 69
 70    # univariate time series forecasting
 71    d1 = DynamicRegressor(h = 5)
 72    d1.forecast(df)
 73    print(d1.result_df_)
 74    ```
 75
 76    """
 77
 78    def __init__(self, h=5, level=95, type_pi="E", date_formatting="original"):
 79
 80        super().__init__(
 81            h=h,
 82            level=level,
 83        )
 84
 85        self.type_pi = type_pi
 86        self.date_formatting = date_formatting
 87        self.input_df = None
 88        self.type_input = "univariate"
 89
 90        self.fcast_ = None
 91        self.averages_ = None
 92        self.ranges_ = None
 93        self.output_dates_ = []
 94        self.mean_ = []
 95        self.lower_ = []
 96        self.upper_ = []
 97        self.result_df_ = None
 98
 99    def forecast(self, df):
100        """Forecasting method from `DynamicRegressor` class
101
102        Parameters:
103
104            df: a data frame;
105                a data frame containing the input time series (see example)
106
107        """
108
109        # get input dates, output dates, number of series, series names, etc.
110        self.init_forecasting_params(df)
111
112        # obtain time series object -----
113        self.format_input()
114
115        self.get_forecast("dynrm")
116
117        # result -----
118        (
119            self.averages_,
120            self.ranges_,
121            _,
122        ) = uv.format_univariate_forecast(
123            date_formatting=self.date_formatting,
124            output_dates=self.output_dates_,
125            horizon=self.h,
126            fcast=self.fcast_,
127        )
128
129        self.mean_ = np.asarray(self.fcast_.rx2["mean"])
130        self.lower_ = np.asarray(self.fcast_.rx2["lower"])
131        self.upper_ = np.asarray(self.fcast_.rx2["upper"])
132
133        self.result_df_ = umv.compute_result_df(self.averages_, self.ranges_)
134
135        return self
class DynamicRegressor(ahead.Base.Base.Base):
 10class DynamicRegressor(Base):
 11    """Dynamic Regression Model adapted from R's `forecast::nnetar`
 12
 13    Parameters:
 14
 15        h: an integer;
 16            forecasting horizon
 17
 18        level: an integer;
 19            Confidence level for prediction intervals
 20
 21        type_pi: a string;
 22            Type of prediction interval (currently "gaussian",
 23            ETS: "E", Arima: "A" or Theta: "T")
 24
 25        date_formatting: a string;
 26            Currently:
 27            - "original": yyyy-mm-dd
 28            - "ms": milliseconds
 29
 30    Attributes:
 31
 32        fcast_: an object;
 33            raw result from fitting R's `ahead::dynrmf` through `rpy2`
 34
 35        averages_: a list;
 36            mean forecast in a list
 37
 38        ranges_: a list;
 39            lower and upper prediction intervals in a list
 40
 41        output_dates_: a list;
 42            a list of output dates (associated to forecast)
 43
 44        mean_: a numpy array
 45            contains series mean forecast as a numpy array
 46
 47        lower_: a numpy array
 48            contains series lower bound forecast as a numpy array
 49
 50        upper_: a numpy array
 51            contains series upper bound forecast as a numpy array
 52
 53        result_df_: a data frame;
 54            contains 3 columns, mean forecast, lower + upper
 55            prediction intervals, and a date index
 56
 57    Examples:
 58
 59    ```python
 60    import pandas as pd
 61    from ahead import DynamicRegressor
 62
 63    # Data frame containing the time series
 64    dataset = {
 65    'date' : ['2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01'],
 66    'value' : [34, 30, 35.6, 33.3, 38.1]}
 67
 68    df = pd.DataFrame(dataset).set_index('date')
 69    print(df)
 70
 71    # univariate time series forecasting
 72    d1 = DynamicRegressor(h = 5)
 73    d1.forecast(df)
 74    print(d1.result_df_)
 75    ```
 76
 77    """
 78
 79    def __init__(self, h=5, level=95, type_pi="E", date_formatting="original"):
 80
 81        super().__init__(
 82            h=h,
 83            level=level,
 84        )
 85
 86        self.type_pi = type_pi
 87        self.date_formatting = date_formatting
 88        self.input_df = None
 89        self.type_input = "univariate"
 90
 91        self.fcast_ = None
 92        self.averages_ = None
 93        self.ranges_ = None
 94        self.output_dates_ = []
 95        self.mean_ = []
 96        self.lower_ = []
 97        self.upper_ = []
 98        self.result_df_ = None
 99
100    def forecast(self, df):
101        """Forecasting method from `DynamicRegressor` class
102
103        Parameters:
104
105            df: a data frame;
106                a data frame containing the input time series (see example)
107
108        """
109
110        # get input dates, output dates, number of series, series names, etc.
111        self.init_forecasting_params(df)
112
113        # obtain time series object -----
114        self.format_input()
115
116        self.get_forecast("dynrm")
117
118        # result -----
119        (
120            self.averages_,
121            self.ranges_,
122            _,
123        ) = uv.format_univariate_forecast(
124            date_formatting=self.date_formatting,
125            output_dates=self.output_dates_,
126            horizon=self.h,
127            fcast=self.fcast_,
128        )
129
130        self.mean_ = np.asarray(self.fcast_.rx2["mean"])
131        self.lower_ = np.asarray(self.fcast_.rx2["lower"])
132        self.upper_ = np.asarray(self.fcast_.rx2["upper"])
133
134        self.result_df_ = umv.compute_result_df(self.averages_, self.ranges_)
135
136        return self

Dynamic Regression Model adapted from R's forecast::nnetar

Parameters:

h: an integer;
    forecasting horizon

level: an integer;
    Confidence level for prediction intervals

type_pi: a string;
    Type of prediction interval (currently "gaussian",
    ETS: "E", Arima: "A" or Theta: "T")

date_formatting: a string;
    Currently:
    - "original": yyyy-mm-dd
    - "ms": milliseconds

Attributes:

fcast_: an object;
    raw result from fitting R's `ahead::dynrmf` through `rpy2`

averages_: a list;
    mean forecast in a list

ranges_: a list;
    lower and upper prediction intervals in a list

output_dates_: a list;
    a list of output dates (associated to forecast)

mean_: a numpy array
    contains series mean forecast as a numpy array

lower_: a numpy array
    contains series lower bound forecast as a numpy array

upper_: a numpy array
    contains series upper bound forecast as a numpy array

result_df_: a data frame;
    contains 3 columns, mean forecast, lower + upper
    prediction intervals, and a date index

Examples:

import pandas as pd
from ahead import DynamicRegressor

# Data frame containing the time series
dataset = {
'date' : ['2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01'],
'value' : [34, 30, 35.6, 33.3, 38.1]}

df = pd.DataFrame(dataset).set_index('date')
print(df)

# univariate time series forecasting
d1 = DynamicRegressor(h = 5)
d1.forecast(df)
print(d1.result_df_)