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]:
{'intercept': 0.1, 'phi': array([[ 0.04560256],
        [ 0.0535601 ],
        [-0.78190871],
        [ 1.30062633],
        [ 0.46616754]]), 'sigma': 1.0}

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()


10000
the loss is 86.566144
the loss is 85.883621
the loss is 85.059396
the loss is 84.174521
the loss is 83.256735
the loss is 82.315231
the loss is 81.352711
the loss is 80.369586
the loss is 79.365436
the loss is 78.339511
the loss is 77.290909
the loss is 76.218632
the loss is 75.121597
the loss is 73.998645
the loss is 72.848528
the loss is 71.669908
the loss is 70.461345
the loss is 69.221287
the loss is 67.948060
the loss is 66.639851
the loss is 65.294697
the loss is 63.910465
the loss is 62.484833
the loss is 61.015266
the loss is 59.498990
the loss is 57.932961
the loss is 56.313829
the loss is 54.637897
the loss is 52.901068
the loss is 51.098788
the loss is 49.225977
the loss is 47.276941
the loss is 45.245272
the loss is 43.123726
the loss is 40.904067
the loss is 38.576880
the loss is 36.131338
the loss is 33.554905
the loss is 30.832954
the loss is 27.948286
the loss is 24.880485
the loss is 21.605075
the loss is 18.092364
the loss is 14.305873
the loss is 10.200102
the loss is 5.717319
the loss is 0.782781
the loss is -4.702611
the loss is -10.874067
the loss is -17.922675
the loss is -26.130693
the loss is -35.939622
the loss is -48.095549
the loss is -64.006631
the loss is -86.830990
the loss is -126.259356

In [5]:
AR_model.params


Out[5]:
{'intercept': array([ 0.00019801]), 'phi': array([[ 0.04563594],
        [ 0.05349392],
        [-0.78162069],
        [ 1.29967032],
        [ 0.46572242]]), 'sigma': array([ 0.01330691])}

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]:
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  1., -1.,  0.,  0.,  1.,  0., -1.,  0.,  1.,
         0.,  0., -1.,  1.,  0., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0., -1.,  1.,  0.,  0.,
        -1.,  0.,  0.,  1.,  0.,  0., -1.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  1., -1.,  0.,  0.,  1.,  0.,  0., -1.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0., -1.,  0.,  0.,
         1.,  0., -1.,  0.,  0.,  1.,  0., -1.,  0.,  0.,  0.,  0.,  0.,
         0.,  1.,  0.,  0., -1.,  0.,  0.,  1.,  0.,  0., -1.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1., -1.,  0.,  0.,  1.,
         0., -1.,  1.,  0.,  0., -1.,  0.,  1.,  0.,  0., -1.,  0.,  1.,
         0., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0., -1.,  0.,  1.,
         0.,  0., -1.,  1., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1., -1.,  0.,  0.,  0.,
         1., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1., -1.,  0.,
         0.,  1.,  0., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

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]


The autoreload extension is already loaded. To reload it, use:
  %reload_ext autoreload
114.269821449

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]:
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  1., -1.,  0.,  0.,  1., -1.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  1.,  0.,  0., -1.,  0.,  0.,  0.,  0.,  0.,
         0.,  1., -1.,  0.,  0.,  1., -1.,  0.,  0.,  0.,  1.,  0.,  0.,
         0., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  1., -1.,  0.,  0.,  1.,
        -1.,  0.,  0.,  0.,  0.,  1.,  0.,  0., -1.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  1., -1.,  0.,  0.,  0.,  0.,  1.,
         0.,  0., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         1., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1., -1.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  1., -1.,  0.,  0.,  0.,  1.,
         0.,  0.,  0., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  1., -1.,  0.,
         0.,  1., -1.,  0.,  0.,  0.,  1., -1.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  1., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  1.,  0.,  0., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  1., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,
        -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1., -1.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  1.,  0., -1.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0., -1.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1., -1.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0., -1.,  0.,  0.,
         0.,  0.,  0.,  0.,  1., -1.,  0.,  0.,  0.,  1.,  0.,  0., -1.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,
         0.,  0., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         1., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  1.,  0., -1.,  0.,  0.,  1.,  0.,  0., -1.,  0.,  0.,
         0.,  0.,  0.,  0.,  1.,  0.,  0.,  0., -1.,  0.,  0.,  0.,  0.,
         0.,  1., -1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,
         0.,  0., -1.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0., -1.,  0.,
         0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0., -1.,  0.,  0.,  0.,
         0.,  0.,  1.,  0., -1.,  0.,  0.,  1.,  0.,  0., -1.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

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]


114.269821449

In [ ]: