Large-scale optimization of backtrader strategy parameters--using particle swarms and other intelligent algorithms

The strategy parameter optimization method built in backtrader is the right search method, which is to traverse each parameter combination value. When there are many parameters and the value of each parameter varies widely, the optimization efficiency is very low.

Intelligent optimization algorithms, such as particle swarm optimization, can be used for large-scale parameter optimization. Next, we use the python open source algorithm library optunity to optimize the backtrader strategy parameters.

Our example strategy is a simple double moving average strategy. Two parameters and two moving average moving windows need to be optimized. The goal is to maximize the market value of the account. Use the particle swarm algorithm in optunity to optimize, the code is as follows:

# example of optimizing SMA crossover strategy parameters using 
# Particle Swarm Optimization in the opptunity python library
# https://github.com/claesenm/optunity

from datetime import datetime
import backtrader as bt

import optunity
import optunity.metrics


class SmaCross(bt.SignalStrategy):
    params = (
        ('sma1', 10), # 需要优化的参数1,短期均线窗口
        ('sma2', 30), # 需要优化的参数2,长期均线窗口
    )
    def __init__(self):
        SMA1 = bt.ind.SMA(period=int(self.params.sma1)) # 用int取整
        SMA2 = bt.ind.SMA(period=int(self.params.sma2)) # 用int取整
        crossover = bt.ind.CrossOver(SMA1, SMA2)
        self.signal_add(bt.SIGNAL_LONG, crossover)


data0 = bt.feeds.YahooFinanceData(dataname='YHOO',
                                  fromdate=datetime(2011, 1, 1),
                                  todate=datetime(2012, 12, 31))

def runstrat(sma1,sma2):
    
    cerebro = bt.Cerebro()
    cerebro.addstrategy(SmaCross, sma1=sma1, sma2=sma2)

    cerebro.adddata(data0)
    cerebro.run()
    return cerebro.broker.getvalue()

#  执行优化,执行100次回测(num_evals),设置两个参数的取值范围
opt = optunity.maximize(runstrat,  num_evals=100,solver_name='particle swarm', sma1=[2, 55], sma2=[2, 55])

optimal_pars, details, _ = opt
print('Optimal Parameters:')
print('sma1 = %.2f' % optimal_pars['sma1'])
print('sma2 = %.2f' % optimal_pars['sma2'])

cerebro = bt.Cerebro()
cerebro.addstrategy(SmaCross, sma1=optimal_pars['sma1'], sma2=optimal_pars['sma2'])
cerebro.adddata(data0)
cerebro.run()
cerebro.plot()

Optunity supports the following algorithms (solvers), and readers can test them separately.

particle swarm,sobol,random search,cma-es,grid search

For more information, please refer to our backtrader tutorial
or video tutorial

Guess you like

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