Implement first version of manual strategy

This commit is contained in:
2020-10-27 19:57:46 -04:00
parent 1798e9569e
commit 4679910374
5 changed files with 56 additions and 112 deletions

View File

@@ -1,6 +1,7 @@
import datetime as dt
import pandas as pd
import util as ut
import util
import indicators
class ManualStrategy:
@@ -20,7 +21,7 @@ class ManualStrategy:
# example usage of the old backward compatible util function
syms = [symbol]
dates = pd.date_range(sd, ed)
prices_all = ut.get_data(syms, dates) # automatically adds SPY
prices_all = util.get_data(syms, dates) # automatically adds SPY
prices = prices_all[syms] # only portfolio symbols
# prices_SPY = prices_all['SPY'] # only SPY, for comparison later
if self.verbose:
@@ -28,31 +29,60 @@ class ManualStrategy:
# example use with new colname
# automatically adds SPY
volume_all = ut.get_data(syms, dates, colname="Volume")
volume_all = util.get_data(syms, dates, colname="Volume")
volume = volume_all[syms] # only portfolio symbols
# volume_SPY = volume_all['SPY'] # only SPY, for comparison later
if self.verbose:
print(volume)
def macd_strat(self, macd, orders):
def strat(ser):
m = macd.loc[ser.index]
prev_macd, prev_signal = m.iloc[0]
cur_macd, cur_signal = m.iloc[1]
shares = 0
if cur_macd < -1 and prev_macd < prev_signal and cur_macd > cur_signal:
if self.holding == 0:
shares = 1000
elif self.holding == -1000:
shares = 2000
elif cur_macd > 1 and prev_macd > prev_signal and cur_macd < cur_signal:
if self.holding == 0:
shares = -1000
elif self.holding == 1000:
shares = -2000
self.holding += shares
return shares
orders['Shares'] = orders['Shares'].rolling(2).apply(strat)
# this method should use the existing policy and test it against new data
def testPolicy(self, symbol="IBM",
sd=dt.datetime(2009, 1, 1),
ed=dt.datetime(2010, 1, 1),
sv=10000):
dates = pd.date_range(sd, ed)
prices = ut.get_data([symbol], dates) # automatically adds SPY
orders = pd.DataFrame(index=prices.index)
self.holding = 0
df = util.get_data([symbol], pd.date_range(sd, ed))
df.drop(columns=["SPY"], inplace=True)
macd = indicators.macd(df, symbol)
orders = pd.DataFrame(index=df.index)
orders["Symbol"] = symbol
orders["Order"] = ""
orders["Shares"] = 0
self.macd_strat(macd, orders)
# here we build a fake set of trades
orders.iloc[0] = [symbol, "BUY", 1000]
orders.iloc[40] = [symbol, "SELL", 1000]
orders.iloc[41] = [symbol, "BUY", 1000]
orders.iloc[60] = [symbol, "SELL", 2000]
orders.iloc[61] = [symbol, "BUY", 2000]
orders.iloc[-1] = [symbol, "SELL", 1000]
orders = orders[orders["Shares"] != 0]
# orders.iloc[0] = [symbol, "BUY", 1000]
# orders.iloc[40] = [symbol, "SELL", 1000]
# orders.iloc[41] = [symbol, "BUY", 1000]
# orders.iloc[60] = [symbol, "SELL", 2000]
# orders.iloc[61] = [symbol, "BUY", 2000]
# orders.iloc[-1] = [symbol, "SELL", 1000]
# orders = orders[orders["Shares"] != 0]
return orders