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

Backtest using custom buy/sell signals



  • I'm new to backtrader and have developed a custom strategy in another python script, which returns a dataframe with -1 (sell/short), 0 (do nothing), or 1 (buy), and the date as the index. The dataframe looks like this:

                   signal
    2018-02-13     0.0
    2018-02-14     1.0
    ...
    2018-06-26     0.0
    2018-06-27    -1.0
    

    I want to call this strategy script, get the signal, and price dataframe, and would like to add this as a signal. Something like this:

    import backtrader as bt
    import data_handler as dh  # read custom data
    import my_strategy  as ms  # generate custom signals
    
    stock = 'XYZ'
    df = dh.read_data(stock=stock, sdate='20180101', edate='20180629')
    
    class my_signal(bt.Signal):
    
        def __init__(self):
            self.signal = ms.generate_signals(stock=stock)
    
    
    cerebro = bt.Cerebro()
    
    data = bt.feeds.PandasData(dataname=df)
    cerebro.adddata(data)
    
    cerebro.add_signal(bt.signal.SIGNAL_LONGSHORT, my_signal)
    cerebro.run()
    cerebro.plot()
    

    I'm not quite sure how to actually have my signal dataframe injested properly, and then have trades executed based on that custom signal. Any help would be appreciated. Thanks!


  • administrators

    You can see this for example:

    I am sure there are at least two other threads tackling the topic. But basically:

    • You load your dataframe as another data feed and see if the signal has been generated.

    Or

    • You hold a reference to your dataframe inside an indicator. When the date of the data feed matches one of the dates in the index of the dataframe you read the signal and deliver.

    You may actually automate it all with this: