Skip to content

Commit c5e1335

Browse files
committed
More Appropriate Modifications
1 parent 8f36116 commit c5e1335

4 files changed

Lines changed: 50 additions & 48 deletions

File tree

Algorithm.Python/KerasNeuralNetworkAlgorithm.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,10 @@ def Initialize(self):
3838
self.lookback = 30 # day of lookback for historical data
3939

4040
self.Schedule.On(self.DateRules.Every(DayOfWeek.Monday), self.TimeRules.AfterMarketOpen("SPY", 28), self.NetTrain) # train Neural Network
41-
self.Schedule.On(self.DateRules.Every(DayOfWeek.Monday), self.TimeRules.AfterMarketOpen("SPY", 30), self.Trade) # trading
41+
self.Schedule.On(self.DateRules.Every(DayOfWeek.Monday), self.TimeRules.AfterMarketOpen("SPY", 30), self.Trade)
4242

4343
def NetTrain(self):
44-
# get daily historical data
44+
# Daily historical data is used to train the machine learning model
4545
history = self.History(self.symbols, self.lookback + 1, Resolution.Daily)
4646

4747
# dicts that store prices for training
@@ -55,14 +55,14 @@ def NetTrain(self):
5555
for symbol in self.symbols:
5656
if not history.empty:
5757
# x: pridictors; y: response
58-
self.prices_x[symbol.Value] = list(history.loc[symbol.Value]['open'])[:-1]
59-
self.prices_y[symbol.Value] = list(history.loc[symbol.Value]['open'])[1:]
58+
self.prices_x[symbol] = list(history.loc[symbol.Value]['open'])[:-1]
59+
self.prices_y[symbol] = list(history.loc[symbol.Value]['open'])[1:]
6060

6161
for symbol in self.symbols:
62-
if symbol.Value in self.prices_x:
62+
if symbol in self.prices_x:
6363
# convert the original data to np array for fitting the keras NN model
64-
x_data = np.array(self.prices_x[symbol.Value])
65-
y_data = np.array(self.prices_y[symbol.Value])
64+
x_data = np.array(self.prices_x[symbol])
65+
y_data = np.array(self.prices_y[symbol])
6666

6767
# build a neural network from the 1st layer to the last layer
6868
model = Sequential()
@@ -85,15 +85,17 @@ def NetTrain(self):
8585
y_pred_final = model.predict(y_data)[0][-1]
8686

8787
# Follow the trend
88-
self.buy_prices[symbol.Value] = y_pred_final + np.std(y_data)
89-
self.sell_prices[symbol.Value] = y_pred_final - np.std(y_data)
88+
self.buy_prices[symbol] = y_pred_final + np.std(y_data)
89+
self.sell_prices[symbol] = y_pred_final - np.std(y_data)
9090

9191
def Trade(self):
92+
'''
93+
Enter or exit positions based on relationship of the open price of the current bar and the prices defined by the machine learning model.
94+
Liquidate if the open price is below the sell price and buy if the open price is above the buy price
95+
'''
9296
for holding in self.Portfolio.Values:
93-
# liquidate
94-
if self.CurrentSlice[holding.Symbol.Value].Open < self.sell_prices[holding.Symbol.Value] and holding.Invested:
95-
self.Liquidate(i.Symbol)
97+
if self.CurrentSlice[holding.Symbol].Open < self.sell_prices[holding.Symbol] and holding.Invested:
98+
self.Liquidate(holding.Symbol)
9699

97-
# buy
98-
if self.CurrentSlice[holding.Symbol.Value].Open > self.buy_prices[holding.Symbol.Value] and not holding.Invested:
100+
if self.CurrentSlice[holding.Symbol].Open > self.buy_prices[holding.Symbol] and not holding.Invested:
99101
self.SetHoldings(holding.Symbol, 1 / len(self.symbols))

Algorithm.Python/PytorchNeuralNetworkAlgorithm.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,10 @@ def Initialize(self):
3939
self.lookback = 30 # days of historical data (look back)
4040

4141
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.AfterMarketOpen("SPY", 28), self.NetTrain) # train the NN
42-
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.AfterMarketOpen("SPY", 30), self.Trade) # trade
42+
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.AfterMarketOpen("SPY", 30), self.Trade)
4343

4444
def NetTrain(self):
45-
# get historical data
45+
# Daily historical data is used to train the machine learning model
4646
history = self.History(self.symbols, self.lookback + 1, Resolution.Daily)
4747

4848
# dicts that store prices for training
@@ -56,21 +56,21 @@ def NetTrain(self):
5656
for symbol in self.symbols:
5757
if not history.empty:
5858
# x: preditors; y: response
59-
self.prices_x[symbol.Value] = list(history.loc[symbol.Value]['open'])[:-1]
60-
self.prices_y[symbol.Value] = list(history.loc[symbol.Value]['open'])[1:]
59+
self.prices_x[symbol] = list(history.loc[symbol.Value]['open'])[:-1]
60+
self.prices_y[symbol] = list(history.loc[symbol.Value]['open'])[1:]
6161

6262
for symbol in self.symbols:
6363
# if this symbol has historical data
64-
if symbol.Value in self.prices_x:
64+
if symbol in self.prices_x:
6565

6666
net = Net(n_feature=1, n_hidden=10, n_output=1) # define the network
6767
optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
6868
loss_func = torch.nn.MSELoss() # this is for regression mean squared loss
6969

7070
for t in range(200):
7171
# Get data and do preprocessing
72-
x = torch.from_numpy(np.array(self.prices_x[symbol.Value])).float()
73-
y = torch.from_numpy(np.array(self.prices_y[symbol.Value])).float()
72+
x = torch.from_numpy(np.array(self.prices_x[symbol])).float()
73+
y = torch.from_numpy(np.array(self.prices_y[symbol])).float()
7474

7575
# unsqueeze data (see pytorch doc for details)
7676
x = x.unsqueeze(1)
@@ -85,18 +85,19 @@ def NetTrain(self):
8585
optimizer.step() # apply gradients
8686

8787
# Follow the trend
88-
self.buy_prices[symbol.Value] = net(y)[-1] + np.std(y.data.numpy())
89-
self.sell_prices[symbol.Value] = net(y)[-1] - np.std(y.data.numpy())
88+
self.buy_prices[symbol] = net(y)[-1] + np.std(y.data.numpy())
89+
self.sell_prices[symbol] = net(y)[-1] - np.std(y.data.numpy())
9090

9191
def Trade(self):
92-
92+
'''
93+
Enter or exit positions based on relationship of the open price of the current bar and the prices defined by the machine learning model.
94+
Liquidate if the open price is below the sell price and buy if the open price is above the buy price
95+
'''
9396
for holding in self.Portfolio.Values:
94-
# liquidate
95-
if self.CurrentSlice[holding.Symbol.Value].Open < self.sell_prices[holding.Symbol.Value] and holding.Invested:
97+
if self.CurrentSlice[holding.Symbol].Open < self.sell_prices[holding.Symbol] and holding.Invested:
9698
self.Liquidate(holding.Symbol)
9799

98-
# buy
99-
if self.CurrentSlice[holding.Symbol.Value].Open > self.buy_prices[holding.Symbol.Value] and not holding.Invested:
100+
if self.CurrentSlice[holding.Symbol].Open > self.buy_prices[holding.Symbol] and not holding.Invested:
100101
self.SetHoldings(holding.Symbol, 1 / len(self.symbols))
101102

102103

Algorithm.Python/ScikitLearnLinearRegressionAlgorithm.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ def Initialize(self):
4141

4242

4343
def Regression(self):
44+
# Daily historical data is used to train the machine learning model
4445
history = self.History(self.symbols, self.lookback, Resolution.Daily)
4546

4647
# price dictionary: key: symbol; value: historical price
@@ -51,15 +52,15 @@ def Regression(self):
5152
for symbol in self.symbols:
5253
if not history.empty:
5354
# get historical open price
54-
self.prices[symbol.Value] = list(history.loc[symbol.Value]['open'])
55+
self.prices[symbol] = list(history.loc[symbol.Value]['open'])
5556

5657
# A is the design matrix
5758
A = range(self.lookback + 1)
5859

5960
for symbol in self.symbols:
60-
if symbol.Value in self.prices:
61+
if symbol in self.prices:
6162
# response
62-
Y = self.prices[symbol.Value]
63+
Y = self.prices[symbol]
6364
# features
6465
X = np.column_stack([np.ones(len(A)), A])
6566

@@ -88,14 +89,12 @@ def Trade(self):
8889
thod_buy = 0.001 # threshold of slope to buy
8990
thod_liquidate = -0.001 # threshold of slope to liquidate
9091

91-
# liquidate
9292
for holding in self.Portfolio.Values:
9393
slope = self.slopes[holding.Symbol]
9494
# liquidate when slope smaller than thod_liquidate
9595
if holding.Invested and slope < thod_liquidate:
9696
self.Liquidate(holding.Symbol)
9797

98-
# buy
9998
for symbol in self.symbols:
10099
# buy when slope larger than thod_buy
101100
if self.slopes[symbol] > thod_buy:

Algorithm.Python/TensorFlowNeuralNetworkAlgorithm.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def add_layer(self, inputs, in_size, out_size, activation_function=None):
5252
return outputs
5353

5454
def NetTrain(self):
55-
# get historical data
55+
# Daily historical data is used to train the machine learning model
5656
history = self.History(self.symbols, self.lookback + 1, Resolution.Daily)
5757

5858
# model: use prices_x to fit prices_y; key: symbol; value: according price
@@ -63,16 +63,16 @@ def NetTrain(self):
6363

6464
for symbol in self.symbols:
6565
if not history.empty:
66-
# get historical data if not empty
66+
# Daily historical data is used to train the machine learning model
6767
# use open prices to predict the next days'
68-
self.prices_x[symbol.Value] = list(history.loc[symbol.Value]['open'][:-1])
69-
self.prices_y[symbol.Value] = list(history.loc[symbol.Value]['open'][1:])
68+
self.prices_x[symbol] = list(history.loc[symbol.Value]['open'][:-1])
69+
self.prices_y[symbol] = list(history.loc[symbol.Value]['open'][1:])
7070

7171
for symbol in self.symbols:
72-
if symbol.Value in self.prices_x:
72+
if symbol in self.prices_x:
7373
# create numpy array
74-
x_data = np.array(self.prices_x[symbol.Value]).astype(np.float32).reshape((-1,1))
75-
y_data = np.array(self.prices_y[symbol.Value]).astype(np.float32).reshape((-1,1))
74+
x_data = np.array(self.prices_x[symbol]).astype(np.float32).reshape((-1,1))
75+
y_data = np.array(self.prices_y[symbol]).astype(np.float32).reshape((-1,1))
7676

7777
# define placeholder for inputs to network
7878
xs = tf.placeholder(tf.float32, [None, 1])
@@ -101,19 +101,19 @@ def NetTrain(self):
101101

102102
# predict today's price
103103
y_pred_final = sess.run(prediction, feed_dict = {xs: y_data})[0][-1]
104-
# self.Debug(f'pred price: {y_pred_final}')
105104

106105
# get sell prices and buy prices as trading signals
107-
self.sell_prices[symbol.Value] = y_pred_final - np.std(y_data)
108-
self.buy_prices[symbol.Value] = y_pred_final + np.std(y_data)
106+
self.sell_prices[symbol] = y_pred_final - np.std(y_data)
107+
self.buy_prices[symbol] = y_pred_final + np.std(y_data)
109108

110109
def Trade(self):
111-
# Trending strategy
110+
'''
111+
Enter or exit positions based on relationship of the open price of the current bar and the prices defined by the machine learning model.
112+
Liquidate if the open price is below the sell price and buy if the open price is above the buy price
113+
'''
112114
for holding in self.Portfolio.Values:
113-
# liquidate if open price smaller than sell_price
114-
if self.CurrentSlice[holding.Symbol.Value].Open < self.sell_prices[holding.Symbol.Value] and holding.Invested:
115+
if self.CurrentSlice[holding.Symbol].Open < self.sell_prices[holding.Symbol] and holding.Invested:
115116
self.Liquidate(holding.Symbol)
116117

117-
# buy if open price larger than buy_price
118-
if self.CurrentSlice[holding.Symbol.Value].Open > self.buy_prices[holding.Symbol.Value] and not holding.Invested:
118+
if self.CurrentSlice[holding.Symbol].Open > self.buy_prices[holding.Symbol] and not holding.Invested:
119119
self.SetHoldings(holding.Symbol, 1 / len(self.symbols))

0 commit comments

Comments
 (0)