Created
June 9, 2020 22:09
-
-
Save marketneutral/a6e4ab2873087921014c080c3686ef24 to your computer and use it in GitHub Desktop.
skits Multi Time Series
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sklearn.linear_model import LinearRegression | |
from sklearn.pipeline import FeatureUnion | |
from skits.feature_extraction import AutoregressiveTransformer | |
from skits.pipeline import ForecasterPipeline | |
from skits.preprocessing import ReversibleImputer | |
df = pd.DataFrame( | |
{ | |
"date": [1, 1, 1, 2, 2, 2, 3, 3 ,3, 4, 4, 4, 5, 5, 5], | |
"ts_name": ["A", "B", "C", "A", "B", "C","A", "B", "C","A", "B", "C","A", "B", "C"], | |
"Y_t": [1.1, 2.3, 3.1, 1.2, 2.2, 3.3, 1.05, 2.25, 3.35, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,], | |
} | |
) | |
forecast_date_start = 4 | |
pipeline = ForecasterPipeline( | |
[ | |
( | |
"features", | |
FeatureUnion( | |
[("ar_transformer", AutoregressiveTransformer(num_lags=2))] | |
), | |
), | |
("post_lag_imputer", ReversibleImputer()), | |
] | |
) | |
Xts = [] | |
yts = [] | |
for ts_name, group in df.query('date < @forecast_date_start').groupby("ts_name"): | |
y = group["Y_t"].values | |
X = y[:, np.newaxis].copy() | |
Xt = pipeline.fit_transform(X, y) | |
yt = pipeline.transform_y(y) | |
if yt.ndim == 1: | |
yt = yt[:, np.newaxis] | |
Xts.append(Xt) | |
yts.append(yt) | |
Xt = np.vstack(Xts) | |
yt = np.vstack(yts) | |
estimator = LinearRegression() | |
# Forecast | |
start_idx = 3 | |
end_idx = 5 | |
for ts_name, group in df.groupby("ts_name"): | |
y = group["Y_t"].values | |
for idx in range(start_idx, end_idx): | |
X = y[:(idx + 1), np.newaxis].copy() | |
Xt = pipeline.transform(X) | |
y[idx] = estimator.predict(Xt[-1:, ]) | |
df.loc[(df.date == idx+1) & (df.ts_name == ts_name), 'Y_t'] = y[idx] | |
df.groupby(['date','ts_name']).last()['Y_t'].unstack().plot() | |
plt.axvline(3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment