Skip to content

Instantly share code, notes, and snippets.

@yuyasugano
Created August 1, 2020 09:13
Show Gist options
  • Save yuyasugano/88841812a48bfe48977bdbe0076d37dc to your computer and use it in GitHub Desktop.
Save yuyasugano/88841812a48bfe48977bdbe0076d37dc to your computer and use it in GitHub Desktop.
backtesting.py 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.data.Close, self.n1)
self.ema2 = self.I(EMA_Backtesting, self.data.Close, self.n2)
def next(self):
# If ema1 crosses above ema2, buy the asset
if crossover(self.ema1, self.ema2):
self.position.close()
self.buy()
# Else, if ema1 crosses below ema2, sell it
elif crossover(self.ema2, self.ema1):
self.position.close()
self.sell()
@huytradingz
Copy link

huytradingz commented Jul 24, 2023

Hey there, I don't know if you see this but if you do, would you mind if I ask what does self.position.close() actually do when called versus when not?

@yuyasugano
Copy link
Author

@huytradingz Sorry for delay. I did not notice this messsage was posted. That means to close the current position. For example, if you have your positions buy or sell that those haven't been settled, this does just close the positions before creating new buys and sells. Please refer to the official page Class Position. https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#gsc.tab=0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment