Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Attempting to get stochastic indicator working but getting error message #932

Unanswered
cgdutoit asked this question in Q&A
Discussion options

Hello -

Using the example code in the documentation, I've successfully created strategies such as a SMA crossover or RSI crossover, for example:

# Do as much initial computation as possible
def init(self):
 self.rsi = self.I(ta.rsi, pd.Series(self.data.Close), self.rsi_window)
# Step through bars one by one
# Note that multiple buys are a thing here
def next(self):
 if crossover(self.rsi, self.upper_bound):
 self.position.close()
 elif crossover(self.lower_bound, self.rsi):
 self.buy()

That works great.

However, I seem to be unable to create one based on the Stochastic oscillator and I'm getting a "Indicators must return (optionally a tuple of) numpy.arrays of same length as data " error message.

Here is my strategy:

class StochOsc(Strategy):
upper_bound = 70
lower_bound = 30
window = 14
# Do as much initial computation as possible
def init(self):
 self.stoch = self.I(ta.stoch, pd.Series(self.data.High), pd.Series(self.data.Low), pd.Series(self.data.Close),
 k=self.window,d=self.window,smooth_k=self.window)
# Step through bars one by one
def next(self):
 if crossover(self.stoch, self.upper_bound):
 self.position.close()
 elif crossover(self.lower_bound, self.stoch):
 self.buy()# Do as much initial computation as possible

I then execute my strategy:

`bt = Backtest(price, StochOsc, cash=10_000, commission=.002)

stats = bt.optimize(upper_bound=range(65, 95, 1),
lower_bound=range(25,35,1),
maximize=optim_func,
constraint=lambda param: param.lower_bound < param.upper_bound)`

Upon executing the code in init it throws the above error.

I can't seem to find any examples of using ta.stoch with backtesting.py so any help would be appreciated. I can't figure out a solution based on that error message.

You must be logged in to vote

Replies: 0 comments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
1 participant

AltStyle によって変換されたページ (->オリジナル) /