Feed list of candles as variable to backtrader

100 views Asked by At

I hаvе list of Candle objeсts and want to feed them straight to сerebro without saving to csv and loading from csv, but can't figure out how to do it.

from datetime import datetime, timedelta
from dataclasses import dataclass

import backtrader as bt


@dataclass(frozen=True)
class Candle:
    open: float
    high: float
    low: float
    close: float
    volume: int
    time: datetime
    is_complete: bool | None = None


class TestStrategy(bt.Strategy):
    def __init__(self):
        self.dataclose = self.datas[0].close

    def next(self):
        print(self.dataclose[0])


def main():
    cerebro = bt.Cerebro()
    cerebro.broker.set_cash(100_000)
    cerebro.broker.setcommission(0.03)
    
    candles = [Candle(open=i, high=i+2, low=i-2, close=i, volume=i*100, time=datetime.utcnow()) for i in range(1, 101)]
    data = bt.DataBase(candles)
    cerebro.adddata(data)
    cerebro.addstrategy(TestStrategy)

    print(f'Starting Portfolio Value: {cerebro.broker.get_value()}')
    cerebro.run()
    print(f'Final Portfolio Value: {cerebro.broker.get_value()}')


if __name__ == '__main__':
    main()

output without any price print:

Starting Portfolio Value: 100000 

Final Portfolio Value: 100000`

I saw something about extending data feed, but didn't understand how to manage it for my case. Tried init LineSeries, but got error while adding data. Is it possible to feed data from variable to backtrader module?

0

There are 0 answers