-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trading with SMA indicator
48 lines (32 loc) · 1.8 KB
/
Trading with SMA indicator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# code to combine indicators and backtest the performance
# region imports
from AlgorithmImports import *
# endregion
class Indicators(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2020, 1, 1) # Set Start Date
self.SetEndDate(2023, 1, 1) # Set Start Date
self.SetCash(100000) # Set Strategy Cash
self.spy = self.AddEquity("AAPL", Resolution.Daily).Symbol #set data for SPY
self.sma = self.SMA(self.spy, 30, Resolution.Daily) #set data for SMA
closing_price = self.History(self.spy, 30, Resolution.Daily)["close"] #take historic prices for SMA
for time, price in closing_price.loc[self.spy].items():
self.sma.Update(time,price) #update first 30 values of SMA to historic prices
def OnData(self, data: Slice):
if not self.sma.IsReady: # to check if SMA is ready or not as it is a average indicator
return
#Another indicator to check for high and low of 60 Daily
hist = self.History(self.spy, timedelta(252), Resolution.Daily)
low = min(hist["low"])
high = min(hist["high"])
#combining both trading logics - SMA + High/Low
price = self.Securities[self.spy].Price
if price >= 1.05*high and self.sma.Current.Value > price:
if not self.Portfolio[self.spy].IsLong:
self.SetHoldings(self.spy,1)
if price <= 0.95*low and self.sma.Current.Value < price:
if not self.Portfolio[self.spy].IsShort:
self.SetHoldings(self.spy,-1)
self.Plot("Benchmark", "60m-High", high)
self.Plot("Benchmark", "60m-Low", low)
self.Plot("Benchmark", "60m-High", self.sma.Current.Value)