import numpy as np
import pandas as pd
import pandas_datareader as pdr
import matplotlib.pyplot as plt
%matplotlib inline
import sys
sys.path.insert(0,'./financial_calcs/')
import trading_calcs.standard as std_calcs
from sklearn import tree
X = [[0,0],[1,1]]
Y = [0,1]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X, Y)
clf.predict([[2.,2.]])
An example of creating in increasing price, and creating a VWAP to go with it.
dti = pd.date_range('2020-01-01',periods=200,freq='D')
inc_price = np.linspace(20,25,100)
decr_price = np.linspace(25,20,100)
price = np.hstack((inc_price, decr_price))
s_price = pd.Series(price, index=dti, name='Price')
volume_arry = np.ones((200,))*50000.0
volume = pd.Series(volume_arry, index=dti, name='Volume')
vwap = std_calcs.vwap_calc(s_price, volume, 14)
totvwap = vwap.sum()
series_pct_chng = s_price.pct_change(1)
plt.plot(series_pct_chng)
Experimental fake values
price = np.array([25, 24, 23, 24, 25, 24, 23, 24, 24.5, 25.5, 26.0, 26.5, 27.0, 27.5])
dti = pd.date_range('2020-01-01',periods=len(price),freq='D')
vol = np.array([30, 50, 20, 80, 30, 90, 10, 80, 90, 80, 85, 90, 110, 95])
s_price = pd.Series(price, index=dti, name='Price')
s_vol = pd.Series(vol, index=dti, name='Volume')
s_vwap = std_calcs.vwap_calc(s_price,s_vol,2)
s_vwap
plt.plot(s_price.pct_change(1))
s_price.plot()
s_vwap.plot()
Get the percent change from price over 3 days, then shift back by three days. Each index now indicates what the percent return will be 3 days into the future.
future_price = s_price.pct_change(3).shift(-3)
future_price=future_price.fillna(0)
future_price
This is where positions are calculated. If the future price will be positive then buy (1).
pos = np.where(future_price > 0, 1,0)
pos
This is where the sell position is decided, when future price will be negative, sell (-1).
pos1 = np.where(future_price <= 0, -1, pos)
pos1
s_vwap = s_vwap.fillna(method='backfill')
X = np.column_stack((s_price.values,s_vwap.values, s_vol))
X
from sklearn import tree
Y = pos1
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X, Y)
clf.predict([[26,24.3]])
tree.plot_tree(clf)
The following represents the position, that is where to buy.
pos = np.where((s_price < (1-0.01)*s_vwap),1,0)
pos
The following makes the position last for 3 days.
def position_expander(pos,duration):
i = 0
while(i<len(pos)):
if pos[i]:
#print(pos[i+1:i+6])
pos[i+1:i+duration] = 1
i += duration
else:
i += 1
return pos
pos = position_expander(pos,3)
pos
pct_chng = s_price.pct_change(1)
pct_chng
system = pos*pct_chng
system
plt.plot(100.0*system.cumsum())