Exemple #1
0
def ARMA_model(data, ohlc='Close'):

    data = data[ohlc]

    # choose best p, q parameters for our model using AIC optimization
    params = bestParams(data)
    model = ARIMA(data, order=(params[0], 0, params[2]))
    res = model.fit()

    #model_summary = res.summary().as_text()
    model_summary = res.summary()
    # write summary to file
    #fileobj = open("quotes/static/model_results/ARMA_Summary.txt", 'w')
    #fileobj.write(model_summary.as_text())
    #fileobj.close()

    fig, ax = plt.subplots(figsize=(10, 8))
    ax = data.plot(ax=ax)
    fig = plot_predict(res,
                       start=data.index[0],
                       end=data.index[-1],
                       ax=ax,
                       plot_insample=False)
    legend = ax.legend(["Actual price", "Forecast", "95% Confidence Interval"],
                       loc='upper left')

    fig.savefig("quotes/static/plots/forecast_vs_actual.jpg")
    return (model, res, model_summary)
Exemple #2
0
def test_predict_plot(use_pandas, model_and_args, alpha):
    model, kwargs = model_and_args
    rs = np.random.RandomState(0)
    y = rs.standard_normal(1000)
    for i in range(2, 1000):
        y[i] += 1.8 * y[i - 1] - 0.9 * y[i - 2]
    y = y[100:]
    if use_pandas:
        index = pd.date_range("1960-1-1", freq="M", periods=y.shape[0] + 24)
        start = index[index.shape[0] // 2]
        end = index[-1]
        y = pd.Series(y, index=index[:-24])
    else:
        start = y.shape[0] // 2
        end = y.shape[0] + 24
    res = model(y, **kwargs).fit()
    fig = plot_predict(res, start, end, alpha=alpha)
    assert isinstance(fig, plt.Figure)
Exemple #3
0
def Arima_And_plot(y, country):
    arma_mod = ARIMA(y, order=(5, 0, 5), trend='n')
    arma_res = arma_mod.fit()

    SARIMAX_results = arma_res.summary()

    start_date, end_date = max(y.index) - pd.Timedelta(days=90), max(
        y.index) + pd.Timedelta(days=10)

    st.write('## ARIMA model for {}'.format(country))
    st.text(SARIMAX_results)

    st.write('## Forecasts for {}'.format(country))
    sns.set_style("darkgrid", {"axes.facecolor": ".9"})
    f, ax = plt.subplots(figsize=(10, 8))
    date_start = max(y.index) - pd.Timedelta(days=90)
    ax.plot(y[(y.index >= date_start)], 'r', label='Actuals')
    f = plot_predict(arma_res, start=start_date, end=end_date, ax=ax)
    ax.legend(loc='upper right')
    st.pyplot(f)
Exemple #4
0
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pandas import datetime
from statsmodels.graphics.tsaplots import plot_predict
from statsmodels.tsa.arima_process import arma_generate_sample
from statsmodels.tsa.arima.model import ARIMA
from sklearn.metrics import mean_squared_error
from math import sqrt

np.random.seed(0)
arparams = np.array([0.75, -0.25])
maparams = np.array([0.65, 0.35])
arparams = np.r_[1, -arparams]
maparams = np.r_[1, maparams]
nobs = 1000
y = arma_generate_sample(arparams, maparams, nobs)

dates = pd.date_range("1950-1-1", freq="M", periods=nobs)
y = pd.Series(y, index=dates)
arma_mod = ARIMA(y, order=(2, 0, 2), trend="n")
arma_res = arma_mod.fit()
print(arma_res.summary())
fig, ax = plt.subplots(figsize=(10, 8))
fig = plot_predict(arma_res, start="1999-06-30", end="2001-05-31", ax=ax)
legend = ax.legend(loc="upper left")

plt.show()
Exemple #5
0
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pandas import datetime
from statsmodels.graphics.tsaplots import plot_predict
from statsmodels.tsa.arima_process import arma_generate_sample
from statsmodels.tsa.arima.model import ARIMA
from sklearn.metrics import mean_squared_error
from math import sqrt

n = 100
N = 10000
mu = np.repeat(np.sin(np.arange(n)), int(N / n))
X = np.random.normal(5, 25, int(N))
Y = X + mu
plt.plot(Y)
plt.plot(mu, color='red')
plt.title("Ciclic trend")
plt.legend(['$Y_t$', '$\mu_t$'])
plt.show()

ma2 = ARIMA(Y, order=(0, 0, 2), trend="n")
ma2_res = ma2.fit()
print(ar1_res.summary())

fig, ax = plt.subplots(figsize=(10, 8))
fig = plot_predict(ma2_res, start=1, end=2 * N, ax=ax)
plt.plot(Y)
legend = ax.legend(loc="upper left")
plt.show()
Exemple #6
0
   e_t=np.random.normal(0,1)
   y=np.append(y,a1*y[-1]+a2*y[-2]+e_t)


y.mean()
y.std()
#plt.plot(y);plt.show()

# Predict
l=20
ar2 = ARIMA(y, order=(2, 0, 0))
ar2_res = ar2.fit()
print(ar2_res.summary())

fig, ax = plt.subplots(figsize=(10, 8))
fig = plot_predict(ar2_res, start=0,end=N+l, ax=ax)
plt.plot(y)
legend = ax.legend(loc="upper left")
plt.show()

####################################################################



# AR(1)
N=1000
a1=0.5
sigma=0.1
x=np.arange(1)
y=np.append(x,a1*x+np.random.normal(0,sigma))