Hi All
I am trying to create a strategy, where whenever the MA's crossover I have to check the FibonacciPivotPoint() to see at what range (s1, r1 etc) the closing price is before I make the decision to Buy or Sell
For MA I am using '1Day' data for the period of 1 Year and for Fibonacci I am using '1Month' data.
The problems I am facing are
-
I am not sure how to pass the "month" data name (the one that I am planning to use for Fibonacci) to the FibonacciPivotPoint() and get the computed values
-
I also want to check the MA cross over with previous month Fibonacci Values. Meaning, if the trade signal is generated based on MA for say 23.06.22. I need to check the previous month(01.05.2022) fibonacci calculated values to see whether the close price is in support range or resistance range
If someone can help me here or modify the code to accomplish the functionality that I am looking for, that would be great
I am pasting some data point for review
1 Day Data
2021-06-23,402.8999938964844,404.95001220703125,396.6000061035156,397.54998779296875,397.54998779296875,1824603
2021-06-24,398.20001220703125,400.8999938964844,394.0,395.20001220703125,395.20001220703125,1888424
2021-06-25,396.0,399.95001220703125,394.3999938964844,396.95001220703125,396.95001220703125,642550
2021-06-28,398.3500061035156,409.70001220703125,397.54998779296875,404.1499938964844,404.1499938964844,3019858
2021-06-29,406.8999938964844,411.0,402.0,407.54998779296875,407.54998779296875,2239813
2021-06-30,408.75,411.0,403.54998779296875,404.45001220703125,404.45001220703125,1217199
1 Month Data
2021-05-01,380.95001220703125,393.6499938964844,370.1499938964844,388.20001220703125,388.20001220703125,55544400
2021-06-01,390.70001220703125,420.25,382.8500061035156,404.45001220703125,404.45001220703125,60320960
2021-07-01,404.5,414.3999938964844,376.70001220703125,386.3500061035156,386.3500061035156,59979772
2021-08-01,387.29998779296875,392.45001220703125,327.54998779296875,358.8500061035156,358.8500061035156,42858605
2021-09-01,360.0,394.1499938964844,350.04998779296875,362.70001220703125,362.70001220703125,58722361
2021-10-01,362.0,370.6000061035156,314.79998779296875,351.1000061035156,351.1000061035156,55033772
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 the backtrader platform
import backtrader as bt
'''
Pending issuse
1. When a trade is booked it is using the next days closing price, need to change it to next days opening price
2. Fibonacci pivot points data are yet to be brought in to the equation
'''
# Create a Stratey
class TestStrategy(bt.Strategy):
params = (
('sl_maperiod', 10),
('ft_maperiod', 12)
)
def log(self, txt, dt=None):
''' Logging function fot this strategy'''
dt = self.dnames.days.datetime.date(0)
self.fib_dt = self.dnames.month.datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def __init__(self):
# Keep a reference to the "close" line in the data[0] dataseries
self.dataclose = self.dnames.days.close
#self.dataclose_m = self.dnames.month.close
#self.fb_close = self.datas[1][0].close
#print(self.fb_close[0])
#print(self.dataclose[0])
# To keep track of pending orders and buy price/commission
self.order = None
# for d in self.getdatanames():
# if d == "days":
# # Add a MovingAverageSimple indicator
self.sl_sma = bt.indicators.ExponentialMovingAverage(self.dnames.days, period=self.params.sl_maperiod)
self.ft_sma = bt.indicators.ExponentialMovingAverage(self.dnames.days, period=self.params.ft_maperiod)
#self.regime = self.ft_sma - self.sl_sma
# else:
self.Fib = bt.indicators.FibonacciPivotPoint(self.dnames.month)
def notify_order(self, order):
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))
pass
elif order.issell(): # Sell
# self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
# (order.executed.price,
# order.executed.value,
# order.executed.comm))
pass
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[0])
self.log(self.fib_dt.isoformat())
#self.log('Close, %.2f' % self.dataclose_m[0])
#self.log('Close, %.2f' % self.data1.close[0])
# Check if an order is pending ... if yes, we cannot send a 2nd one
if self.order:
return
# Check if we are in the market
for d in self.getdatanames():
#print(d)
pos = self.getpositionbyname(d).size
if d == "days" and pos == 0:
print(d, pos)
if self.sl_sma[0] > self.ft_sma[0]:
#print(self.regime[0], self.sl_sma[0], self.ft_sma[0])
self.log('BUY CREATE, %.2f, %.2f ,%.2f' % (self.dataclose[0],self.sl_sma[0], self.ft_sma[0]))
self.order = self.buy()
elif self.sl_sma[0] < self.ft_sma[0]:
print(d, pos)
#print(self.regime[0], self.sl_sma[0], self.ft_sma[0])
self.log('SELL CREATE, %.2f, %.2f ,%.2f' % (self.dataclose[0],self.sl_sma[0], self.ft_sma[0]))
self.order = self.sell()
elif d == "days" and pos !=0:
if pos > 0:
if self.sl_sma[0] < self.ft_sma[0]:
self.log('BUY CLOSE, %.2f, %.2f ,%.2f' % (self.dataclose[0],self.sl_sma[0], self.ft_sma[0]))
self.order = self.close()
else:
if self.sl_sma[0] > self.ft_sma[0]:
self.log('SELL CLOSE, %.2f, %.2f ,%.2f' % (self.dataclose[0],self.sl_sma[0], self.ft_sma[0]))
self.order = self.close()
if __name__ == '__main__':
cerebro = bt.Cerebro()
cerebro.addstrategy(TestStrategy)
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, "data", "BIOCON.NS1YR.csv")
datapath1 = os.path.join(modpath, "data", "BIOCON.NS1MO.csv")
#pv_datapath = os.path.join(modpath, "data", "BIOCON.NS1YR.csv")
cerebro.broker.set_cash(100000.00)
cerebro.addsizer(bt.sizers.FixedSize, stake=10) # Quantity
cerebro.broker.setcommission(commission=0.001)
data = bt.feeds.YahooFinanceCSVData(
dataname=datapath,
fromdate=datetime.datetime(2021, 6, 23 ),
todate=datetime.datetime(2022, 6, 24),
reverse=False)
fib_data = bt.feeds.YahooFinanceCSVData(
dataname=datapath1,
fromdate=datetime.datetime(2021, 5, 1),
todate=datetime.datetime(2022, 5, 31),
reverse=False)
# data1 = bt.feeds.YahooFinanceCSVData(
# dataname=pv_datapath,
# fromdate=datetime.datetime(2021, 7, 1),
# todate=datetime.datetime(2022, 6, 1),
# reverse=False)
#fib_resample_data = cerebro.resampledata(fib_data, timeframe = bt.TimeFrame.Months)
cerebro.adddata(data, name="days")
cerebro.adddata(fib_data, name="month")
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
#cerebro.plot()[link text]([link url](link url))```