In [1]:
# load the packages needed
import numpy as np
import sys
if "../" not in sys.path:
sys.path.append("../")
from tsap.solver import Solver
from tsap.model import AR, MA
import tsap.data_processor as dp
import tsap.inference as inf
from tsap.ts_gen import ar1_gen
import tsap.trading as tr
In [2]:
# read data and do the preprocessing
data = np.loadtxt("../data/GOOG.csv", delimiter=',')
X = np.array([data[0:100]])
Y = dp.get_return(X)
In [3]:
# initialize model
lag = 5
sigma = 1.0
intercept = 0.1
phi = np.array([[ 0.04560256],
[ 0.0535601 ],
[-0.78190871],
[ 1.30062633],
[ 0.46616754]])
AR_model = AR(lag=lag, phi=phi, sigma=sigma, intercept=intercept)
AR_model.params
Out[3]:
In [4]:
# solve the model
_, grads = AR_model.loss(Y)
solver = Solver(AR_model, Y,
update_rule='sgd_momentum',
optim_config={
'learning_rate': 1e-6,
},
num_epochs=10000, batch_size=1,
print_every=10)
solver.train()
In [5]:
AR_model.params
Out[5]:
In [6]:
# get the trading profit, signal and predicted price
l=100
nstep=20
window=5
money=100
profit, signal, pred_price = tr.rolltrade(np.array([data]),AR_model,l,nstep,window,money)
signal
Out[6]:
In [21]:
# This is a bit of magic to make matplotlib figures appear inline in the notebook
# rather than in a new window.
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# Some more magic so that the notebook will reload external python modules;
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
plt.figure()
plt.plot(pred_price[0,0:data.shape[0]-11],'r')
plt.plot(data,'b')
plt.hold(True)
plt.xlabel('time')
plt.ylabel('stock price')
plt.title('price prediction')
plt.show()
flag1=0
flag2=0
plt.figure()
plt.plot(data[0:],'b')
for i in range(data.shape[0]-l):
if signal[0,i]==1:
if flag1==0:
plt.plot(i,data[i],'ro',label="buy")
flag1=1
else:
plt.plot(i,data[i],'ro')
if signal[0,i]==-1:
if flag2==0:
plt.plot(i,data[i],'g^',label="sell")
flag2=1
else:
plt.plot(i,data[i],'g^')
plt.xlabel('Time')
plt.ylabel('Stock price')
plt.title('Trading signal of Google stock')
plt.legend(loc="lower right")
plt.savefig("signal.pdf")
plt.show()
plt.figure()
plt.plot(profit[0,:],'r')
plt.xlabel('Time')
plt.ylabel('Dollars')
plt.title('Profit')
plt.savefig("profit.pdf")
plt.show()
"""plt.figure()
plt.plot(data[l:],'b')
for i in range(data.shape[0]-l):
if signal[0,l+i]==1:
plt.plot(i,data[l+i],'ro')
if signal[0,l+i]==-1:
plt.plot(i,data[l+i],'g^')
plt.xlabel('time')
plt.ylabel('stock price')
plt.title('trading signal')"""
flag1=0
flag2=0
plt.figure()
plt.plot(data[l:l+20],'b')
for i in range(20):
if signal[0,100+i]==1:
if flag1==0:
plt.plot(i,data[100+i],'ro',label="buy")
flag1=1
else:
plt.plot(i,data[100+i],'ro')
if signal[0,100+i]==-1:
if flag2==0:
plt.plot(i,data[100+i],'g^',label="sell")
flag2=1
else:
plt.plot(i,data[100+i],'g^')
plt.xlabel('Time')
plt.ylabel('Stock price')
plt.title('Trading signal for 20 days')
plt.legend(loc="lower right")
plt.savefig("20days.pdf")
plt.show()
print profit[0,-1]
In [8]:
phi_y, sigma_y = inf.yule_walker(Y, order =5, method='unbiased')
AR_model_y = AR(lag=5, phi=phi_y, sigma=sigma_y, intercept=0)
l=100
nstep=20
window=5
money=100
profit, signal, pred_price = tr.rolltrade(np.array([data]),AR_model_y,l,nstep,window,money)
signal
Out[8]:
In [20]:
# This is a bit of magic to make matplotlib figures appear inline in the notebook
# rather than in a new window.
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# Some more magic so that the notebook will reload external python modules;
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
plt.figure()
plt.plot(pred_price[0,0:data.shape[0]-11],'r')
plt.plot(data,'b')
plt.hold(True)
plt.xlabel('time')
plt.ylabel('stock price')
plt.title('price prediction')
plt.show()
plt.figure()
plt.plot(data[0:],'b')
for i in range(data.shape[0]-l):
if signal[0,i]==1:
plt.plot(i,data[i],'ro')
if signal[0,i]==-1:
plt.plot(i,data[i],'g^')
plt.xlabel('time')
plt.ylabel('stock price')
plt.title('trading signal')
plt.show()
plt.figure()
plt.plot(profit[0,:],'r')
plt.xlabel('time')
plt.ylabel('profit')
plt.title('profit')
plt.show()
"""plt.figure()
plt.plot(data[l:],'b')
for i in range(data.shape[0]-l):
if signal[0,l+i]==1:
plt.plot(i,data[l+i],'ro')
if signal[0,l+i]==-1:
plt.plot(i,data[l+i],'g^')
plt.xlabel('time')
plt.ylabel('stock price')
plt.title('trading signal')"""
plt.figure()
plt.plot(data[l:l+20],'b')
for i in range(20):
if signal[0,100+i]==1:
plt.plot(i,data[100+i],'ro')
if signal[0,100+i]==-1:
plt.plot(i,data[100+i],'g^')
plt.xlabel('time')
plt.ylabel('stock price')
plt.title('trading signal')
plt.show()
print profit[0,-1]
In [ ]: