Im new to backtrader and still trying to get the hang of it. How would I go about calling the fastk and fastd lines in my strategy? Doing StochasticRSI.lines.fastk throws me an attribute error (AttributeError: 'NoneType' object has no attribute 'lines').
Latest posts made by Tomas
-
RE: Stochastic RSI indicator.
-
Not able to fetch live data from IB but works with Yahoofinance
Hello!
Im trying to fetch data from Interactive Brokers, however it simply throws me the following error when I try to plot the data(base) D:\backtrader projects>D:\Python\python.exe "d:\backtrader projects\strategies\testytest.py" Server Version: 76 TWS Time at connection:20190421 18:33:13 CET 21-Apr-19 18:33:19 DEBUG CACHEDIR=C:\Users\Tomas_000\.matplotlib 21-Apr-19 18:33:19 DEBUG Using fontManager instance from C:\Users\Tomas_000\.matplotlib\fontlist-v300.json Traceback (most recent call last): File "d:\backtrader projects\strategies\testytest.py", line 64, in <module> cerebro.plot() File "D:\Python\lib\site-packages\backtrader\cerebro.py", line 996, in plot plotter.show() File "D:\Python\lib\site-packages\backtrader\plot\plot.py", line 795, in show self.mpyplot.show() AttributeError: 'Plot_OldSync' object has no attribute 'mpyplot'
However if I try to run the exact same code but instead comment out the IBData feed and insert a yahoo datafeed it will work and plot the graph as wanted.
My code is
from __future__ import (absolute_import, division, print_function, unicode_literals) import backtrader as bt import datetime # For datetime objects import os.path # To manage paths import sys # To find out the script name (in argv[0]) import math from backtrader.indicators import Indicator, MovAv, RelativeStrengthIndex, Highest, Lowest class TestStrategy(bt.Strategy): def __init__(self): # Keep a reference to the "close" line in the data[0] dataseries self.dataclose = self.datas[0].close def next(self): print(self.dataclose) if __name__ == '__main__': #Variable for our starting cash startcash = 10000 #Create an instance of cerebro cerebro = bt.Cerebro() #Add the strategy cerebro.addstrategy(TestStrategy) # Add Sizer #cerebro.addsizer(LongOnly) # Activate optimization StrategyOptimizationEnabled = False #Add our strategy if StrategyOptimizationEnabled == True: cerebro.optstrategy(TestStrategy, maperiod=range(14,21)) #Get Apple data from Yahoo Finance. THIS ACTUALLY WORKS BUT IBDATA DOESNT WORK # data = bt.feeds.YahooFinanceData( # dataname="AAPL", # fromdate = datetime.datetime(2019,1,1), # todate = datetime.datetime(2020,1,1) # ) #Get Twitter data from Yahoo Finance. store = bt.stores.IBStore(port=7497) data = store.getdata(dataname='TWTR', timeframe=bt.TimeFrame.Ticks, fromdate=datetime.datetime(2019,1,1), todate=datetime.datetime(2020,1,1)) cerebro.resampledata(data, timeframe=bt.TimeFrame.Seconds, compression=10) #Add the data to Cerebro #cerebro.resampledata(data, timeframe=bt.TimeFrame.Minutes, compression=15) # Set our desired cash start cerebro.broker.setcash(startcash) # Run over everything opt_runs = cerebro.run() # Set the commission cerebro.broker.setcommission(commission=0.005) # Plot the result cerebro.plot()
-
RE: Unable to get indicators to work
@backtrader
Well, I'm just trying to port a strategy of mine from Pinescript. I'm sorry if my question seems ignorant? -
RE: Unable to get indicators to work
Well, I have tried googling it now for the past few days. Still no luck. Perhaps @backtrader has any thoughtful input as to why indicators doesn't work?
-
RE: Unable to get indicators to work
neither
bt.indicators.SimpleMovingAverage(self.datas[0].close, period = 40)
orbt.ind.SMA(...)
works. The indicators still dont get plotted. I tried this as well from the start but gave it a shot again, still no luck -
Unable to get indicators to work
Hello all!
Im new to backtrader and so far im trying to get a few simple indicators to work but without any luck.I simply get an error on every indicator I try to use saying the following: Module 'backtrader' has no 'sma' memberpylint(no-member)
When plotting my strategy everything but the indicator plots. I have been looking around in the documentation for a while now and still can't seem to find a fix.
Code below:
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 backtrader as bt import math # Create a Stratey class TestStrategy(bt.Strategy): params = ( ('maperiod', 15), ) def __init__(self): self.startcash = self.broker.getvalue() self.sma = bt.sma(self.data.close, period=15) self.rsi = bt.RSI_SMA(self.data.close, period=14,) def next(self): if not self.position: if self.rsi < 30: self.buy() else: if self.rsi > 70: self.close() class LongOnly(bt.Sizer): params = (('stake', 1),) def _getsizing(self, comminfo, cash, data, isbuy): if isbuy: divide = math.floor(cash/data.close[0]) self.p.stake = divide return self.p.stake # Sell situation position = self.broker.getposition(data) if not position.size: return 0 # do not sell if nothing is open return self.p.stake if __name__ == '__main__': #Variable for our starting cash startcash = 10000 #Create an instance of cerebro cerebro = bt.Cerebro(optreturn=False) # Add Sizer cerebro.addsizer(LongOnly) # Activate optimization StrategyOptimizationEnabled = False #Add our strategy if StrategyOptimizationEnabled == True: cerebro.optstrategy(TestStrategy, maperiod=range(14,21)) #Get Apple data from Yahoo Finance. data = bt.feeds.YahooFinanceData( dataname='AAPL', fromdate = datetime.datetime(2019,1,1), todate = datetime.datetime(2020,1,1), buffered= True ) #Add the data to Cerebro cerebro.adddata(data) # Set our desired cash start cerebro.broker.setcash(startcash) # Run over everything opt_runs = cerebro.run() # Set the commission cerebro.broker.setcommission(commission=0.005) # Generate results list if StrategyOptimizationEnabled == True: final_results_list = [] for run in opt_runs: for strategy in run: value = round(strategy.broker.get_value(),2) PnL = round(value - startcash,2) maperiod = strategy.params.maperiod final_results_list.append([maperiod,PnL]) #Sort Results List by_period = sorted(final_results_list, key=lambda x: x[0]) by_PnL = sorted(final_results_list, key=lambda x: x[1], reverse=True) #Print results print('Results: Ordered by period:') for result in by_period: print('Period: {}, PnL: {}'.format(result[0], result[1])) print('Results: Ordered by Profit:') for result in by_PnL: print('Period: {}, PnL: {}'.format(result[0], result[1])) # Plot the result cerebro.plot()