For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

No excecution of orders during tutorial SMAcrossover



  • I started recently with python so excuse me for not being the brightest light atm.
    However i've been trying alot and reading alot and i can't figure out the problem.
    I cut off almost all my code to find the essence of the problem.

    So now i'm trying a basic strategy found online.
    Its just the SMA crossover thing and i'm importing data with pandas.
    I think the data is getting imported good, i can print values out correctly during the cerebo run and i also can plot the graph in the end. Also the SMA's are visible where i can see them crossing, however the orders don't get triggered upon that. No errors are given.
    I've been trying putting other triggers for the buys/sells but they also don't work.

    import matplotlib
    import matplotlib.pyplot as plt
    from pandas.plotting import register_matplotlib_converters
    import pandas as pd
    import numpy as np
    import datetime
    import seaborn as sns
    from sklearn.model_selection import train_test_split
    import sys
    import json
    import pandas
    import numpy as np
    from sklearn.cluster import MeanShift, estimate_bandwidth
    from datetime import datetime
    import matplotlib.pyplot as plt
    from __future__ import (absolute_import, division, print_function,unicode_literals)
    import datetime
    import backtrader as bt
    import backtrader.feeds as btfeed
    import backtrader.feeds as btfeeds
    import backtrader.indicators as btind
    from datetime import datetime
    import datetime
    import os.path  # To manage paths
    import argparse
    from __future__ import (absolute_import, division, print_function,unicode_literals)
    ################## 
    path_to_market_data = '/Users/Lenovo/Desktop/machinelearning/'
    symbol = 'Bitfinex_BTCUSD_d2kort.csv'
    filename = path_to_market_data + symbol
    pd.options.display.float_format = '${:,.2f}'.format
    daily = pd.read_csv(filename, parse_dates=['Date'], index_col=['Date'])
    del daily['Unix Timestamp']
    del daily['Symbol']
    daily["Volume"] = pd.to_numeric(daily["Volume"],errors='coerce')
    print(daily)
    
    
    class PandasData(btfeed.DataBase):
        params = (('datetime', None),('open', -1),('high', -1),('low', -1),('close', -1),('volume', -1))
    
    #data = bt.feeds.PandasData(dataname=daily)
        
    class CandlesticksBW(bt.Strategy):
        
        def __init__(self):
            self.sma = btind.SimpleMovingAverage(period=15)
            self.sma2 = btind.SimpleMovingAverage(period=2)
            self.dataclose = self.data.close
            self.dataopen = self.data.open
            self.test = self.sma>self.sma2
        def next(self):
            if self.sma>self.sma2:
                self.buy()
            if self.sma < self.sma2:
                self.sell()
    
    def runstrat():
        args = parse_args()
        # Create a cerebro entity
        cerebro = bt.Cerebro()
        startcash = 10000
        # Add a strategy
        cerebro.addstrategy(CandlesticksBW)
        # Get a pandas dataframe
        datapath = filename
        # Simulate the header row isn't there if noheaders requested
        skiprows = 0 if args.noheaders else 0
        header = None if args.noheaders else 0
        dataframe = pandas.read_csv(datapath,skiprows=skiprows,header=header,parse_dates=True,index_col=0)
        if not args.noprint:
            print('--------------------------------------------------')
            print(daily)
            print('--------------------------------------------------')
        # Pass it to the backtrader datafeed and add it to the cerebro
        data = bt.feeds.PandasData(dataname=daily)
        cerebro.adddata(data)
        # Set our desired cash start
        cerebro.broker.setcash(startcash)
        # Set the commission
        cerebro.broker.setcommission(commission=0.0005)
        # Add a sizer
        #cerebro.addsizer(bt.sizers.PercentSizer, percents=50)
        # Run over everything
        cerebro.run()
        # Print out the starting conditions
        print('Starting Portfolio Value: %.2f' % startcash)
        # Get final portfolio Value
        portvalue = cerebro.broker.getvalue()
        pnl = portvalue - startcash
        # Print out the final result
        print('Final Portfolio Value: ${}'.format(portvalue))
        print('P/L: ${}'.format(pnl))
        # Plot the result
        cerebro.plot(style='bar')
        print(data.close[0])
        if data.close[0]>15:
            print('closegroterdan15')
    
    
    def parse_args():
        parser = argparse.ArgumentParser(description='Pandas test script')
        parser.add_argument('--noheaders', action='store_true', default=False,required=False,help='Do not use header rows')
        parser.add_argument('--noprint', action='store_true', default=False,help='Print the dataframe')
        return parser.parse_args()
    
    if __name__ == '__main__':
        runstrat()
    
    


  • Apologies, found it after all ;)
    Had to say which kind of orders i want to place.
    Since it was already happened and a market order couldn't work.
    This can be closed or removed !



  • Okay another question :

    I have a function that calculates values
    It reads the Close prices from a csv file with pandas.
    It uses a library to calculate.
    Then i get different pricepoints as return in an array.

    Now i want to use this in backtrader and i really wonder how i can implement this since i'm new to backtrader.

    It uses all the data from the past with samples of 50.
    So first 50 candles will be empty.
    From there different values will be calculated.
    And i need to be able to access them afcorse.

    How can i fix this the most easy way ?



  • Seems to me like a classic case for the indicator. Take a look at: https://www.backtrader.com/docu/inddev/



  • @vladisld

    I have been reading altoa dn the indicator seemed the solution indeed.
    However in the examples, the lines always contain only 1 value for each next.
    In my usecase i will need to be able to save more values matching the last close.
    And this is with 1 calculation.
    So thats where i started wondering if it would work or not.
    Thanks in advance !



  • One step closer

    Normalyl i'm putting values in my calculation like this : ( i use a panda dataframe and convert to numpy array)
    [2000]
    [3000]
    [1000]

    But the lines are giving :
    [2000,3000,1000]

    Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
    

    When using reshape he says no attribute found reshape
    Probably there is an easy fix for this but can't find it in all the posts here nor online.



  • @censorship said in No excecution of orders during tutorial SMAcrossover:

    the lines always contain only 1 value for each next.
    In my usecase i will need to be able to save more values matching the last close

    Indicator's next method will indeed be called for each new bar of the underlying data. However, by properly defining the minimum period of the indicator, it is ensured that previous minimum period bars of the underlying data are available and you may safely perform your calculations.

    If you need to pre-calculate all the indicator values for all the available bars of the underlying data - you may provide the implementation of the once method - where all the underlying data bars are pre-loaded.

    @censorship said in No excecution of orders during tutorial SMAcrossover:

    i use a panda dataframe and convert to numpy array

    Not sure you need pandas to implement a simple indicator at all.



  • @vladisld

    Okay thanks for the advice, i think i understand that.

    Just one problem, i'm using a machine learning function.
    And that wants data in a numpy array format like this;
    (2D numpy array i think)

    [1000]
    [2000]
    [3000]

    But the lines in backtrader are working different :
    [1000 2000 3000 4000]
    (1D array i think)
    So i wonder if there is a way to convert this too a numpy array on which the algorithm is working.


Log in to reply
 

});