import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('stock_price_nn.csv').set_index('Date')
plt.plot(df)
plt.xticks([1, 15, 30, 45, 60])
plt.show()
import statsmodels.graphics.tsaplots as sgt
def plot_acf_pacf(series):
plt.rcParams["figure.figsize"] = 6, 9
fig, axes = plt.subplots(2, 1)
sgt.plot_acf(series, ax=axes[0])
sgt.plot_pacf(series, ax=axes[1], method='ywm')
plt.show()
plot_acf_pacf(df)
from statsmodels.tsa.stattools import adfuller
stats = adfuller(df) # Исходный ряд
print("adf: ", stats[0])
print("p-value: ", stats[1])
print("Critical values: ", stats[4])
if stats[0] > stats[4]["5%"]:
print("ряд нестационарен")
else:
print("ряд стационарен")
#adf: -1.539
#p-value: 0.513
#Critical values: {'1%': -3.533, '5%': -2.906, '10%': -2.590}
#ряд нестационарен
stats = adfuller(df.diff().dropna()) # 1-й дифферент
print("adf: ", stats[0])
print("p-value: ", stats[1])
print("Critical values: ", stats[4])
if stats[0] > stats[4]["5%"]:
print("ряд нестационарен")
else:
print("ряд стационарен")
#adf: -7.988
#p-value: 0.000
#Critical values: {'1%': -3.535, '5%': -2.907, '10%': -2.591}
#ряд стационарен
train = df[:-15]
test = df[-15:]
filler = df[-16:-14]
plt.plot(pd.concat([train, filler]))
plt.plot(test)
plt.xticks([1, 15, 30, 45, 60])
plt.show()
from statsmodels.tsa.statespace.sarimax import SARIMAX
model = SARIMAX(train, order=(1, 1, 5), seasonal_order=(0, 0, 0, 0)).fit(maxiter=100)
pred = model.predict(start=test.index[0], end=test.index[-1])
test['pred'] = pred
plt.plot(pd.concat([train, filler]))
plt.plot(test)
plt.xticks([1, 15, 30, 45, 60])
plt.show()
plt.plot(pd.concat([train, filler]))
plt.plot(test)
plt.xticks([47, 52, 57])
plt.xlim('2023-10-20', '2023-11-09')
plt.ylim(17000, 18250)
plt.grid()
plt.show()
import pmdarima as pm
smodel = pm.auto_arima(
train,
start_p=1,
d=1,
start_q=1,
max_p=5,
max_q=5,
D=1,
start_P=0,
m=5,
test="adf",
error_action="ignore",
trace=True,
)
smodel.summary()
for i in range(27):
train = df[:-30+i]
test = df[-30+i:]
filler = df[-31+i:-29+i]
model = SARIMAX(train, order=(0, 1, 0), seasonal_order=(0, 1, 1, 5)).fit(maxiter=100)
pred = model.predict(start=test.index[0], end=test.index[3])
test['pred'] = pred
plt.plot(pd.concat([train, filler]))
plt.plot(test)
plt.show()
!pip install prophet
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from prophet import Prophet
df = pd.read_csv('stock_price_nn.csv')
idx = pd.to_datetime(df['Date'])
df = pd.DataFrame(df['Value']).set_index(idx)
print(df.shape) #(67, 1)
df = df.asfreq(freq='D')
df = df.interpolate(method='linear')
print(df.shape) #(93, 1)
df.reset_index(inplace= True)
df.columns = ['ds', 'y'] #требование prophet
train = df[:-20]
test = df[-20:]
filler = df[-21:-19]
plt.plot(pd.concat([train, filler]).y)
plt.plot(test.y)
plt.grid()
plt.show()
model = Prophet()
model.fit(train)
future = model.make_future_dataframe(periods=test.shape[0])
forecast = model.predict(future)
print(', '.join(forecast.columns))
# ds, trend, yhat_lower, yhat_upper, trend_lower, trend_upper, additive_terms,
# additive_terms_lower, additive_terms_upper, weekly, weekly_lower, weekly_upper,
# multiplicative_terms, multiplicative_terms_lower, multiplicative_terms_upper, yhat
for i in range(10, df.shape[0], 5):
batch = df.iloc[:i]
model = Prophet()
model.fit(batch)
future = model.make_future_dataframe(periods=3)
forecast = model.predict(future)
cmp_df = forecast.set_index('ds')[['yhat', 'yhat_lower', 'yhat_upper']].join(df.set_index('ds'))
plt.plot(df.set_index('ds'), label='real')
plt.plot(cmp_df.yhat_lower, alpha=0.5, label='lower')
plt.plot(cmp_df.yhat_upper, alpha=0.5, label='upper')
plt.plot(cmp_df.yhat, label='predicted')
plt.grid()
plt.legend()