-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
-
First of all, thank you for this module that you have provided.
I've been able to use the examples and documentation and online resources I can find to get started with some simple applications.
But alas, I am quite new to python, and have been stuck for a while trying to use the resample_apply for the strategies.
It seems simple enough, but I keep getting errors no matter what I try.
I have even tried using the suggestion found in https://github.com/kernc/backtesting.py/discussions/440 but with no luck.
Here is the code I am using:
`from backtesting import Backtest, Strategy
from backtesting.lib import crossover
from backtesting.lib import resample_apply
import pandas as pd
import pandas_ta as ta
class Super(Strategy):
period = 7
multiplier = 3
offset = 1
def init(self):
self.weekly_st = resample_apply(
'W-FRI',
ta.supertrend,
series = pd.Series(self.data.index),
high = pd.Series(self.data.High),
low = pd.Series(self.data.Low),
close = pd.Series(self.data.Close),
length = self.period,
multiplier = self.multiplier,
offset = self.offset)
def next(self):
if crossover(self.data.Close, self.weekly_st[-1]):
self.buy()
elif crossover(self.weekly_st[-1], self.data.Close):
self.position.close()
df = pd.read_csv('SPY.csv', index_col=0, parse_dates=True, infer_datetime_format=True)
df.info()
bt = Backtest(df, Super,
cash=100000, commission=0,
exclusive_orders=True)
stats = bt.run()
print(stats)
bt.plot()`
The error I get for this is:
`<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 7542 entries, 1993年01月29日 to 2023年01月10日
Data columns (total 6 columns):
Column Non-Null Count Dtype
0 Open 7542 non-null float64
1 High 7542 non-null float64
2 Low 7542 non-null float64
3 Close 7542 non-null float64
4 Adj Close 7542 non-null float64
5 Volume 7542 non-null int64
dtypes: float64(5), int64(1)
memory usage: 412.5 KB
Traceback (most recent call last):
File "C:\Users\drumlin\PycharmProjects\BTSTweekly-1\main.py", line 37, in
stats = bt.run()
^^^^^^^^
File "C:\Users\drumlin\AppData\Local\Programs\Python\Python311\Lib\site-packages\backtesting\backtesting.py", line 1139, in run
strategy.init()
File "C:\Users\drumlin\PycharmProjects\BTSTweekly-1\main.py", line 13, in init
self.weekly_st = resample_apply(
^^^^^^^^^^^^^^^
File "C:\Users\drumlin\AppData\Local\Programs\Python\Python311\Lib\site-packages\backtesting\lib.py", line 294, in resample_apply
resampled = series.resample(rule, label='right').agg(agg).dropna()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\drumlin\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\series.py", line 5872, in resample
return super().resample(
^^^^^^^^^^^^^^^^^
File "C:\Users\drumlin\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\generic.py", line 8858, in resample
return get_resampler(
^^^^^^^^^^^^^^
File "C:\Users\drumlin\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\resample.py", line 1544, in get_resampler
return tg._get_resampler(obj, kind=kind)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\drumlin\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\resample.py", line 1725, in _get_resampler
raise TypeError(
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'
Process finished with exit code 1
`
Any suggestions would be greatly appreciated!
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'
close = pd.Series(self.data.Close),
This resets all those passed series to a simple RangeIndex. Instead use e.g. self.data.Close.s
accessor to obtain data-indexed Series (i.e. pd.Series(self.data.Close, index=self.data.index)
).
Replies: 2 comments
-
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'
close = pd.Series(self.data.Close),
This resets all those passed series to a simple RangeIndex. Instead use e.g. self.data.Close.s
accessor to obtain data-indexed Series (i.e. pd.Series(self.data.Close, index=self.data.index)
).
Beta Was this translation helpful? Give feedback.
All reactions
-
Thank you for the reply and for your suggestion!
I am sorry for not replying sooner, but this tool is great, and I've been playing around with it trying to understand it better.
On top of that, I think I am starting to understand python a little more as well, so I greatly appreciate the help!
Your suggestion not only helped but also reminded me to look at the documentation, which is really pretty detailed, once I understood things a little more.
I implemented things in a slightly different manner, but it works:
`
from backtesting import Backtest, Strategy
from backtesting.lib import crossover
from backtesting.lib import resample_apply
import pandas as pd
import pandas_ta as ta
def isLastDay(dt):
today = pd.to_datetime(dt.index[-2]).weekday()
tomorrow = pd.to_datetime(dt.index[-1]).weekday()
if today == 4:
return True
elif today == 3 and tomorrow != 4:
return True
elif today == 2 and tomorrow == 0:
return True
else:
return False
def MyIndicator(data):
length = 7
multiplier = 3
supertrend = ta.supertrend(high=data.High, low=data.Low, close=data.Close, length=length, multiplier=multiplier)
return supertrend.to_numpy().T
class MyST(Strategy):
def init(self):
high = pd.Series(self.data.High)
low = pd.Series(self.data.Low)
close = pd.Series(self.data.Close)
self.weekly_st = resample_apply('W-FRI', MyIndicator, self.data.df, plot=True, overlay = True)
def next(self):
trend = self.weekly_st[0]
if isLastDay(self.data):
if self.position:
if self.data.Close[-2] < trend[-2]:
self.position.close()
else:
if self.data.Close[-2] > trend[-2]:
self.buy()
df = pd.read_csv('..\BTbaseline\SPY.csv', index_col=0, parse_dates=True, infer_datetime_format=True)
bt = Backtest(df, MyST,
cash=100000, commission=0,
exclusive_orders=True)
stats = bt.run()
print(stats)
bt.plot()
`
Don't laugh to hard at the clumsy, code, I'm still learning.
I'm still trying to work out some stuff, but in general, I think I have a start.
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions
-
🚀 1