Created
October 20, 2016 14:55
-
-
Save ericyue/b33e88a651adea5804922dbf2b0545ce to your computer and use it in GitHub Desktop.
wentao-sma.py
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
import sys,os | |
import datetime | |
from pyalgotrade import bar | |
from pyalgotrade import strategy | |
from pyalgotrade import plotter | |
from pyalgotrade.technical import vwap,ma,cumret,cross | |
from pyalgotrade.barfeed import csvfeed | |
from pyalgotrade.bitstamp import broker | |
from pyalgotrade import broker as basebroker | |
from pyalgotrade.stratanalyzer import sharpe,drawdown,returns,trades | |
import run_info | |
from utils.logger import backtesting_logger as logger | |
class SMACrossStrategy(strategy.BacktestingStrategy): | |
def __init__(self, feed, instrument, smaPeriod1, smaPeriod2, money): | |
super(SMACrossStrategy, self).__init__(feed, money) | |
self.__position = None | |
self.__instrument = instrument | |
self.__sma1 = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod1) | |
self.__sma2 = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod2) | |
def onEnterOk(self, position): | |
execInfo = position.getEntryOrder().getExecutionInfo() | |
self.info("BUY share %f at $%.2f" % (position.getEntryOrder().getQuantity(), execInfo.getPrice())) | |
def onEnterCanceled(self, position): | |
self.__position = None | |
def onExitOk(self, position): | |
execInfo = position.getExitOrder().getExecutionInfo() | |
self.info("SELL share %f at $%.2f" % (position.getEntryOrder().getQuantity(), execInfo.getPrice())) | |
self.__position = None | |
def onExitCanceled(self, position): | |
self.__position.exitMarket() | |
def onBars(self, bars): | |
bar = bars[self.__instrument] | |
if self.__sma1[-1] is None or self.__sma2[-1] is None: | |
return | |
if self.__position is not None: | |
if not self.__position.exitActive() and cross.cross_below(self.__sma1, self.__sma2) > 0: | |
self.__position.exitMarket() | |
if self.__position is None: | |
if cross.cross_above(self.__sma1, self.__sma2) > 0 : | |
shares = self.getBroker().getEquity() * 1.0 / bars[self.__instrument].getPrice() | |
self.__position = self.enterLong(self.__instrument, shares, True) | |
if __name__ == "__main__": | |
try: | |
input_fn = sys.argv[1] | |
except: | |
input_fn = "./data/okcoinCNY.csv.resample.since201605.csv.output.csv.1min" | |
print("input: %s" % input_fn) | |
instrument = "BTC" | |
initialCash = 100000 | |
barFeed = csvfeed.GenericBarFeed(bar.Frequency.MINUTE, maxLen = 2000000) | |
barFeed.addBarsFromCSV(instrument, input_fn) | |
strat = SMACrossStrategy(barFeed, instrument, 10, 30, initialCash) | |
run_info.run_and_stat(strat, barFeed) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment