def __init__(self): # To control operation entries self.orderid = None # Indicators poc = btind.SimpleMovingAverage( self.data0.POC, period=1, plotname='POC', subplot=False, ) ppoc = btind.SimpleMovingAverage( self.data0.PPOC, period=1, plotname='PPOC', subplot=False, ) self.atr = bt.talib.ATR(self.data0.high, self.data0.low, self.data0.close, timeperiod=14) #self.rsi = bt.talib.RSI(self.data0.close, timeperiod=14) #self.macd = bt.talib.MACD(self.data0.close) self.ematr = btind.ExponentialMovingAverage(self.atr, period=89) self.signal1 = btind.CrossOver(self.data0.close, poc, plot=False) self.signal2 = btind.CrossOver(self.data0.close, ppoc, plot=False) self.flag = True self.flag1 = False
def __init__(self): """Initialize the strategy""" self.fastma = dict() self.slowma = dict() self.regime = dict() if self.params.optim: # Use a tuple during optimization self.params.fast, self.params.slow = self.params.optim_fs # fast and slow replaced by tuple's contents if self.params.fast > self.params.slow: raise ValueError( "A SMAC strategy cannot have the fast moving average's window be " + \ "greater than the slow moving average window.") for d in self.getdatanames(): # The moving averages self.fastma[d] = btind.SimpleMovingAverage( self.getdatabyname(d), # The symbol for the moving average period=self.params.fast, # Fast moving average plotname="FastMA: " + d) self.slowma[d] = btind.SimpleMovingAverage( self.getdatabyname(d), # The symbol for the moving average period=self.params.slow, # Slow moving average plotname="SlowMA: " + d) # Get the regime self.regime[d] = self.fastma[d] - self.slowma[ d] # Positive when bullish
def __init__(self): sma = btind.SimpleMovingAverage(period=self.p.smaperiod) sma1 = btind.SimpleMovingAverage(self.data, period=self.params.period1) sma2 = btind.SimpleMovingAverage(period=self.params.period2) myindicator = sma2 - sma1 + self.datas[0].close self.sma = btind.SimpleMovingAverage(period=self.p.period) # see the (delay) notation self.cmpval = self.data.close(-1) > self.sma datasum = btind.SumN(self.data, period=self.p.period1) # using operators / av = datasum / self.p.period1 self.line.sma = av # cannot use "and" operators, backtrader provides several methods close_over_sma = self.data.close > sma self.sma_dist_to_high = self.data.high - sma sma_dist_small = self.sma_dist_to_high < 3.5 sell_sig = bt.And(close_over_sma, sma_dist_small) high_or_low = bt.If(sma1 > self.data.close, self.data.low, self.data.high) self.buysell = btind.CrossOver(self.data.close, sma, plot=True) self.order = None
def __init__(self): """Initialize the strategy""" self.fastma = dict() self.slowma = dict() self.regime = dict() self._addobserver( True, bt.observers.BuySell ) # CAUTION: Abuse of the method, I will change this in future code (see: https://community.backtrader.com/topic/473/plotting-just-the-account-s-value/4) if self.params.optim: # Use a tuple during optimization self.params.fast, self.params.slow = self.params.optim_fs # fast and slow replaced by tuple's contents if self.params.fast > self.params.slow: raise ValueError( "A SMAC strategy cannot have the fast moving average's window be " + \ "greater than the slow moving average window.") for d in self.getdatanames(): # The moving averages self.fastma[d] = btind.SimpleMovingAverage( self.getdatabyname(d), # The symbol for the moving average period=self.params.fast, # Fast moving average plotname="FastMA: " + d) self.slowma[d] = btind.SimpleMovingAverage( self.getdatabyname(d), # The symbol for the moving average period=self.params.slow, # Slow moving average plotname="SlowMA: " + d) # Get the regime self.regime[d] = self.fastma[d] - self.slowma[ d] # Positive when bullish
def set_datalines(self): self.data.spread = btind.SimpleMovingAverage(self.datas[0] - self.datas[1], period=1) self.data.spread.plotinfo.subplot = True self.data.spread.plotinfo.plotabove = True self.data.spread.plotinfo.plotname = list(self.p.asset_names)[0] # Override stat line: # self.stat_asset = btind.SimpleMovingAverage((self.datas[0] + self.datas[1]) / 2, period=1) # self.stat_asset.plotinfo.plot = False self.stat_asset = self.data.spread self.data.std = btind.StdDev(self.data.spread, period=self.p.time_dim, safepow=True) self.data.std.plotinfo.plot = False self.data.features = [ # btind.SimpleMovingAverage(self.data.spread, period=period) for period in self.p.features_parameters btind.EMA(self.data.spread, period=period) for period in self.p.features_parameters ] initial_time_period = np.asarray(self.p.features_parameters).max() + self.p.time_dim self.data.dim_sma = btind.SimpleMovingAverage( self.datas[0], period=initial_time_period ) self.data.dim_sma.plotinfo.plot = False
def __init__(self): self.sma5 = btind.SimpleMovingAverage(period=5) # 5日均线 self.sma10 = btind.SimpleMovingAverage(period=10) # 10日均线 # bt.And 中所有条件都满足时返回 1;有一个条件不满足就返回 0 self.And = bt.And(self.data > self.sma5, self.data > self.sma10, self.sma5 > self.sma10) # bt.Or 中有一个条件满足时就返回 1;所有条件都不满足时返回 0 self.Or = bt.Or(self.data > self.sma5, self.data > self.sma10, self.sma5 > self.sma10) # bt.If(a, b, c) 如果满足条件 a,就返回 b,否则返回 c self.If = bt.If(self.data > self.sma5, 1000, 5000) # bt.All,同 bt.And self.All = bt.All(self.data > self.sma5, self.data > self.sma10, self.sma5 > self.sma10) # bt.Any,同 bt.Or self.Any = bt.Any(self.data > self.sma5, self.data > self.sma10, self.sma5 > self.sma10) # bt.Max,返回同一时刻所有指标中的最大值 self.Max = bt.Max(self.data, self.sma10, self.sma5) # bt.Min,返回同一时刻所有指标中的最小值 self.Min = bt.Min(self.data, self.sma10, self.sma5) # bt.Sum,对同一时刻所有指标进行求和 self.Sum = bt.Sum(self.data, self.sma10, self.sma5) # bt.Cmp(a,b), 如果 a>b ,返回 1;否则返回 -1 self.Cmp = bt.Cmp(self.data, self.sma5)
def __init__(self): self.fastma = dict() self.slowma = dict() self.regime = dict() #self._addobserver(True, bt.observers.BuySell) # CAUTION: Abuse of the method, I will change this in future code (see: https://community.backtrader.com/topic/473/plotting-just-the-account-s-value/4) #optimization if self.params.optim: self.params.fast, self.params.slow = self.params.optim_fs # fast and slow replaced by tuple's contents for d in self.getdatanames(): # The moving averages self.fastma[d] = btind.SimpleMovingAverage( self.getdatabyname(d), # The symbol for the moving average period=self.params.fast, # Fast moving average plotname="FastMA: " + d) self.slowma[d] = btind.SimpleMovingAverage( self.getdatabyname(d), # The symbol for the moving average period=self.params.slow, # Slow moving average plotname="SlowMA: " + d) # Get the regime self.regime[d] = self.fastma[d] - self.slowma[ d] # Positive when bullish
def set_datalines(self): self.data.features = [ btind.SimpleMovingAverage(self.datas[0], period=period) for period in self.features_parameters ] self.data.dim_sma = btind.SimpleMovingAverage( self.datas[0], period=(np.asarray(self.features_parameters).max() + self.time_dim) ) self.data.dim_sma.plotinfo.plot = False
def __init__(self): # 12 hour sma self.sma_12hr = btind.SimpleMovingAverage(period=self.p.pfast) # 30 day sma self.sma_30day = btind.SimpleMovingAverage(period=self.p.pslow) self.gsma = btind.CrossOver(self.sma_12hr, self.sma_30day) # used to determine if order has executed self.order = None # self.signal_add(bt.SIGNAL_LONG, bt.ind.CrossOver(sma_12hr, sma_30day)) self.dataclose = self.datas[0].close
def set_datalines(self): self.data.sma_16 = btind.SimpleMovingAverage(self.datas[0], period=16) self.data.sma_32 = btind.SimpleMovingAverage(self.datas[0], period=32) self.data.sma_64 = btind.SimpleMovingAverage(self.datas[0], period=64) self.data.sma_128 = btind.SimpleMovingAverage(self.datas[0], period=128) self.data.dim_sma = btind.SimpleMovingAverage(self.datas[0], period=(128 + self.time_dim)) self.data.dim_sma.plotinfo.plot = False
def __init__(self): # To control operation entries self.orderid = None self.set_tradehistory(True) # Indicators poc = SimpleMovingAverage1(self.data0.POC, period=1, plotname='POC', subplot=False) ppoc = SimpleMovingAverage1(self.data0.PPOC, period=1, plotname='PPOC', subplot=False) poc3w = SimpleMovingAverage1(self.data0.POC3w, period=1, plotname='POC3w', subplot=False) pocw = SimpleMovingAverage1(self.data0.POCw, period=1, plotname='POCw', subplot=False) sma80 = btind.SimpleMovingAverage(self.data1.close, period=80, plotname='SMA80') sma240 = btind.SimpleMovingAverage(self.data1.close, period=240, plotname='SMA240') self.atr = bt.talib.ATR(self.data0.high, self.data0.low, self.data0.close, timeperiod=14) self.rsi = btind.RSI_EMA(self.data1.close, period=14) self.macd = btind.MACDHistogram(self.data1.close) #self.ematr = btind.ExponentialMovingAverage(self.atr, period=89) self.signal1 = btind.CrossOver(self.data0.close, poc, plot=False) self.signal2 = btind.CrossOver(self.data0.close, ppoc, plot=False) self.sma80_slope = Slope(sma80, period=self.p.pslope, plot=False) self.sma240_slope = Slope(sma240, period=self.p.pslope, plot=False) self.macd_slope = Slope(self.macd, period=self.p.pslope, plot=False) self.rsi_slope = Slope(self.rsi, period=self.p.pslope, plot=False) self.diffPOC = (self.data0.POC - self.data0.PPOC) self.diffPOC3w = (self.data0.POC - self.data0.POC3w) self.diffPOCw = (self.data0.POC - self.data0.POCw) self.diffClPOC = (self.data0.close - self.data0.POC) #self.diffClPPOC = (self.data0.close - self.data0.PPOC) self.diffClPOC3w = (self.data0.close - self.data0.POC3w) self.diffClPPOC3w = (self.data0.close - self.data0.PPOC3w) self.diffClPOCw = (self.data0.close - self.data0.POCw) self.diffClPPOCw = (self.data0.close - self.data0.PPOCw) self.diffSMA = (sma80 - sma240) self.flag = True self.counter = 0 self.nlost = 0
def __init__(self): # Keep a reference to the "close" line in the data[0] dataseries self.dataclose = self.datas[0].close # To keep track of pending orders and buy price/commission self.order = None self.buyprice = None self.buycomm = None # Add a MovingAverageSimple indicator self.sma10 = btind.SimpleMovingAverage(self.datas[0], period=self.p.pfast) self.sma20 = btind.SimpleMovingAverage(self.datas[0], period=self.p.pslow) self.crossover = btind.CrossOver(self.sma10, self.sma20) # crossover signal
def set_datalines(self): self.data.spread = btind.SimpleMovingAverage(self.datas[0] - self.datas[1], period=1) self.data.spread.plotinfo.subplot = True self.data.spread.plotinfo.plotabove = True self.data.spread.plotinfo.plotname = list(self.p.asset_names)[0] initial_time_period = self.p.time_dim self.data.dim_sma = btind.SimpleMovingAverage( self.datas[0], period=initial_time_period) self.data.dim_sma.plotinfo.plot = False
def __init__(self): """Initialize the strategy""" self.fastma = dict() self.slowma = dict() self.regime = dict() self.date_combos = [c for c in zip(self.p.start_dates, self.p.end_dates)] # Error checking if type(self.p.start_dates) is not list or type(self.p.end_dates) is not list or \ type(self.p.fast) is not list or type(self.p.slow) is not list: raise ValueError("Must past lists filled with numbers to params start_dates, end_dates, fast, slow.") elif len(self.p.start_dates) != len(self.p.end_dates) or \ len(self.p.fast) != len(self.p.start_dates) or len(self.p.slow) != len(self.p.start_dates): raise ValueError("All lists passed to params must have same length.") for d in self.getdatanames(): self.fastma[d] = dict() self.slowma[d] = dict() self.regime[d] = dict() # Additional indexing, allowing for differing start/end dates for sd, ed, f, s in zip(self.p.start_dates, self.p.end_dates, self.p.fast, self.p.slow): # More error checking if type(f) is not int or type(s) is not int: raise ValueError("Must include only integers in fast, slow.") elif f > s: raise ValueError("Elements in fast cannot exceed elements in slow.") elif f <= 0 or s <= 0: raise ValueError("Moving average windows must be positive.") if type(sd) is not dt.date or type(ed) is not dt.date: raise ValueError("Only datetime dates allowed in start_dates, end_dates.") elif ed - sd < dt.timedelta(0): raise ValueError("Start dates must always be before end dates.") # The moving averages # Notice that different moving averages are obtained for different combinations of # start/end dates self.fastma[d][(sd, ed)] = btind.SimpleMovingAverage(self.getdatabyname(d), period=f, plot=False) self.slowma[d][(sd, ed)] = btind.SimpleMovingAverage(self.getdatabyname(d), period=s, plot=False) # Get the regime self.regime[d][(sd, ed)] = self.fastma[d][(sd, ed)] - self.slowma[d][(sd, ed)]
def set_datalines(self): self.data.high = self.data.low = self.data.close = self.data.open self.data.std = btind.StdDev(self.data.open, period=self.p.time_dim, safepow=True) self.data.std.plotinfo.plot = False self.data.features = [ btind.SimpleMovingAverage(self.data.open, period=period) for period in self.p.features_parameters ] initial_time_period = np.asarray(self.p.features_parameters).max() + self.p.time_dim self.data.dim_sma = btind.SimpleMovingAverage( self.datas[0], period=initial_time_period ) self.data.dim_sma.plotinfo.plot = False
def set_datalines(self): # Override stat line: self.stat_asset = self.data.spread = SpreadConstructor() # Spy on reward behaviour: self.reward_tracker = CumSumReward() self.data.std1 = btind.StdDev(self.datas[0], period=self.p.time_dim, safepow=True) self.data.std1.plotinfo.plot = False self.data.std2 = btind.StdDev(self.datas[1], period=self.p.time_dim, safepow=True) self.data.std2.plotinfo.plot = False self.data.features1 = [ btind.EMA(self.datas[0], period=period) for period in self.p.features_parameters ] self.data.features2 = [ btind.EMA(self.datas[1], period=period) for period in self.p.features_parameters ] initial_time_period = np.asarray( self.p.features_parameters).max() + self.p.time_dim self.data.dim_sma = btind.SimpleMovingAverage( self.datas[0], period=initial_time_period) self.data.dim_sma.plotinfo.plot = False
def set_datalines(self): initial_time_period = self.p.time_dim self.data.dim_sma = btind.SimpleMovingAverage( self.datas[0], period=initial_time_period ) self.data.dim_sma.plotinfo.plot = False
def set_datalines(self): features_low = [ MinPool(self.data, period=period) for period in self.features_parameters ] features_high = [ MaxPool(self.data, period=period) for period in self.features_parameters ] # If `scale` was scalar - make it vector: if len(np.asarray(self.p.state_ext_scale).shape) < 1: self.p.state_ext_scale = np.repeat( np.asarray(self.p.state_ext_scale), self.num_features) # Sort features by `period` for .get_external_state() to estimate # more or less sensible gradient; double-stretch scale vector accordingly: # TODO: maybe 2 separate conv. encoders for hi/low? self.data.features = [] for f1, f2 in zip(features_low, features_high): self.data.features += [f1, f2] self.p.state_ext_scale = np.repeat(self.p.state_ext_scale, 2) # print('p.state_ext_scale: ', self.p.state_ext_scale, self.p.state_ext_scale.shape) self.data.dim_sma = btind.SimpleMovingAverage( self.datas[0], period=(np.asarray(self.features_parameters).max() + self.time_dim)) self.data.dim_sma.plotinfo.plot = False
def __init__(self): self.rsi = btind.RSI(period=self.params.period) # self.macd = btind.MACD() # self.macd = btind.EMA(9) - btind.EMA(14) # self.signal = btind.EMA(14) self.sma = btind.SimpleMovingAverage(period=21) self.ema = btind.ExponentialMovingAverage(period=14) self.accDe = btind.AccDeOsc(period=14) self.close_over_sma = self.data.close > self.sma self.close_over_ema = self.data.close > self.ema self.sma_ema_diff = self.sma - self.ema self.buy_sig = bt.And(self.close_over_sma, self.close_over_ema, self.sma_ema_diff > 0) self.max_pos = 10 self.overSold = self.rsi < 50 self.overBought = self.rsi > 70 self.oscSig = self.accDe > 0 self.buy_price = [] self.sell_price = [] self.buy_price = [] self.sell_price = [] self.ave_buy = 0 self.ave_sell = 0
def __init__(self): """初始化一些参数 self.datas 用来存储feed进来的数据 SimpleMovingAverage 方法应该会生成一条叫做sma的lines """ # sma = btind.SimpleMovingAverage(self.data, period=self.params.period) self.movav = btind.SimpleMovingAverage(self.data, period=self.p.period) pass
def set_datalines(self): # Here spread is for plotting and norm. tracking: self.data.spread = btind.SimpleMovingAverage(self.datas[0] - self.datas[1], period=1) self.data.spread.plotinfo.subplot = True self.data.spread.plotinfo.plotabove = True self.data.spread.plotinfo.plotname = list(self.p.asset_names)[0] # Override stat line: self.stat_asset = self.data.spread initial_time_period = self.p.time_dim self.data.dim_sma = btind.SimpleMovingAverage( self.datas[0], period=initial_time_period ) self.data.dim_sma.plotinfo.plot = False
def __init__(self): sma1 = btind.SimpleMovingAverage(self.data) ema1 = btind.ExponentialMovingAverage() close_over_sma = self.data.close > sma1 close_over_ema = self.data.close > ema1 sma_ema_diff = sma1 - ema1 buy_sig = bt.And(close_over_sma, close_over_ema, sma_ema_diff > 0)
def __init__(self): self.sma1 = btind.SimpleMovingAverage(self.data) self.ema1 = btind.ExponentialMovingAverage() self.close_over_sma = self.data.close > self.sma1 self.close_over_ema = self.data.close > self.ema1 self.sma_ema_diff = self.sma1 - self.ema1 # 生成交易信号 self.buy_sig = bt.And(self.close_over_sma, self.close_over_ema, self.sma_ema_diff > 0)
def set_datalines(self): self.data_streams = {stream._name: stream for stream in self.datas} # self.data = self.data_streams[self.p.base_dataline] # TODO: ??!! self.data.dim_sma = btind.SimpleMovingAverage( self.data, period=(np.asarray(self.features_parameters).max() + self.time_dim)) self.data.dim_sma.plotinfo.plot = False
def __init__(self): self.order = None self.previous_action: StateToRemember = None # read from params self.environment = self.params.environment self.agent = self.environment.agent self.sma = btind.SimpleMovingAverage(self.datas[0], period=self.environment.window + 2) # meh
def __init__(self): # 指标函数也支持简写 SimpleMovingAverage → SMA # 最简方式:直接省略指向的数据集 self.sma1 = btind.SimpleMovingAverage(period=5) # 只指定第一个数据表格 self.sma2 = btind.SMA(self.data, period=5) # 指定第一个数据表格的 close 线 self.sma3 = btind.SMA(self.data.close, period=5) # 完整写法 self.sma4 = btind.SMA(self.datas[0].lines[0], period=5)
def __init__(self): sma1 = btind.SimpleMovingAverage(self.datas[0], period=self.p.period1) # This 2nd Moving Average operates using sma1 as "data" sma2 = btind.SimpleMovingAverage(sma1, period=self.p.period2) # New data created via arithmetic operation something = sma2 - sma1 + self.data.close # This 3rd Moving Average operates using something as "data" sma3 = btind.SimpleMovingAverage(something, period=self.p.period3) # Comparison operators work too ... greater = sma3 > sma1 # Pointless Moving Average of True/False values but valid # This 4th Moving Average operates using greater as "data" sma3 = btind.SimpleMovingAverage(greater, period=self.p.period4)
def __init__(self): # To control operation entries self.orderid = None # Indicators poc = btind.SimpleMovingAverage(self.data0.POC, period=1, plotname='POC') ppoc = btind.SimpleMovingAverage(self.data0.PPOC, period=1, plotname='PPOC') self.atr = bt.talib.ATR(self.data0.high, self.data0.low, self.data0.close, period=14) self.ematr = btind.ExponentialMovingAverage(self.atr, period=89) self.dataclose = self.data0.close self.anchor = 3.0 self.expand = 1.0 self.signal1 = btind.CrossOver(self.dataclose, poc, plotname='POC') self.signal2 = btind.CrossOver(self.dataclose, ppoc, plotname='PPOC') #self.trailing = True self.flag = True
def __init__(self): print('init strategy') self.dataclose = dict() self.sma_fast = dict() self.sma_slow = dict() self.longsignal = dict() self.shortsignal = dict() for symbol in self.getdatanames(): self.dataclose[symbol] = self.datas[0].close self.sma_fast[symbol] = btind.SimpleMovingAverage( self.getdatabyname(symbol), period=self.p.fast, plotname="FastMA: " + symbol) self.sma_slow[symbol] = btind.SimpleMovingAverage( self.getdatabyname(symbol), period=self.p.slow, plotname="SlowMA: " + symbol) self.longsignal[symbol] = btind.CrossOver(self.sma_fast[symbol], self.sma_slow[symbol]) self.shortsignal[symbol] = btind.CrossOver(self.sma_slow[symbol], self.sma_fast[symbol])
def set_datalines(self): # Discard superclass dataline, use SpreadConstructor instead: self.data.spread = None # Override stat line: self.stat_asset = self.SpreadConstructor() # Spy on reward behaviour: self.reward_tracker = self.CumSumReward() initial_time_period = self.p.time_dim self.data.dim_sma = btind.SimpleMovingAverage( self.datas[0], period=initial_time_period) self.data.dim_sma.plotinfo.plot = False