For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

Initializing a volatility indicator with a 30 bar period



  • Hi all -

    I am trying to develop an indicator to measure market volatility. I am implementing a formula already in python (https://github.com/jasonstrimpel/volatility-trading/blob/master/volatility/models/YangZhang.py), but am converting this to a custom indicator in backtrader.

    I have tried to read the documentation on: https://www.backtrader.com/docu/inddev/, but it has not clicked.

    Could someone recommend how to initialize the indicator using the 'window' param for the number of minimum periods for the indicator? In the below code, this uses an implementation of rolling().sum() but this code is not in line with the indicator development methodology supported by backtrader.

        class YangZhangEstimator(Indicator):
    '''
    
    '''
    alias = ('YZE',)
    
    lines = ('yze',)
    params = (('window', 30), 
    		  ('trading_periods', 100))
    '''
    def _plotlabel(self):
    	plabels = [self.p.period]
    	plabels += [self.p.movav] * self.p.notdefault('movav')
    	return plabels
    '''
    def __init__(self):
    	log_ho = (self.data.high / self.data.open).apply(np.log)
    
    	log_lo = (self.data.low / self.data.open).apply(np.log)
    
    	log_co = (self.data.close / self.data.open).apply(np.log)
    
    	log_oc = (self.data.open / self.data.close[-1]).apply(np.log)
    
    	log_oc_sq = log_oc**2	 
    
    	log_oc = (self.data.close / self.data.close[-1]).apply(np.log)
    
    	log_cc_sq = log_oc**2
    	
    	rs = log_ho * (log_ho - log_co) + log_lo * (log_lo - log_co)
    	
    	close_vol = log_cc_sq.rolling(window=self.p.window).sum() * (1.0 / (self.p.window - 1.0))
    
    	open_vol = log_oc_sq.rolling(window=self.p.window).sum() * (1.0 / (self.p.window - 1.0))
    	
    	window_rs = rs.rolling(window=self.p.window).sum() * (1.0 / (self.p.window - 1.0))
    
    	k = 0.34 / (1 + (self.p.window + 1) / (self.p.window - 1))
    	
    	self.lines.yze = (open_vol + k * close_vol + (1 - k) * window_rs).apply(np.sqrt) * math.sqrt(self.p.trading_periods)
    
    	super(YangZhangEstimator, self).__init__()

Log in to reply
 

});