As it is, I wrote a custom indicator class in the same script for explanation. However, it is more convenient to write only the custom indicator class in a separate py file and use it separately from the strategy script.
If the file name of the custom indicator is ** customindicator.py **, it will be at the beginning of the strategy.
ʻImport customindicator as cind` (any descriptive name)
In the init method of the strategy class
self.myind1 = cind.MyStochastics1(self.data)
Write.
Place customindicator.py in the same directory as the strategy script. If you are using Jupyter notebook and keep the default settings, it is C: \ Users \ username \
.
customindicator.py
import backtrader as bt
class MyStochastic1(bt.Indicator):
lines = ('k', 'd', )
params = (
('k_period', 14),
('d_period', 3), #Comma at the end of the tuple(、)Put in
)
def __init__(self):
highest = bt.ind.Highest(self.data, period=self.p.k_period)
lowest = bt.ind.Lowest(self.data, period=self.p.k_period)
self.lines.k = k = (self.data - lowest) / (highest - lowest)
self.lines.d = bt.ind.SMA(k, period=self.p.d_period)
sto2.py
%matplotlib notebook
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import datetime
import os.path
import sys
import backtrader as bt
import customindicator as cind #
class TestStrategy(bt.Strategy):
def __init__(self):
self.myind1 = cind.MyStochastics1(self.data)
if __name__ == '__main__':
cerebro = bt.Cerebro()
cerebro.addstrategy(TestStrategy)
datapath = 'C:\\Users\\XXXX\\orcl-1995-2014.txt'
# Create a Data Feed
data = bt.feeds.YahooFinanceCSVData(
dataname=datapath,
fromdate=datetime.datetime(2000, 1, 1),
todate=datetime.datetime(2000, 12, 31),
reverse=False)
cerebro.adddata(data)
cerebro.run(stdstats=False)
cerebro.plot(style='candle')
Recommended Posts