打造属于自己的量化投资系统1——backtrader框架简介

一、核心组件

(1)数据加载(Data Feed):将交易策略的数据加载到回测框架中。
(2)交易策略(Strategy) strategy.py:该模块是编程过程中最复杂的部分,需要设计交易决策,得出买入/卖出信号。
(3)回测框架设置( Cerebro)cerebro.py:需要设置(i)初始资金(ii)佣金(iii)数据馈送(iv)交易策略(v)交易头寸大小。
(4)运行回测:运行Cerebro回测并打印出所有已执行的交易。
(5)评估性能(Analyzers):以图形和风险收益等指标对交易策略的回测结果进行评价。

在这里插入图片描述

二、策略的生命周期
1.Conception: init

任何类在生成的时候都是先调用这一初始化构造函数
This is obviously invoked during instantiation: indicators will be created here and other needed attribute. Example:

def __init__(self):
    self.sma = btind.SimpleMovingAverage(period=15)
2.Birth: start

start方法在cerebro告诉strategy,是时候开始行动了,也就是说,通知策略激活的时候被调用。
The world (cerebro) tells the strategy is time to start kicking. A default empty method exists.

3.Childhood: prenext

有些技术指标,比如我们提到的MA,存在一个窗口,也就是说,需要n天的数据才能产生指标,那么在没有产生之前呢?这个prenext方法就会被自动调用。
indicators declared during conception will have put constraints on how long the strategy needs to mature: this is called the minimum period. Above init created a SimpleMovingAverage with a period=15.As long as the system has seen less than 15 bars, prenext will be called (the default implementation is a no-op)

4.Adulthood: next

这个方法是最核心的,就是每次移动到下一的时间点,策略将会调用这个方法,所以,策略的核心往往都是写在这个方法里的。
Once the system has seen 15 bars and the SimpleMovingAverage has a buffer large enough to start producing values, the strategy is mature enough to really execute.
There is a nextstart method which is called exactly once, to mark the switch from prenext to next. The default implementation of nextstart is to simply call next

5.Reproduction: None

Ok, strategies do not really reproduce. But in a sense they do, because the system will instantiate them several times if optimizing (with different parameters)

6.Death: stop

策略的生命周期结束,cerebro把这一策略退出。
The system tells the strategy the time to come to a reset and put things in order has come. A default empty method exists.

三、框架使用流程
1.Start by creating a cerebro:(创建cerebro)

cerebro = bt.Cerebro(**kwargs)

2.Add Data feeds(增加数据)

cerebro.adddata(data)

3.Add Strategies(增加策略)

.addstrategy(MyStrategy, myparam1=value1, myparam2=value2)

4.Other elements(其他元素)

addwriter
addanalyzer
addobserver (or addobservermulti)

5.Changing the broker(改变broker)

cerebro.broker = broker

6.Receive notifications(接收通知)

Cerebro.notify_store

7.Run cerebro(运行cerebro)

result = cerebro.run(**kwargs)

8.Create plot(创建图表)

cerebro.plot()

四、框架案例

# -*- coding: utf-8 -*-
"""
Created on Wed May 13 14:37:09 2020

@author: 觉醒2020
"""

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import datetime
import backtrader as bt # 引入backtrader框架

#框架使用流程
#1.创建cerebro
#cerebro = bt.Cerebro(**kwargs)
#2.增加数据
#cerebro.adddata(data)
#3.增加策略
#cerebro.addstrategy(MyStrategy, myparam1=value1, myparam2=value2)
#4.增加其他元素
#例如增加观察者addobserver (or addobservermulti)
#5.改变broker
#cerebro.broker = broker
#6.接收通知
#Cerebro.notify_store
#运行cerebro
#result = cerebro.run(**kwargs)
#创建图表
#cerebro.plot()



#平安银行股票数据为例子


class StrategyClass(bt.Strategy):
    #'股票策略
    def __init__(self):
        pass
    def next(self):
        pass

cerebro=bt.Cerebro()
datapath=".\\datas\\test\\000001.XSHE"
data=bt.feeds.GenericCSVData(dataname=datapath,
                             fromdate = datetime.datetime(2018, 1, 1),
                             todate = datetime.datetime(2020, 3, 20),
                             nullvalue=0.0,
                             dtformat=('%Y-%m-%d'),
                             datetime=0,
                             high=3,
                             low=4,
                             open=1,
                             close=2,
                             volume=5,
                             openinterest=-1)
cerebro.adddata(data)

cerebro.addstrategy(StrategyClass)
#设置金额,默认是100000
cerebro.broker.set_cash(200000)
cerebro.run(maxcpu=1)
cerebro.plot()


运行结果:
在这里插入图片描述

【觉醒2020】提醒你,请继续关注,后续将详细介绍每一个知识点的内容。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值