Sunday, April 8, 2018

Prediction of stockprice with trained weight with Google API

This is just a project for a practice. This is predicting based only on previous 10 closing prices. It is highly possible that the information (columns of dataset) to predict is not enough and the prediction is not precise.

1. Prediction of stockprice (Training a model)
2. Prediction of stockprice (Prediction by CSV)
3. Prediction of stockprice with trained weight with Google API

At first, install google API like this:
$ pip install googlefinance.client
Also you need a trained weight file. See Prediction of stockprice (Training a model) .

If you want trained weight and model:
https://www.dropbox.com/s/cepuxsgxj90kuqa/stockprice_model.hdf5?dl=0

Please note that it is predicting next closing price.

This predicts today's stock price. The code:
#-*- coding: utf-8 -*-
import numpy
import pandas
import matplotlib.pyplot as plt
from decimal import *

from keras.models import load_model
from sklearn import preprocessing
from sklearn.preprocessing import StandardScaler
from keras.models import Sequential
from keras.models import model_from_json
from keras.layers.core import Dense, Activation
from keras.layers.recurrent import LSTM
import keras.backend.tensorflow_backend as KTF
import os.path
from googlefinance.client import get_price_data, get_prices_data, get_prices_time_data

class Prediction :
 
  def load_data(self, data):
    X = []
    X.append(data.iloc[0:10].as_matrix())
    #Y.append(data.iloc[i+n_prev].as_matrix())
    retX = numpy.array(X)
    #retY = numpy.array(Y)
    return retX
 
  def validate_data(self, data):
    if(len(data.index) > 10):
      data = data.drop(data.index[0])
      data = data.reset_index(drop=True)
    return data

  def create_model(self, f_model, model_filename):
    print(os.path.join(f_model,model_filename))
    if os.path.isfile(os.path.join(f_model,model_filename)):
      print('Saved parameters found. I will use this file...')
      model = load_model(os.path.join(f_model,model_filename))
    else:
      print('Saved parameters weren\'t found')
      return
    return model
 
if __name__ == "__main__":

  f_log = './'
  f_model = './'
  model_filename = 'stockprice_model.hdf5'

  prediction = Prediction()

  # Data
  # S&P 500 Index
  param = {
    'q': ".INX", # Stock symbol (ex: "AAPL")
    'i': "86400", # Interval size in seconds ("86400" = 1 day intervals)
    'x': "INDEXSP", # Stock exchange symbol on which stock is traded (ex: "NASD")
    'p': "11d" # Period (Ex: "1d" = 1 day)
  }
  data = get_price_data(param)
  data = data.drop('Volume',axis=1)
  data = data.reset_index()
  data = prediction.validate_data(data)
  print(data)
  #data = None
  #data_ = pandas.read_csv('./csv/%s' % (prediction.csv))
  #data = data_ if (data is None) else pandas.concat([data, data_])

  data.columns = ['Date', 'Open', 'High', 'Low', 'Close']
  data['Date'] = pandas.to_datetime(data['Date'], format='%Y-%m-%d')
  # Data of closing price
  scaler = StandardScaler()
  scaler.fit(data[['Close']])
  data['Close'] = scaler.transform(data[['Close']])
  data = data.sort_values(by='Date')
  data = data.reset_index(drop=True)
  data = data.loc[:, ['Date', 'Close']]

  x_test = prediction.load_data(data[['Close']])

  model = prediction.create_model(f_model, model_filename)

  predicted = model.predict(x_test, verbose=1)
  print("Next stock price is predicted to be: " + str(float(scaler.inverse_transform(predicted))))