Making 5-minute prediction script working all the time

Spent another 40 mins on reworking the script to plot actual and predicted price all the time based on real-time data from database.

Here’s the code:


from pandas import read_csv
from pandas import datetime
from matplotlib import pyplot
from statsmodels.tsa.arima_model import ARIMA
from sklearn.metrics import mean_squared_error
import pymysql

pyplot.show()
while 1:
    conn = pymysql.connect(host='192.168.0.25', user='***', password='***', db='solocryptoprenuer',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
    print('Connected to database')
    cur = conn.cursor()
    sql = "SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(time)/300)*300) x, AVG(price) price FROM gdax_matches WHERE product_id = 'BTC-USD' AND time >= now() - INTERVAL 8 HOUR GROUP BY x"
    print(sql)
    cur.execute(sql)
    X = []
    for row in cur:
        print(row['price'])
        X.append( row[ 'price' ] )
    cur.close()
    conn.close()

    size = int(len(X) * 0.66)
    train, test = X[0:size], X[size:len(X)]
    history = [x for x in train]
    predictions = list()
    i=0
    for t in range(len(test)):
        i+=1
        model = ARIMA(history, order=(7,1,0))
        model_fit = model.fit(disp=0)
        output = model_fit.forecast()
        yhat = output[0]
        predictions.append(yhat)
        obs = test[t]
        history.append(obs)
        print('%d, predicted=%f, expected=%f' % (i, yhat, obs))
    error = mean_squared_error(test, predictions)
    
    #add 1 more prediction
    model = ARIMA(history, order=(7,1,0))
    model_fit = model.fit(disp=0)
    output = model_fit.forecast()
    yhat = output[0]
    predictions.append(yhat)
    print( 'Next 5 minute prediction: %f' % yhat )
    
    print('Test MSE: %.3f' % error)
    # plot
    pyplot.cla()
    pyplot.clf()
    pyplot.plot(test)
    pyplot.plot(predictions, color='red')
    mng = pyplot.get_current_fig_manager()
    mng.window.state('zoomed')
    pyplot.pause(0.0001)

 

Untitled-1
Thanks for reading,
Łukasz.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s