You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm trying to add a new condition to the strategy in the guide, however I'm not getting the expected result. Can you help me indicate what I am doing wrong? I'm trying to combine SMA and RVOL at the same time. Thanks.
frombacktestingimportBacktest, Strategyfrombacktesting.libimportcrossoverfrombacktesting.testimportGOOGimportpandasaspdimportnumpyasnpimportyfinanceasyfMSFT=yf.download(["MSFT"], start="2019-01-01", end="2024-01-01")
defSMA(values, n):
""" Return simple moving average of `values`, at each step taking into account `n` previous values. """returnpd.Series(values).rolling(n).mean()
defRVOL(volume, window):
""" Calculate Relative Volume (RVOL) using a rolling window. Args: volume (np.array): Array of volume data. window (int): Window size for calculating the average volume. Returns: np.array: RVOL values calculated using the rolling window. """avg_volume=np.convolve(volume, np.ones(window)/window, mode='valid')
rvol_values=volume[window-1:] /avg_volumervol_values=np.concatenate((np.full(window-1, np.nan), rvol_values))
returnrvol_valuesclassSmaCross(Strategy):
n1=20n2=50threshold=1.2definit(self):
close=self.data.Closeself.sma1=self.I(SMA, close, self.n1)
self.sma2=self.I(SMA, close, self.n2)
# Precompute RVOLself.rvol=self.I(RVOL, self.data.Volume, 10) # Adjust the window size as neededdefnext(self):
ifcrossover(self.sma1, self.sma2) andself.rvol[-1] >self.threshold:
self.position.close()
self.buy()
elifcrossover(self.sma2, self.sma1) andself.rvol[-1] >self.threshold:
self.position.close()
self.sell()
bt=Backtest(MSFT, SmaCross,
cash=10000, commission=.002,
exclusive_orders=True)
stats=bt.run()
print(stats)
The text was updated successfully, but these errors were encountered:
I'm trying to add a new condition to the strategy in the guide, however I'm not getting the expected result. Can you help me indicate what I am doing wrong? I'm trying to combine SMA and RVOL at the same time. Thanks.
The text was updated successfully, but these errors were encountered: