Last active
October 1, 2022 10:51
-
-
Save arif9799/e8c32a6bfa97ae7baf389e194e13ce00 to your computer and use it in GitHub Desktop.
Time Series Prediction Interval - Initial Preview Of Article
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
### Installations to execute on every fresh run | |
!pip install --upgrade pandas | |
!pip install --upgrade pandas-datareader | |
!pip install celluloid | |
import pandas_datareader as pdr | |
import pandas as pd | |
from statsmodels.tsa.ar_model import AutoReg | |
from statsmodels.tools.eval_measures import rmse | |
import numpy as np | |
import seaborn as sb | |
import matplotlib.pyplot as plt | |
from matplotlib import rcParams | |
from cycler import cycler | |
shares_df = pdr.DataReader('AAPL', 'yahoo', start='2021-01-01', end='2021-12-31') | |
data = shares_df['Close'] | |
data = data.asfreq('d') | |
data = pd.DataFrame(data.interpolate()) | |
model_fit = AutoReg(data, lags=1).fit() | |
pred = model_fit.get_prediction(start=pd.to_datetime('2022-01-01'),end = pd.to_datetime('2022-03-31'), dynamic=False) | |
predictions = pd.DataFrame(pred.predicted_mean) | |
pred = model_fit.get_prediction(start=pd.to_datetime('2021-07-01'),end = pd.to_datetime('2021-12-31'), dynamic=False) | |
predictions = pd.DataFrame(pred.predicted_mean) | |
error = rmse(predictions.predicted_mean, data.Close[-len(predictions):]) | |
pred = model_fit.get_prediction(start=pd.to_datetime('2022-01-01'),end = pd.to_datetime('2022-03-31'), dynamic=False) | |
predictions = pd.DataFrame(pred.predicted_mean) | |
predictions['Upper'],predictions['Lower'] = format(0, '.6f'), format(0, '.6f') | |
for i in range(len(predictions)): | |
predictions.Upper[i], predictions.Lower[i] = predictions.predicted_mean[i] + 1.96 * np.sqrt(i+1) * error, predictions.predicted_mean[i] - 1.96 * np.sqrt(i+1) * error | |
rcParams['figure.figsize'] = 15,5 | |
rcParams['axes.spines.top'] = False | |
rcParams['axes.spines.right'] = False | |
rcParams['lines.linewidth'] = 2.5 | |
plt.title("Stock Price Prediction") | |
plt.xlabel("Date") | |
plt.ylabel("Price (in $)") | |
sb.despine(right = True, top = True) | |
sb.lineplot(data = data, x = data.index, y = data.Close, label = 'Historical Data') | |
plt.axvline(x = predictions.index[0], ymin = 0, ymax = 1, label = 'Prediction Starts from Here') | |
sb.lineplot(data = predictions, x = predictions.index, y = predictions.predicted_mean, label = 'Predictions') | |
sb.lineplot(data = predictions, x = predictions.index, y = predictions.Upper, label = 'Upper Bound') | |
sb.lineplot(data = predictions, x = predictions.index, y = predictions.Lower, label = 'Lower Bound') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment