Skip to content

Instantly share code, notes, and snippets.

What would you like to do? ema strategy
from backtesting import Strategy
from backtesting.lib import crossover
def EMA_Backtesting(values, n):
Return exponential moving average of `values`, at
each step taking into account `n` previous values.
close = pd.Series(values)
return talib.EMA(close, timeperiod=n)
class EmaCrossStrategy(Strategy):
# Define the two EMA lags as *class variables*
# for later optimization
n1 = 5
n2 = 10
def init(self):
# Precompute two moving averages
self.ema1 = self.I(EMA_Backtesting,, self.n1)
self.ema2 = self.I(EMA_Backtesting,, self.n2)
def next(self):
# If ema1 crosses above ema2, buy the asset
if crossover(self.ema1, self.ema2):
# Else, if ema1 crosses below ema2, sell it
elif crossover(self.ema2, self.ema1):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment