backtrader回测框架学习笔记-1

简介: backtrader回测框架学习笔记-1
#基于macd技术指标的策略
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
import datetime  # For datetime objects
import os.path  # To manage paths
import sys  # To find out the script name (in argv[0])
import pandas as pd
#import statsmodel as sm
# Import the backtrader platform
import backtrader as bt
# Create a Stratey
class TestStrategy(bt.Strategy):
    params = (
        # Standard MACD Parameters
        ('macd1', 12),
        ('macd2', 26),
        ('macdsig', 9),
    )
    def log(self, txt, dt=None):
        ''' Logging function for this strategy'''
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))
    def __init__(self):
        self.dataclose_x = self.datas[0].close
        self.dataclose_y = self.datas[1].close
        self.macd = bt.indicators.MACD(self.data,
                                       period_me1=self.p.macd1,
                                       period_me2=self.p.macd2,
                                       period_signal=self.p.macdsig)
        self.order = None
        self.buyprice = None
        self.buycomm = None
    def notify_cashvalue(self, cash, value):
        self.log('Cash %s Value %s' % (cash, value))
    def notify_order(self, order):
        print(type(order), 'Is Buy ', order.isbuy())
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            return
        # Check if an order has been completed
        # Attention: broker could reject order if not enough cash
        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                    (order.executed.price,
                     order.executed.value,
                     order.executed.comm))
                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
            else:  # Sell
                self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.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]:
            self.log('Order Canceled/Margin/Rejected')
        self.order = None
    def notify_trade(self, trade):
        if not trade.isclosed:
            return
        self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                 (trade.pnl, trade.pnlcomm))
    def next(self):
        # Simply log the closing price of the series from the reference
        self.log('Close, %.2f' % self.dataclose_x[0])
        self.log('Close, %.2f' % self.dataclose_y[0])
        # Check if we are in the market
        if not self.getposition(self.datas[1]):
            # Not yet ... we MIGHT BUY if ...
            if self.macd[0]>self.macd[-1]:
                    #if sma[0]<top[-5]:
                        # BUY, BUY, BUY!!! (with default parameters)
                        self.log('BUY CREATE,{},{}'.format(self.dataclose_y[0],self.dataclose_x[0]) )
                        # Keep track of the created order to avoid a 2nd order
                        self.order=self.sell(self.datas[1])
                        #self.order = self.buy(self.datas[0])
        else:
            # Already in the market ... we might sell
            if len(self) >= (self.bar_executed + 5):
                # SELL, SELL, SELL!!! (with all possible default parameters)
                self.log('BUY CREATE,{},{}'.format(self.dataclose_y[0],self.dataclose_x[0]) )
                # Keep track of the created order to avoid a 2nd order
                self.log('Pos size %s' % self.position.size)
                self.order = self.close(self.datas[1])
                #self.order = self.close(self.datas[0])
if __name__ == '__main__':
    # Create a cerebro entity
    cerebro = bt.Cerebro()
    cerebro.addstrategy(TestStrategy)
    # Datas are in a subfolder of the samples. Need to find where the script is
    # because it could have been called from anywhere
    datapath_1='/home/yjj/stock_data_day/000001.SZ.csv'
    datapath_2='/home/yjj/stock_data_day/000002.SZ.csv'
    # Create a Data Feed
    data_1 = bt.feeds.GenericCSVData(
        dataname=datapath_1,
        # Do not pass values before this date
        fromdate=datetime.datetime(1991, 12, 23),
        # Do not pass values after this date
        todate=datetime.datetime(2017, 12, 31),
        dtformat=('%Y-%m-%d'),
        tmformat=('%H.%M.%S'),
        date=0,
        open=1,
        close=2,
        high=3,
        low=4,
        volume=5,
        openinterest=6,
        code=-1,
        reverse=False)
    data_2 = bt.feeds.GenericCSVData(
        dataname=datapath_2,
        # Do not pass values before this date
        fromdate=datetime.datetime(1991, 12, 23),
        # Do not pass values after this date
        todate=datetime.datetime(2017, 12, 31),
        dtformat=('%Y-%m-%d'),
        tmformat=('%H.%M.%S'),
        date=0,
        open=1,
        close=2,
        high=3,
        low=4,
        volume=5,
        openinterest=6,
        reverse=False)
    # Add the Data Feed to Cerebro
    cerebro.adddata(data_1)
    cerebro.adddata(data_2)
    # Set our desired cash start
    cerebro.broker.setcash(100000.0)
    cerebro.broker.setcommission(commission=0.001)
    cerebro.addsizer(bt.sizers.FixedSize, stake=100) 
    # Print out the starting conditions
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    # Run over everything
    cerebro.run()
    # Print out the final result
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    cerebro.plot()
目录
相关文章
|
7月前
|
JSON 数据可视化 安全
UCB Data100:数据科学的原理和技巧:第六章到第十章(1)
UCB Data100:数据科学的原理和技巧:第六章到第十章(1)
107 0
|
7月前
|
数据可视化 Linux 定位技术
UCB Data100:数据科学的原理和技巧:第六章到第十章(4)
UCB Data100:数据科学的原理和技巧:第六章到第十章(4)
144 0
|
7月前
|
机器学习/深度学习 数据可视化 Linux
UCB Data100:数据科学的原理和技巧:第六章到第十章(3)
UCB Data100:数据科学的原理和技巧:第六章到第十章(3)
81 0
|
7月前
|
数据可视化 Python
UCB Data100:数据科学的原理和技巧:第六章到第十章(2)
UCB Data100:数据科学的原理和技巧:第六章到第十章(2)
86 0
|
2月前
|
数据可视化 数据处理 Python
如何使用Python实现一个基于均线的交易策略
【10月更文挑战第9天】本文介绍了如何使用Python实现一个基于均线的交易策略。主要步骤包括导入所需库(如`pandas`、`numpy`和`matplotlib`),加载股票或期货的历史数据,计算均线和其他指标,实现交易策略逻辑,以及可视化交易结果。示例代码展示了如何根据均线交叉点进行开仓、止损和止盈操作,并提供了注意事项,如数据来源、交易成本和风险管理。
95 7
|
7月前
|
机器学习/深度学习 数据可视化
UCB Data100:数据科学的原理和技巧:第六章到第十章(5)
UCB Data100:数据科学的原理和技巧:第六章到第十章(5)
72 0
|
6月前
|
机器学习/深度学习 数据采集 API
|
7月前
|
Python
python实现股票策略回测案例
此Python代码演示了一个简单的股票策略回测,使用yfinance库获取AAPL股票2020年至2022年的数据。它计算每日收益率,并基于前一日收益率决定买卖:正则买入,负则卖出。通过模拟交易更新现金和股票余额,最终计算总收益。请注意,此示例未涵盖交易费用、滑点、风险管理等实际交易因素。
187 0
|
7月前
|
机器学习/深度学习 算法 数据挖掘
数据分享|Python爱彼迎Airbnb新用户体验数据XGBoost、随机森林预测
数据分享|Python爱彼迎Airbnb新用户体验数据XGBoost、随机森林预测
|
7月前
|
机器学习/深度学习 数据采集 数据可视化
探秘scikit-learn:机器学习库的核心功能详解
【4月更文挑战第17天】探索scikit-learn,Python机器学习库,涵盖数据预处理(如标准化、归一化)、模型选择(分类、回归、聚类等)、模型训练、评估与优化(交叉验证、网格搜索)、流水线和集成学习,以及可视化和解释性工具。这个库简化了复杂项目,助力用户高效构建和理解机器学习模型,适合各水平学习者提升技能。