Skip to content

Commit

Permalink
New Strategy, Custom Indicator, fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
aLca committed Jun 5, 2024
1 parent be3bd8a commit 8c931d8
Show file tree
Hide file tree
Showing 3 changed files with 152 additions and 7 deletions.
14 changes: 7 additions & 7 deletions backtest.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from imports import *
from live_strategys.QQE_Hullband_VolumeOsc import QQE_Example
from template_strategys.DCA_QQE_Example_backtesting import QQE_DCA_Example

from template_strategys.SuperTrend_Scalp import SuperSTrend_Scalper

def backtest():
running_backtest(True)
Expand All @@ -10,14 +10,14 @@ def backtest():
my_data_frame = pd.read_csv(rvn, index_col=0, parse_dates=True)
my_data_frame = my_data_frame.sort_index()

start = "2022-01-01"
end = "2022-02-27"
df = my_data_frame.loc[start:end]
_start = "2022-01-01"
_end = "2022-02-27"
df = my_data_frame.loc[_start:_end]
data = MyPandasData(dataname=df)

cerebro = bt.Cerebro(oldbuysell=True)
cerebro.adddata(data)
cerebro.addstrategy(QQE_DCA_Example, backtest=True)
cerebro.addstrategy(SuperSTrend_Scalper, backtest=True)

startcash = 10000
cerebro.broker.setcash(startcash)
Expand Down Expand Up @@ -52,10 +52,10 @@ def backtest():

# Format the filename with coin name, start date, end date, and current date
current_date = dt.datetime.now().strftime("%Y-%m-%d")
filename = f"QuantStat_{start}_to_{end}_generated_on_{current_date}.html"
filename = f"QuantStat_{_start}_to_{_end}_generated_on_{current_date}.html"

# Generate QuantStats report
quantstats.reports.html(returns, output=filename, title=f'{current_date}_{start}_to_{end}_1m')
quantstats.reports.html(returns, output=filename, title=f'{current_date}_{_start}_to_{_end}_1m')

def print_trade_analyzer_results(trade_analyzer, indent=0):
for key, value in trade_analyzer.items():
Expand Down
48 changes: 48 additions & 0 deletions custom_indicators/SuperTrend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import backtrader as bt

class SuperTrend(bt.Indicator):
lines = ('super_trend',)
params = (('period', 7),
('multiplier', 3),
)
plotlines = dict(
super_trend=dict(
_name='SuperTrend',
color='cyan',
alpha=1
)
)
plotinfo = dict(subplot=False)

def __init__(self):
self.st = [0]
self.finalupband = [0]
self.finallowband = [0]
self.addminperiod(self.p.period)
atr = bt.ind.ATR(self.data, period=self.p.period)
self.upperband = (self.data.high + self.data.low) / 2 + self.p.multiplier * atr
self.lowerband = (self.data.high + self.data.low) / 2 - self.p.multiplier * atr

def next(self):
pre_upband = self.finalupband[0]
pre_lowband = self.finallowband[0]
if self.upperband[0] < self.finalupband[-1] or self.data.close[-1] > self.finalupband[-1]:
self.finalupband[0] = self.upperband[0]
else:
self.finalupband[0] = self.finalupband[-1]
if self.lowerband[0] > self.finallowband[-1] or self.data.close[-1] < self.finallowband[-1]:
self.finallowband[0] = self.lowerband[0]
else:
self.finallowband[0] = self.finallowband[-1]
if self.data.close[0] <= self.finalupband[0] and ((self.st[-1] == pre_upband)):
self.st[0] = self.finalupband[0]
self.lines.super_trend[0] = self.finalupband[0]
elif (self.st[-1] == pre_upband) and (self.data.close[0] > self.finalupband[0]):
self.st[0] = self.finallowband[0]
self.lines.super_trend[0] = self.finallowband[0]
elif (self.st[-1] == pre_lowband) and (self.data.close[0] >= self.finallowband[0]):
self.st[0] = self.finallowband[0]
self.lines.super_trend[0] = self.finallowband[0]
elif (self.st[-1] == pre_lowband) and (self.data.close[0] < self.finallowband[0]):
self.st[0] = self.finalupband[0]
self.lines.super_trend[0] = self.st[0]
97 changes: 97 additions & 0 deletions template_strategys/SuperTrend_Scalp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import backtrader as bt
from live_strategys.live_functions import BaseStrategy
from custom_indicators.SuperTrend import SuperTrend

