首页 > 编程语言 >python 利用backtrader 和 akshare 做股票回测

python 利用backtrader 和 akshare 做股票回测

时间:2023-02-01 16:13:08浏览次数:49  
标签:executed backtrader python self %. bt 回测 import order

python 版本设置在 3.8

ImportError: cannot import name 'warnings' from 'matplotlib.dates'

报上面的错 降级 matplotlib
pip uninstall matplotlib
pip install matplotlib==3.2.2
 

以下是源码

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from datetime import datetime
import os.path
import sys
import backtrader as bt
import akshare as ak
from backtrader import feeds
import backtrader.feeds as btfeeds
import pandas as pd

# 创建 一个Stratey
class TestStrategy(bt.Strategy):
    params = (
        ('exitbars',5),
        ('maperiod',65),
        ('printlog', False),
    )
    def log(self,txt,dt=None, doprint=False):
        ''' 打印日志 '''
        if self.params.printlog or doprint:
            dt = dt or self.datas[0].datetime.date(0)
            print('%s, %s' % (dt.isoformat(),txt))
    
    def __init__(self) -> None:
        self.dataclose = self.datas[0].close
        self.order = None
        self.bar_executed=None        
        self.buyprice = None
        self.buycomm = None

        # 添加简单移动平均线
        self.sma = bt.indicators.MovingAverageSimple(self.datas[0],period=self.params.maperiod)
        # Indicators for the plotting show
        bt.indicators.ExponentialMovingAverage(self.datas[0], period=25)
        bt.indicators.WeightedMovingAverage(self.datas[0], period=25,
                                            subplot=True)
        bt.indicators.StochasticSlow(self.datas[0])
        bt.indicators.MACDHisto(self.datas[0])
        rsi = bt.indicators.RSI(self.datas[0])
        bt.indicators.SmoothedMovingAverage(rsi, period=10)
        bt.indicators.ATR(self.datas[0], plot=False)

    def notify_order(self, order):
        # 订单提交 
        if order.status in [order.Submitted,order.Accepted]:
            #print("订单提交 ")
            return
        # 交易成功
        if order.status in [order.Completed]:
            #买进
            if order.isbuy():
                self.log('买进价格: %.2f,数量:%.2f,费用: %.2f' % 
                        (order.executed.price,
                        order.executed.value,
                        order.executed.comm))
                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm        
            #卖出
            else:
                self.log('卖出价格: %.2f,数量:%.2f,费用: %.2f' % 
                        (order.executed.price,
                        order.executed.value,
                        order.executed.comm))
            
            self.bar_executed = len(self)

        #交易失败的类型
        elif order.status in [order.Canceled,order.Margin,order.Rejected]:
            print('交易不成功/订单没有提及/资金不足/股票退市/暂停交易')   
        self.order = None
    def notify_trade(self,trade):
        if not trade.isclosed:
            return 
        self.log('运营利润,毛利:%.2f,净利:%.2f'%
                (trade.pnl,trade.pnlcomm))
    def next(self):
        self.log('Close, %.2f' % self.dataclose[0])
        '''股票连跌3天买买买'''
        if self.order:
            return
        self.log('self len:%s,bar_executed:%s' % (len(self),self.bar_executed))
        #没有持仓,买入    
        if not self.position:
            if self.dataclose[0] >self.sma[0]:
                if self.dataclose[0] <self.dataclose[-1]:
                    self.log('Buy create ,%.2f'% self.dataclose[0])
                    self.order = self.buy()
        else:
            if self.dataclose[0]< self.sma[0]:
                self.log('卖出:%.2f'% self.dataclose[0])

                self.order = self.sell()

    def stop(self):
        self.log('(移动平均 %2d) Ending Value %.2f'%
                (self.params.maperiod,self.broker.getvalue()),doprint=True)
if __name__ == '__main__':
    cerebro = bt.Cerebro()
    cerebro.addstrategy(TestStrategy)
    # 58 65 营利

    # strats = cerebro.optstrategy(
    #     TestStrategy,
    #     maperiod=(58,65))
    
    cerebro.broker.setcash(100000.0)
    # 购买固定的股票数
    cerebro.addsizer(bt.sizers.FixedSize,stake=100)
    cerebro.broker.setcommission(commission=0.001)

    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    df = ak.stock_zh_a_daily(symbol='sz000063',start_date='20201103',end_date='20221103',adjust='hfq')
    df.set_index(df['date'],inplace=True)
    df.drop('date',axis=1,inplace=True)
    df.index = pd.to_datetime(df.index)
#    print(df)
    data = bt.feeds.PandasData(dataname=df,fromdate=datetime(2020,11,3),todate=datetime(2022,11,3))
    
    cerebro.adddata(data)
    cerebro.run(maxcpus=4)
    cerebro.plot(style='bar')
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

 

标签:executed,backtrader,python,self,%.,bt,回测,import,order
From: https://www.cnblogs.com/jackluo/p/17083162.html

相关文章

  • python tcp socket 源码分享
    服务端的源码:importsocketserverclassHandler_TCPServer(socketserver.BaseRequestHandler):"""TheTCPServerclassfordemonstration.Note:We......
  • Python服务进程管理工具supervisor使用记录
    [本文出自天外归云的博客园]学习资料supervisor文档:http://supervisord.org/running.html踩坑总结问题1:提示找不到一些包含/tmp的路径需要修改supervisord.conf配置文......
  • Python操作MongoDB
    虽然经常使用mongodb,但是很多方法都是现用现查,难得有时间,简单整理一下:一、连接mongodb安装第三方库:pipinstallpymongo连接到mongodb服务器:importpymongo#ho......
  • python打包exe
    1、安装[​​pipinstallpyinstaller​​]2、打包成exe文件[​​pyinstallerxxx.py​​]3、测试打包好的exe文件4、打包方式例:​​pyinstaller-Fxxx.py​​//生成单......
  • 使用java python 实现 QI-页面排序-骑马钉
    链接:http://www.cnprint.org/bbs/thread/77/339531/......
  • 五彩斑斓的 Black —— Python 代码格式化工具
      https://muzing.top/posts/a29e4743/#  良好的Python代码应有良好的格式规范(不止于遵守 PEP8 ),使用一个更强大更专业的代码格式化工具,来替代编辑器自带的......
  • Python 中global 关键字理解
    Python中的global关键字,你了解吗?前言今天来了解下Python中的global关键字。Python变量的作用域实战案例演示之前,先要了解下Python的作用域.Python变量的作......
  • python 中给文件加锁——fcntl模块
    如果没有fcntl模块则用sudopipinstallfcntl安装模块简单说明:打开文件,不存在则创建之f=open('./test','w')fcntl.flock(f,fcntl.LOCK_EX)这样就对文件t......
  • python实现区块链代码
    如果你明白了原理其实挺简单的。加密算法是python自带的需要导入hashlibimporthashlibashashsha=hasher.sha256()sha.update('yourcontent')printsha.hexdigest()输......
  • Python-接口
    fromabcimportABCMeta,abstractmethod#接口:若干抽象方法的集合classPaymet(metaclass=ABCMeta):#abstractmethodclass#抽象方法@abstractmeth......