The combination of backtrader and machine learning is that simple!

Click here to download the tutorial

Machine learning is too popular. Nowadays, quantitative investment does not mention machine learning. Artificial intelligence is too low. As for the effect, hehehe.

So is it complicated to introduce machine learning in quantitative backtesting? In fact, there are complex and simple. Today I will introduce you a way of combining machine learning with backtrader.

For example, I want to test whether a certain machine learning algorithm can be used to trade stock price predictions in order to obtain profits. The routine may be like this, we use a hypothetical case to illustrate.

(1) I used the machine learning algorithm "Support Vector Machine SVM" to train a model, which can use the daily return rate of the stock in the past n days to predict that the stock will rise (state 1), flat (state 0), or fall (state 1). -1) Which state. Then, I put the prediction results in the market data table, as follows, the last column of predict is the result of machine learning prediction. (If you are interested in this step, please refer to here )

(2) Based on the above table, I propose a strategy. If it is predicted that it will rise tomorrow, then buy in the whole position; if it falls, then all the stocks will be thrown out, and if it is flat, then it will not move. A sample of our machine learning strategy class is as follows:

class MLStrategy(bt.Strategy):
    params = dict(
    )

    def __init__(self):
        # 跟踪股票open, close价和predicted值
        self.data_predicted = self.datas[0].predicted  # 这就是机器学习算法的预测值
        self.data_open = self.datas[0].open
        self.data_close = self.datas[0].close

        # 跟踪未决订单/buy price/buy commission
        self.order = None
        self.price = None
        self.comm = None
    # logging function

    def log(self, txt):
        '''Logging function'''
        dt = self.datas[0].datetime.date(0).isoformat()
        print(f'{dt}, {txt}')

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # order already submitted/accepted - no action required
            return
        # report executed order
        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(f'BUY EXECUTED - -- Price: {order.executed.price: .2f},
                         Cost: {order.executed.value: .2f}, Commission: {order.executed.comm: .2f}')
                self.price = order.executed.price
                self.comm = order.executed.comm
            else:
                self.log(f'SELL EXECUTED - -- Price: {order.executed.price: .2f},
                         Cost: {order.executed.value: .2f}, Commission: {order.executed.comm: .2f}')
        # 报告失败订单
        elif order.status in [order.Canceled, order.Margin,
                              order.Rejected]:
            self.log('Order Failed')
        # 现在没有未决订单了
        self.order = None

    def notify_trade(self, trade):
        if not trade.isclosed:
            return
        self.log(
            f'OPERATION RESULT --- Gross: {trade.pnl:.2f}, Net: {trade.pnlcomm:.2f}')

    def next(self):
        # 如果有未决订单,则无动作,不再生成新订单
        if self.order:
            return
        
        if not self.position:
            if self.data_predicted > 0:  # 如果预测明天会涨,就买
                # 全仓买入 ('all-in')
                size = int(self.broker.getcash() / self.datas[0].open)
                # buy order
                self.log( f'BUY CREATED --- Size: {size}, Cash: {self.broker.getcash():.2f}, 
                    Open: {self.data_open[0]}, Close: {self.data_close[0]}')
                self.order = self.buy(size=size)
        else:
            if self.data_predicted < 0:  # 如果预测明天会跌,就卖
                # sell order
                self.log(f'SELL CREATED --- Size: {self.position.size}')
                self.order = self.sell(size=self.position.size)

(3) Then, we can back-test the above strategy on the sample data, maybe there are any big discoveries.

In summary, the above process only uses machine learning algorithms for data preprocessing in the first step, and adds a field predicted to the market table. The remaining steps are the typical backtrader backtesting process. Jane is not simple, excited or not? Finally got the machine learning quantitative backtest, and I can talk about it in the next interview, hahaha!

As for how to use backtrader, see this: Why do I need a systematic Backtrader Chinese technical tutorial ,

Guess you like

Origin blog.csdn.net/qtbgo/article/details/110419095