Created
August 1, 2020 09:13
-
-
Save yuyasugano/88841812a48bfe48977bdbe0076d37dc to your computer and use it in GitHub Desktop.
backtesting.py ema strategy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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
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?