简体   繁体   中英

After running Cerebro nothing is happening to my portfolio value in backtrader, how do i check if it is working or not

import backtrader as bt import backtrader.feeds as btfeed import backtrader.analyzers as btanalyzers import talib as ta import numpy as np import pandas as pd

from datetime import datetime

class MACross(bt.Strategy):

def __init__(self):
    ma_fast = bt.ind.SMA(period = 10)
    ma_slow = bt.ind.SMA(period = 50)
    
    self.crossover = bt.ind.CrossOver(ma_fast, ma_slow)
    
def next(self):
    if not self.position:
        if self.crossover >0:
            self.buy()
    
    elif self.crossover <0:
        self.close()


class dataFeed(btfeed.GenericCSVData):
        params = (
        ('dtformat', '%m/%d/%Y %H:%M'),
        ('datetime', 0),
        ('open', 1),
        ('high', 2),
        ('low', 3),
        ('close', 4),
        ('volume', 5),
        ('openinterest', -1)
    
    )

cerebro = bt.Cerebro()
data = dataFeed(dataname='data.csv')
cerebro.addstrategy(MACross)
cerebro.adddata(data)

back = cerebro.run()
cerebro.broker.getvalue()
back[0].analyzers.sharpe.get_analysis()

cerebro.plot()
[[<Figure size 640x480 with 5 Axes>]]

Assuming the code is all correct (not in the format posted)

To check if the value has changed use:

print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

If this doesnt change have a look at the original example posted thats
also a crossover strategy and see where it differs.
Extract:

    def __init__(self):  #indicators created here
        sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
        sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
        self.crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal
    #--init--

    def next(self):
        if not self.position:  # not in the market
            if self.crossover > 0:  # if fast crosses slow to the upside
                self.order = self.buy()  #go long
            elif self.crossover < 0:  # in the market & cross to the downside
                self.order = self.sell()
                
        else:
            if len(self) >= (self.bar_executed + 5):
                self.close()  # close long position

https://www.backtrader.com/docu/quickstart/quickstart/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM