[Quantitative backtest must-see! 】Backtrader nanny-level teaching + free market source SMA strategy

foreword

Want to start quantitative learning but don't know how to get started? There are too many learning materials on the market and don’t know what to read?
The blogger will explain the backtesting framework from the basics, and complete the construction of quantitative data sources step by step, allowing you to become a quantitative master within 10 days. The blogger will
also update the content of the video course on station B. You can follow "Quantitative NPC" to get the latest video courses
. To know how to install backtrader and configure it, you can click: Backtrader nanny -level teaching +
free market source framework introduction Appendix section at the end of the article.


Introduction to SMA strategy

insert image description here

Access the market source

This article uses the INSIGHT market source, which provides free TICK data, minute K, day K, and various financial information data.
If you are interested in INSIGHT, you can visit: INSIGHT digital documents.
If you want to see the comparison of various data sources, you can see : Comparative analysis of the strongest quantitative free market sources

writing strategy

Define the init method in the strategy

  1. Refer to the default indicator.MovingAverageSimple() in bt
  2. Call indicator.crossover, the meaning of crossover is to judge whether the closing price has crossed with bt_sma, if it is 1, it is an upward crossover, 0 means there is no crossover, and -1 is a downward crossover. buy_or_sell is a time series, similar to the sequence of [0,0,0,0,0,1,0,0,0,-1,1...]
  def __init__(self):
        self.bt_sma = bt.indicators.MovingAverageSimple(self.data, period=3)
        self.buy_or_sell = bt.indicators.CrossOver(self.data, self.bt_sma)
import backtrader as bt
import pandas as pd

from com.insight import common
from com.insight.query import *
from com.insight.market_service import market_service
from datetime import datetime

# user 用户名
# password 密码
def login():
    # 登陆前 初始化
    user = "填写自己的账户"
    password = "填写自己的密码"
    common.login(market_service, user, password)


class Mystrategy(bt.Strategy):
    def __init__(self):
        self.bt_sma = bt.indicators.MovingAverageSimple(self.data, period=3)
        self.buy_or_sell = bt.indicators.CrossOver(self.data, self.bt_sma)


    def start(self):
        print("start")

    def prenext(self):
        print("prenext")

    def next(self):
        print("next")

        # 方法一
        # ma_value = sum(self.data.close[-date] for date in range(3))/3
        # pre_ma_value = sum(self.data.close[-date-1] for date in range(3))/3
        # 方法二
        # ma_value = self.bt_sma[0]
        # pre_ma_value = self.bt_sma[-1]

        # if self.data.close[0] > ma_value and self.data.close[-1] < pre_ma_value:
        #     self.order = self.buy()
        # if self.data.close[0] < ma_value and self.data.close[-1] > pre_ma_value:
        #     self.order = self.sell()

        # if self.buy_or_sell[0] == 1:
        #     self.order = self.buy()
        # elif self.buy_or_sell[0] == -1:
        #     self.order = self.sell()
        if self.getposition().size >= 0 and self.buy_or_sell[0] == 1:
            self.order = self.buy()
        if self.getposition().size <= 0 and self.buy_or_sell[0] == -1:
            self.order = self.sell()
        if self.getposition().size > 0 and self.buy_or_sell[0] == -1:
            self.order = self.close()
            self.order = self.sell()
        if self.getposition().size < 0 and self.buy_or_sell[0] == 1:
            self.order = self.close()
            self.order = self.buy()



if __name__ == '__main__':
    #方法一
    login()
    df = get_kline(htsc_code=["601688.SH"], time=[datetime(2021, 5, 10), datetime(2022, 5, 10)],
                       frequency="daily", fq="none")
    # csv = df.to_csv("daily-kline.csv")
    #方法二
    # df = pd.read_csv("daily-kline.csv")
    # df["time"] = pd.to_datetime(df["time"])

    data = bt.feeds.PandasData(
        dataname=df,
        fromdate=datetime(2021, 5, 10),
        todate=datetime(2022, 5, 10),
        datetime='time',
        # open='open',
        # high='high',
        # low='low',
        # close='close',
        # volume='volume',
        openinterest=-1
    )
    cerebro = bt.Cerebro()
    cerebro.adddata(data, name="daily_kline")
    cerebro.addstrategy(Mystrategy)
    result = cerebro.run()

    cerebro.plot()

Guess you like

Origin blog.csdn.net/weixin_38132951/article/details/129289308