backtrader-学习笔记2

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
        ('period', 252),
        ('prepend_constant', True),
    )
    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.ma1 = bt.indicators.SMA(self.datas[0],
                                       period=self.p.period
                                      )
        self.ma2 = bt.indicators.SMA(self.datas[1],
                                       period=self.p.period
                                      )
        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.ma1[0]-self.ma1[-1])/self.ma1[-1]>(self.ma2[0]-self.ma2[-1])/self.ma2[-1]:
                    #if sma[0]

backtrader-学习笔记2_第1张图片

你可能感兴趣的:(python,回测系统)