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

mean reversion half life



  • Dear fellow backtraders,
    Thank you guys for contributions to the community. I'm new to Python & backorder, and have a difficulty to code a half life analyzer/screener.

    Below is my python code, that works well,

    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    import numpy as np
    import statsmodels.api as sm
    from pandas import read_csv
    import pandas as pd
    import math
    
    import datetime
    from pandas import read_csv
    from matplotlib import pyplot
    
    
    from pandas import read_csv
    from matplotlib import pyplot
    
    #use pandas read_csv to read stock file
    TimeSeries = read_csv('data/TSLA.CSV', header=0, parse_dates=[0], index_col=0)
    
    #make sure the data are in pandas DataFram format
    TimeSeries = pd.DataFrame(TimeSeries)
    
    
    
    #set start and end date
    start = datetime.date(2019, 1, 3)
    end = datetime.date(2020, 4, 30)
    TimeSeries=TimeSeries.loc(axis=0)[start:end]
    
    #select Adj close price
    data=TimeSeries['Adj Close']
    
    
    
    #set up lagged series of TimeSeries
    
    lag = np.roll(data, 1)
    lag[0] = 0
    ret = data - lag
    ret[0] = 0
    
    # adds intercept terms to X variable for regression
    lag2 = sm.add_constant(lag)
    
    model = sm.OLS(ret, lag2)
    res = model.fit()
    
    #Calculate and print Half life
    half_life = -np.log(2) / res.params[1]
    
    print(half_life)
    
    
    
    
    #pyplot.plot(TimeSeries['Adj Close'])
    #pyplot.show()
    
    

    Here is my backtrader analyzer/screener, that sucks. Could you please help?

    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    import datetime
    import backtrader as bt
    import numpy as np
    import statsmodels.api as sm
    
    
    class Half_Life(bt.Analyzer):
        """
        Half Life test from the Ornstein-Uhlenbeck process 
        Source: http://www.pythonforfinance.net/2016/05/09/python-backtesting-mean-reversion-part-2/
        """
     
        def start (self):
           pass
           
     
        def stop (self):
            lag = np.roll(self.data.close, 1)
            lag[0] = 0
            ret = self.data.close - lag
            ret[0] = 0
     
            # adds intercept terms to X variable for regression
            lag2 = sm.add_constant(lag)
     
            model = sm.OLS(ret, lag2)
            res = model.fit()
     
            self.half_life = -np.log(2) / res.params[1]
     
            
    
    
    #Instantiate Cerebro engine
    cerebro = bt.Cerebro()
    
    #Set data parameters and add to Cerebro
    data = bt.feeds.GenericCSVData(
        dataname='data/TSLA.csv',
        nullvalue=0.0,
        dtformat=('%Y-%m-%d'),
        datetime=0,
        time=-1,
        high=2,
        low=3,
        open=1,
        close=4,
        volume=5,
        openinterest=-1,
        timeframe=bt.TimeFrame.Days,
        fromdate=datetime.datetime(2010, 1, 1),
        todate=datetime.datetime(2011, 1, 1),
    )
    
    cerebro.adddata(data) 
    #Add analyzer for screener
    cerebro.addanalyzer(Half_Life)
    if __name__ == '__main__':
    #Run Cerebro Engine
        cerebro.run(runonce=False, stdstats=False, writer=True)
     
    
    


  • https://www.backtrader.com/docu - read about bt data feds, lines concept etc. Try quickstart.


Log in to reply
 

});