Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
backtesting can't optimize
#1
from backtesting import Strategy, Backtest
import yfinance as yf
import pandas as pd
import numpy as np
import pandas_ta as ta

# === Download Data ===
print("Downloading data...")
df = yf.download('TSLA', period='8d', interval='1m')
df.columns = [c[0] for c in df.columns]

# === Calculate Indicators ===
df["VWAP"] = ta.vwap(df.High, df.Low, df.Close, df.Volume)
df['RSI'] = ta.rsi(df.Close, length=16)
my_bbands = ta.bbands(df.Close, length=14, std=2.0)
df = df.join(my_bbands)

VWAPsignal = [0] * len(df)
backcandles = 15

for row in range(backcandles, len(df)):
    upt = 1
    dnt = 1
    for i in range(row - backcandles, row + 1):
        if max(df.Open.iloc[i], df.Close.iloc[i]) >= df.VWAP.iloc[i]:
            dnt = 0
        if min(df.Open.iloc[i], df.Close.iloc[i]) <= df.VWAP.iloc[i]:
            upt = 0
    if upt == 1 and dnt == 1:
        VWAPsignal[row] = 3
    elif upt == 1:
        VWAPsignal[row] = 2
    elif dnt == 1:
        VWAPsignal[row] = 1

df['VWAPSignal'] = VWAPsignal

def TotalSignal(l):
    if (df.VWAPSignal.iloc[l] == 2
        and df.Close.iloc[l] <= df['BBL_14_2.0'].iloc[l]
        and df.RSI.iloc[l] < 45):
        return 2
    if (df.VWAPSignal.iloc[l] == 1
        and df.Close.iloc[l] >= df['BBU_14_2.0'].iloc[l]
        and df.RSI.iloc[l] > 55):
        return 1
    return 0

TotSignal = [0] * len(df)
for row in range(backcandles, len(df)):
    TotSignal[row] = TotalSignal(row)
df['TotalSignal'] = TotSignal

def pointposbreak(x):
    if x['TotalSignal'] == 1:
        return x['High'] + 1e-4
    elif x['TotalSignal'] == 2:
        return x['Low'] - 1e-4
    else:
        return np.nan

df['pointposbreak'] = df.apply(lambda row: pointposbreak(row), axis=1)

dfpl = df[:75000].copy()
dfpl['ATR'] = ta.atr(dfpl.High, dfpl.Low, dfpl.Close, length=7)

def SIGNAL():
    return dfpl.TotalSignal

class MyStrat(Strategy):
    initsize = 0.99
    mysize = initsize

    # Add these lines:
    rsi_exit_long = 90   # Default value; will be overridden during optimization
    rsi_exit_short = 10  # Default value; will be overridden during optimization

    def init(self):
        super().init()
        self.signal1 = self.I(SIGNAL)

    def next(self):
        super().next()
        slatr = 1.2 * self.data.ATR[-1]
        TPSLRatio = 1.5

        if len(self.trades) > 0:
            if self.trades[-1].is_long and self.data.RSI[-1] >= self.rsi_exit_long:
                self.trades[-1].close()
            elif self.trades[-1].is_short and self.data.RSI[-1] <= self.rsi_exit_short:
                self.trades[-1].close()

        if self.signal1[-1] == 2 and len(self.trades) == 0:
            sl1 = self.data.Close[-1] - slatr
            tp1 = self.data.Close[-1] + slatr * TPSLRatio
            self.buy(sl=sl1, tp=tp1, size=self.mysize)

        elif self.signal1[-1] == 1 and len(self.trades) == 0:
            sl1 = self.data.Close[-1] + slatr
            tp1 = self.data.Close[-1] - slatr * TPSLRatio
            self.sell(sl=sl1, tp=tp1, size=self.mysize)

bt = Backtest(
    dfpl,
    MyStrat,
    cash=30000,
    margin=1/10,
    commission=0.00
)

output=bt.run()
print(output)


stats=bt.optimize(rsi_exit_long=range(70, 100, 5), rsi_exit_short=range(5, 35, 5),maximize='Equity Final [$]')



print(stats)
bt.plot()
i am newbiee in python backtest.
i don't understand why code can't load the optimize result.
Any idea?
Reply
#2
If you want to see the equity curve for the optimized (best) run,you need to pass that pd.Series back into bt.plot(...).
stats = bt.optimize(
    rsi_exit_long = range(70, 100, 5),
    rsi_exit_short = range(5, 35, 5),
    maximize = 'Equity Final [$]'
)

# shows the metrics of the best run
print(stats)

# Plot the best run
bt.plot(results=stats)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I multithread to optimize a groupby task: davisc4468 0 1,259 Jun-30-2023, 02:45 PM
Last Post: davisc4468
  do you have an idea to optimize this code[recursion]]? netanelst 4 2,351 May-20-2022, 06:41 PM
Last Post: jefsummers
  Optimization using scipy.optimize KaneBilliot 3 3,066 Nov-30-2021, 08:03 AM
Last Post: Gribouillis
  Using curve_fit to optimize function (TypeError) Laplace12 4 4,066 Aug-30-2021, 11:15 AM
Last Post: Larz60+
  is there a way to optimize my checking system? GalaxyCoyote 4 3,749 Oct-13-2019, 09:18 AM
Last Post: perfringo
  cannot import scipy.optimize.Bounds larkypython 2 8,908 May-05-2019, 04:09 AM
Last Post: larkypython
  Optimize unittest loading Nazz 3 3,428 Mar-05-2019, 11:59 AM
Last Post: Nazz
  optimize choices in multiple if ---: statements Pedroski55 2 3,744 Dec-25-2018, 05:06 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020