class SuperSTrend_Scalper(BaseStrategy):
params = (
("dca_threshold", 2.5),
("take_profit", 4),
('percent_sizer', 0.01), # 0.01 -> 1%
# Trend Strenght
("adx_period", 13),
("adx_strength", 31),
("di_period", 14),
("adxth", 25),

# Supertrends
("st_fast", 2),
('st_fast_multiplier', 3),
("st_slow", 6),
('st_slow_multiplier', 7),
# RevFinder
('reversal_lookback', 10),
('reversal_malen', 40),
('reversal_mult', 2.2),
('reversal_rangethreshold', 0.9),
('debug', False),
("backtest", None)
)

def __init__(self):
super().__init__()
self.adx = bt.indicators.ADX(self.data, plot=False)
self.plusDI = bt.indicators.PlusDI(self.data, plot=False)
self.minusDI = bt.indicators.MinusDI(self.data, plot=False)
self.supertrend_fast = SuperTrend(period=self.p.st_fast, multiplier=self.p.st_fast_multiplier, plotname='SuperTrend Fast: ', plot=True)
self.supertrend_slow = SuperTrend(period=self.p.st_slow, multiplier=self.p.st_slow_multiplier, plotname='SuperTrend Slow: ', plot=True)
self.supertrend_uptrend_signal = bt.indicators.CrossOver(self.supertrend_fast, self.supertrend_slow, plot=False)
# self.supertrend_downtrend_signal = bt.indicators.CrossDown(self.supertrend_fast, self.supertrend_slow, plot=False) # NOT USED IN THIS EXAMPLE
self.DCA = True
self.buy_executed = False
self.conditions_checked = False

def buy_or_short_condition(self):
if (
self.adx[0] >= self.params.adxth and \
self.minusDI[0] > self.params.adxth and \
self.plusDI[0] < self.params.adxth and \
self.supertrend_uptrend_signal
):

if self.params.backtest == False:
self.entry_prices.append(self.data.close[0])
self.sizes.append(self.amount)
self.load_trade_data()
self.rabbit.send_jrr_buy_request(exchange=self.exchange, account=self.account, asset=self.asset, amount=self.amount)
self.buy_executed = True
self.conditions_checked = True
elif self.params.backtest == True:
self.buy(size=self.stake, price=self.data.close[0], exectype=bt.Order.Market)
self.take_profit_price = self.data.close[-1] * (1 + self.params.take_profit / 100)
self.buy_executed = True
self.conditions_checked = True

def dca_or_short_condition(self):
if (self.position and \
self.adx[0] >= self.params.adxth and \
self.minusDI[0] > self.params.adxth and \
self.plusDI[0] < self.params.adxth and \
self.supertrend_uptrend_signal
):

if self.params.backtest == False:
self.entry_prices.append(self.data.close[0])
self.sizes.append(self.amount)
self.load_trade_data()
self.rabbit.send_jrr_buy_request(exchange=self.exchange, account=self.account, asset=self.asset, amount=self.amount)
self.buy_executed = True
self.conditions_checked = True
elif self.params.backtest == True:
self.buy(size=self.stake, price=self.data.close[0], exectype=bt.Order.Market)
self.take_profit_price = self.data.close[-1] * (1 + self.params.take_profit / 100)
self.buy_executed = True
self.conditions_checked = True


def sell_or_cover_condition(self):
if self.buy_executed and self.data.close[0] >= self.take_profit_price:
if self.params.backtest == False:
self.rabbit.send_jrr_close_request(exchange=self.exchange, account=self.account, asset=self.asset)
elif self.params.backtest == True:
self.close()
self.reset_position_state()
self.buy_executed = False
self.conditions_checked = True

def next(self):
BaseStrategy.next(self)

0 comments on commit 8c931d8

Please sign in to comment.