Ejemplo n.º 1
0
    def __init__(self, feed, instrument):
        strategy.BacktestingStrategy.__init__(self, feed)
        self.__rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 14)
        self.__rsi6 = rsi.RSI(feed[instrument].getCloseDataSeries(), 6)

        self.__instrument = instrument
        self.__position = None
        self.getBroker()
Ejemplo n.º 2
0
    def __init__(self, feed, instrument, entrySMA, exitDays, rsiPeriod,
                 overBoughtThreshold, overSoldThreshold):
        super(TestStrat, self).__init__(feed, cash_or_brk=100000)
        self.exitDays = exitDays

        self.STRATNAME = "RSI_oversold"

        self.__instrument = instrument
        # We'll use adjusted close values, if available, instead of regular close values.
        if feed.barsHaveAdjClose():
            self.setUseAdjustedValues(True)

        #self.__priceDS = feed[self.__instrument].getPriceDataSeries()
        self.__priceDS = self.getFeed().getDataSeries(
            self.__instrument).getPriceDataSeries()

        #self.__Ds = self.getFeed().getDataSeries(self.__instrument).getCloseDataSeries()

        #self.__closeDS = feed[instrument].

        self.__entrySMA = ma.SMA(self.__priceDS, entrySMA)
        #self.__exitSMA = ma.SMA(self.__priceDS, exitSMA)

        self.__rsi = rsi.RSI(self.__priceDS, rsiPeriod)
        #self.__rsi = RSI(self.__Ds, rsiPeriod) # CARL

        #self.Cad = talibext.indicator.AD(self.__priceDS,20 ) #     Chaikin A/D Line

        #self.ADX = talibext.indicator.ADX(self.__priceDS, 20, ) # ADX

        self.__overBoughtThreshold = overBoughtThreshold
        self.__overSoldThreshold = overSoldThreshold
        self.__longPos = None
        self.__shortPos = None
        self.getBroker().getFillStrategy().setVolumeLimit(None)  # hack / CARL
Ejemplo n.º 3
0
 def __init__(self, feed, instrument, arg_set, ma_short=5, ma_long=10, rsi_in=6, rsi_out=12):
     broker_commission = broker.backtesting.TradePercentage(0.0004)
     brokers = broker.backtesting.Broker(1000000, feed, broker_commission)
     super(Ma_Rsi, self).__init__(feed, brokers)
     self.__instrument = instrument
     self.__feed = feed
     # self.setUseAdjustedValues(True)
     self.__position = None
     self.initState = False  # 开头的几个过滤掉
     self.code = feed.getKeys()[0]
     self.priceDS = feed[instrument].getPriceDataSeries()
     self.arg_set = arg_set
     self.ma_short = ma.SMA(self.priceDS, ma_short)
     self.ma_long = ma.SMA(self.priceDS, ma_long)
     self.rsi_in = rsi.RSI(self.priceDS, rsi_in)
     self.rsi_out = rsi.RSI(self.priceDS, rsi_out)
 def __init__(self, feed, instrument, cash):
     strategy.BacktestingStrategy.__init__(self, feed, cash)
     self.__rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 14)
     self.__sma = ma.SMA(self.__rsi, 15)
     self.__instrument = instrument
     self.__EMA = tf.EMA(feed[instrument].getCloseDataSeries(), 16, .3)
     self.__DT = tf.Derivative(feed[instrument])
Ejemplo n.º 5
0
    def __init__(self, feed, instrument, hurstPeriod, macdShorterPeriod,
                 macdLongerPeriod, macdSignalPeriod, rsiPeriod, entrySMAPeriod,
                 exitSMAPeriod, overBoughtThreshold, overSoldThreshold):
        strategy.BacktestingStrategy.__init__(self, feed)

        self.__instrument = instrument
        self.__hurstPeriod = hurstPeriod

        # Use adjusted close values, if available, instead of regular close values.
        if feed.barsHaveAdjClose():
            self.setUseAdjustedValues(True)
        self.__priceDS = feed[instrument].getPriceDataSeries()
        self.__adjClose = feed[instrument].getAdjCloseDataSeries()

        self.__macdShorterPeriod = macdShorterPeriod
        self.__macdLongerPeriod = macdLongerPeriod
        self.__macdSignalPeriod = macdSignalPeriod
        self.__macd = macd.MACD(self.__adjClose, self.__macdShorterPeriod,
                                self.__macdLongerPeriod,
                                self.__macdSignalPeriod)

        self.__hurst = MovingHurst.HurstExponent(self.__adjClose, hurstPeriod)

        self.__entrySMA = ma.EMA(self.__priceDS, entrySMAPeriod)
        self.__exitSMA = ma.EMA(self.__priceDS, exitSMAPeriod)

        self.__rsi = rsi.RSI(self.__adjClose, rsiPeriod)
        self.__overBoughtThreshold = overBoughtThreshold
        self.__overSoldThreshold = overSoldThreshold

        self.__longPos = None
        self.__shortPos = None
Ejemplo n.º 6
0
    def __init__(self,feed,instruments,ind_dt,ts):
        strategy.BacktestingStrategy.__init__(self,feed,cash_or_brk=200)

        self.__position  = [] 
        self.__intrapost = dict()

        self.__instruments = instruments
        self.__ts          = ts
        self.__ydate       = '' 

        self.lastday = dict()
        self.df      = pd.read_csv(ind_dt,dtype={'code':np.str})
        self.tdays   = np.array(self.df['Date'].unique())
        
        self.__prices = feed.getDataSeries(self.__instruments)
        self.__KDJ = stoch.StochasticOscillator(self.__prices,9)

        rsiPeriod = 6
        self.__priceDS = feed[self.__instruments].getPriceDataSeries()
        self.__rsi = rsi.RSI(self.__priceDS, rsiPeriod)

        self.__PK = None
        self.__PD = None
        self.__fakeShares = 0

        self.__prevJ = None
        self.__buydays = set() 
        
        self.getBroker().setMaxHoldingDays(2)
Ejemplo n.º 7
0
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed)
        self.__rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 14)
        self.__sma_rsi = ma.SMA(self.__rsi, 15)
        self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 2)
        # self.info("__sma: {}, {}.".format(self.__sma, self.__sma[-1]))

        self.__instrument = instrument
Ejemplo n.º 8
0
 def __init__(self, feed, instrument):
     super(MyStrategy, self).__init__(feed)
     self.__rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 14)
     # 5 period sma over closing price
     self.__sma5 = ma.SMA(self.__rsi, 5)
     # 15 period sma over closing price
     self.__sma15 = ma.SMA(self.__rsi, 15)
     self.__instrument = instrument
Ejemplo n.º 9
0
 def __init__(self, feed, instrument):
     strategy.BacktestingStrategy.__init__(self, feed)
     # We want a 15 period SMA over the closing prices.
     self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 15)
     self.__rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 14)
     self.__macd = macd.MACD(feed[instrument].getCloseDataSeries(), 12, 55,
                             9).getSignal()
     self.__instrument = instrument
Ejemplo n.º 10
0
    def __init__(self, feed, brk):
        config = ConfigParser.ConfigParser()
        config.read('xrpbot.cfg')
        strategy.BaseStrategy.__init__(self, feed, brk)
        self.__smaPeriod = int(config.get('main', 'sma_period'))
        self.__rsiPeriod = int(config.get('main', 'rsi_period'))
        self.__instrument = config.get('main', 'instrument')
        self.__prices = feed[self.__instrument].getCloseDataSeries()
        self.__sma = ma.SMA(self.__prices, self.__smaPeriod)
        self.__rsi = rsi.RSI(self.__prices, self.__rsiPeriod)
        self.__bid = None
        self.__ask = None
        self.__spread = None
        self.__position = None
        self.__posSize = float(config.get('main', 'position_size'))
        #self.__posSize = random.randint(45, 93)
        self.__strategyUUID = None
        self.__engine = config.get('main', 'engine_name')
        self.__start_time = time.time()
        self.__maxRunTime = int(config.get('main', 'runtime'))
        self.__logURL = "https://*****:*****@quantumconfigurations.com/dionysus/index.php?%s"
        self.__barsctr = 0
        self.__isShuttingDown = False
        self.__isExitActive = False
        self.__isOrderOpenActive = False
        self.__orderbookctr = 0
        self.__positionsctr_1 = 0
        self.__positionsctr_2 = 0
        self.__cmdTimer = time.time()
        self.__exitActiveTimer = 0
        self.__exitBid = 0
        self.__cmdTimerMax = int(config.get('main', 'command_run_interval'))
        self.__status = "RUNNING"
        self.__pos_type = "N"
        self.__last_pos_type = "N"

        initCtr = 0
        initMax = 5
        initDelay = 5

        while self.__strategyUUID == None and initCtr < initMax:
            self.initDB()

            if self.__strategyUUID == None:
                self.error("Strategy was not initialized, retry " +
                           str(initCtr))
                initCtr += initCtr
                time.sleep(initDelay)
            else:
                self.info("Strategy " + self.__strategyUUID +
                          " has been initialized.")

        if self.__strategyUUID == None:
            self.error("ERROR: Unable to initialize, shutting down")
            self.stop()
        else:
            # Subscribe to order book update events to get bid/ask prices to trade.
            feed.getOrderBookUpdateEvent().subscribe(self.__onOrderBookUpdate)
Ejemplo n.º 11
0
    def __init__(self, feed, instrument, brk):
        super(MyStrategy, self).__init__(feed, brk)
        logger.info("========MyStrategy init=======")
        self.__rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 14)
        self.__sma_rsi = ma.SMA(self.__rsi, 15)
        self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 2)
        logger.info("__sma: {}".format(self.__sma))

        self.__instrument = instrument
Ejemplo n.º 12
0
 def __init__(self, feed, feed2, instrument, instrument2, smaPeriod,
              rsiPeriod):
     super(MyStrategy, self).__init__(feed, 1000)
     self.__position = None
     self.__instrument = instrument
     # We'll use adjusted close values instead of regular close values.
     self.setUseAdjustedValues(True)
     self.__sma = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod)
     self.__rsi = rsi.RSI(feed[instrument].getPriceDataSeries(), rsiPeriod)
Ejemplo n.º 13
0
 def __init__(self, feed, instrument, bBandsPeriod, overBoughtThreshold,
              overSoldThreshold):
     super(BBands, self).__init__(feed)
     self.__instrument = instrument
     self.__bbands = bollinger.BollingerBands(
         feed[instrument].getCloseDataSeries(), bBandsPeriod, 2)
     self.__rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 14)
     self.overBoughtThreshold = overBoughtThreshold
     self.overSoldThreshold = overSoldThreshold
 def __init__(self, feed, entrySMA, exitSMA, rsiPeriod, overBoughtThreshold, overSoldThreshold):
     strategy.BacktestingStrategy.__init__(self, feed, 2000)
     ds = feed["dia"].getCloseDataSeries()
     self.__entrySMA = ma.SMA(ds, entrySMA)
     self.__exitSMA = ma.SMA(ds, exitSMA)
     self.__rsi = rsi.RSI(ds, rsiPeriod)
     self.__overBoughtThreshold = overBoughtThreshold
     self.__overSoldThreshold = overSoldThreshold
     self.__longPos = None
     self.__shortPos = None
Ejemplo n.º 15
0
	def __init__(self, feed, entrySMA, exitSMA, rsiPeriod, overBoughtThreshold, overSoldThreshold):
		initialCash = 2000
		strategy.Strategy.__init__(self, feed, initialCash)
		self.__instrument = feed.getDefaultInstrument()
		ds = feed.getDataSeries().getCloseDataSeries()
		self.__entrySMA = ma.SMA(ds, entrySMA)
		self.__exitSMA = ma.SMA(ds, exitSMA)
		self.__rsi = rsi.RSI(ds, rsiPeriod)
		self.__overBoughtThreshold = overBoughtThreshold
		self.__overSoldThreshold = overSoldThreshold
		self.__longPos = None
		self.__shortPos = None
Ejemplo n.º 16
0
 def __init__(self, feed, instrument, capital, selected_features,
              predict_n_days, model_form, testing_datetime,
              testing_end_datetime):
     super(Backtester, self).__init__(feed, capital)
     self.capital = capital
     self.instrument = instrument
     self.mpf_asset = [
         'hk_equity_fund', 'growth_fund', 'balanced_fund',
         'conservative_fund', 'hkdollar_bond_fund', 'stable_fund'
     ]
     self.positions = {asset: None for asset in self.mpf_asset}
     self.current_percentages = None
     self.previous_percentages = None
     # technical indicators is denfined here
     self.hk_equity_fund_macd = macd.MACD(
         feed['hk_equity_fund'].getCloseDataSeries(), 12, 26, 9)
     self.hk_equity_fund_macd_histogram = self.hk_equity_fund_macd.getHistogram(
     )
     self.growth_fund_macd = macd.MACD(
         feed['growth_fund'].getCloseDataSeries(), 12, 26, 9)
     self.growth_fund_macd_histogram = self.growth_fund_macd.getHistogram()
     self.balanced_fund_macd = macd.MACD(
         feed['balanced_fund'].getCloseDataSeries(), 12, 26, 9)
     self.balanced_fund_macd_histogram = self.balanced_fund_macd.getHistogram(
     )
     self.conservative_fund_macd = macd.MACD(
         feed['conservative_fund'].getCloseDataSeries(), 12, 26, 9)
     self.conservative_fund_macd_histogram = self.conservative_fund_macd.getHistogram(
     )
     self.hkdollar_bond_fund_macd = macd.MACD(
         feed['hkdollar_bond_fund'].getCloseDataSeries(), 12, 26, 9)
     self.hkdollar_bond_fund_macd_histogram = self.hkdollar_bond_fund_macd.getHistogram(
     )
     self.stable_fund_macd = macd.MACD(
         feed['stable_fund'].getCloseDataSeries(), 12, 26, 9)
     self.stable_fund_macd_histogram = self.stable_fund_macd.getHistogram()
     self.hk_equity_fund_rsi = rsi.RSI(
         feed['hk_equity_fund'].getCloseDataSeries(), 14)
     self.growth_fund_rsi = rsi.RSI(
         feed['growth_fund'].getCloseDataSeries(), 14)
     self.balanced_fund_rsi = rsi.RSI(
         feed['balanced_fund'].getCloseDataSeries(), 14)
     self.conservative_fund_rsi = rsi.RSI(
         feed['conservative_fund'].getCloseDataSeries(), 14)
     self.hkdollar_bond_fund_rsi = rsi.RSI(
         feed['hkdollar_bond_fund'].getCloseDataSeries(), 14)
     self.stable_fund_rsi = rsi.RSI(
         feed['stable_fund'].getCloseDataSeries(), 14)
     # self.testing_datetime = datetime(2014, 8, 2)
     # self.testing_end_datetime = datetime(2018, 1, 15)
     self.testing_datetime = testing_datetime
     self.testing_end_datetime = testing_end_datetime
     self.pending_order = None
     self.historical_data = list()
     self.historical_df = None
     self.selected_features = selected_features
     self.predict_n_days = predict_n_days
     self.model_form = model_form
     self.model = None
Ejemplo n.º 17
0
 def __init__(self, feed, instrument, smaPeriod, factor1):
     super(MyStrategy, self).__init__(feed, 1000000)
     self.__position = None
     self.__instrument = instrument
     # We'll use adjusted close values instead of regular close values.
     self.setUseAdjustedValues(True)
     self.__sma = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod)
     self.__rsi = rsi.RSI(feed[instrument].getPriceDataSeries(), smaPeriod)
     self.__volsma = ma.SMA(feed[instrument].getVolumeDataSeries(),
                            smaPeriod)
     self.__vol = feed[instrument].getVolumeDataSeries()
     self.__chg = ma.SMA(
         feed[instrument].getExtraDataSeries(name="pct_chg"), 1)
Ejemplo n.º 18
0
 def __init__(self, feed, instruments, posMax, entrySma, exitSma, rsiPeriod,
              overSoldThreshold):
     MyBenchmark.__init__(self, feed, instruments, posMax, exitSma)
     self._overSoldThreshold = overSoldThreshold
     self._prices = {}
     self._entrySmas = {}
     self._exitSmas = {}
     self._rsis = {}
     for instrument in instruments:
         priceDS = feed[instrument].getPriceDataSeries()
         self._prices[instrument] = priceDS
         self._entrySmas[instrument] = ma.SMA(priceDS, entrySma)
         self._exitSmas[instrument] = ma.SMA(priceDS, exitSma)
         self._rsis[instrument] = rsi.RSI(priceDS, rsiPeriod)
Ejemplo n.º 19
0
 def __init__(self, feed, instrument, entrySMA, exitSMA, rsiPeriod,
              overBoughtThreshold, overSoldThreshold):
     strategy.BacktestingStrategy.__init__(self, feed)
     self.__instrument = instrument
     # We'll use adjusted close values instead of regular close values.
     self.setUseAdjustedValues(True)
     self.__priceDS = feed[instrument].getPriceDataSeries()
     self.__entrySMA = ma.SMA(self.__priceDS, entrySMA)
     self.__exitSMA = ma.SMA(self.__priceDS, exitSMA)
     self.__rsi = rsi.RSI(self.__priceDS, rsiPeriod)
     self.__overBoughtThreshold = overBoughtThreshold
     self.__overSoldThreshold = overSoldThreshold
     self.__longPos = None
     self.__shortPos = None
Ejemplo n.º 20
0
 def __init__(self, feed, instrument, entrySMA, exitSMA, rsiPeriod, overBoughtThreshold, overSoldThreshold):
     super(RSI2, self).__init__(feed)
     self.__instrument = instrument
     # We'll use adjusted close values, if available, instead of regular
     # close values.
     if feed.barsHaveAdjClose():
         self.setUseAdjustedValues(True)
     self.__priceDS = feed[instrument].getPriceDataSeries()
     self.__entrySMA = ma.SMA(self.__priceDS, entrySMA)
     self.__exitSMA = ma.SMA(self.__priceDS, exitSMA)
     self.__rsi = rsi.RSI(self.__priceDS, rsiPeriod)
     self.__overBoughtThreshold = overBoughtThreshold
     self.__overSoldThreshold = overSoldThreshold
     self.__longPos = None
     self.__shortPos = None
Ejemplo n.º 21
0
 def __init__(self, feed, instrument, bBandsPeriod):
     super(MyStrategy, self).__init__(feed)
     self.__instrument = instrument
     # 使用调整后的数据
     if feed.barsHaveAdjClose():
         self.setUseAdjustedValues(True)
     # 持有仓位
     self.__holdPosition = 0.0
     # 空闲仓位
     self.__emptyPosition = 10.0
     # 单元持仓金额
     self.__unit = self.getBroker().getCash(False) / 10
     # 统计收盘价
     self.__priceDS = feed[instrument].getPriceDataSeries()
     # 计算macd指标
     self.__macd = macd.MACD(self.__priceDS, 12, 26, 9)
     # 计算KD指标
     self.__stoch = stoch.StochasticOscillator(feed[instrument], 9, 3)
     # 计算rsi指标
     self.__rsi7 = rsi.RSI(self.__priceDS, 7)
     self.__rsi14 = rsi.RSI(self.__priceDS, 14)
     # 计算布林线
     self.__bbands = bollinger.BollingerBands(self.__priceDS, bBandsPeriod,
                                              2)
Ejemplo n.º 22
0
 def __init__(self, feed, instrument, entrySMA, exitSMA, rsiPeriod, overBoughtThreshold, overSoldThreshold):
     strategy.BacktestingStrategy.__init__(self, feed)
     self.__instrument = instrument
     if feed.barsHaveAdjClose():
         self.setUseAdjustedValues(True)
     self.__typicalPrice = feed[instrument].getAdjCloseDataSeries() 
     self.__volume = feed[instrument].getVolumeDataSeries()
      
     self.__entrySMA = ma.SMA(self.__priceDS, entrySMA)
     self.__exitSMA = ma.SMA(self.__priceDS, exitSMA)
     self.__rsi = rsi.RSI(self.__priceDS, rsiPeriod)
     self.__overBoughtThreshold = overBoughtThreshold
     self.__overSoldThreshold = overSoldThreshold
     self.__longPos = None
     self.__shortPos = None
     self.__MFI = None
Ejemplo n.º 23
0
    def __init__(self, feed, smaPeriod, tickers, trend_indicator):
        global LOWERLIMIT
        strategy.Strategy.__init__(self, feed, 2000)
        self.tickers = tickers
        self.period = smaPeriod
        self.trend_indi = trend_indicator
        self.trend_data = {}
        self.positions = []
        self.p_tickers = set()
        #self.getBroker().setCommission(FixedCommission(9))
        self.failed = {}
        no_data = set()
        self.last_price = {}
        if LOWERLIMIT >= len(tickers):
            LOWERLIMIT = int(len(tickers) * .5)
        max_date = min_date = None
        import datetime
        now = datetime.datetime.now()
        start = now - datetime.timedelta(days=90)

        for ticker in tickers:
            data = du.get_data(ticker)
            if len(data) <= 0:
                no_data.add(ticker)
                continue
            feed.addBarsFromCSV(ticker, mongofeed.MongoRowParser())
            if max_date == None:
                max_date = data[-1]['date']
            elif max_date < data[-1]['date']:
                max_date = data[-1]['date']

            if min_date == None:
                min_date = data[0]['date']
            elif min_date > data[0]['date']:
                min_date = data[0]['date']
            self.trend_data[ticker] = rsi.RSI(
                feed.getDataSeries(ticker).getAdjCloseDataSeries(), smaPeriod)
        print 'start: %r end: %r' % (min_date, max_date)
        print 'No Data: %r' % no_data
        metrics.start_date = min_date
        metrics.end_date = max_date
        metrics.num_transactions = 0
        self.start_month = min_date
Ejemplo n.º 24
0
 def __init__(self, feed, instrument, entrySMA, exitSMA, rsiPeriod,
              overBoughtThreshold, overSoldThreshold):
     super(pyAlgoRSI, self).__init__(feed)
     self.__instrument = instrument
     # We'll use adjusted close values, if available, instead of regular close values.
     if feed.barsHaveAdjClose():
         self.setUseAdjustedValues(True)
     self.__priceDS = feed[instrument].getPriceDataSeries()
     self.__entrySMA = ma.SMA(self.__priceDS, entrySMA)
     self.__exitSMA = ma.SMA(self.__priceDS, exitSMA)
     self.__rsi = rsi.RSI(self.__priceDS, rsiPeriod)
     self.__overBoughtThreshold = overBoughtThreshold
     self.__overSoldThreshold = overSoldThreshold
     self.__longPos = None
     self.__shortPos = None
     self.__col = [
         "buyPrice", "buyTime", "sellPrice", "sellTime", "returns"
     ]
     self.__msdf = pd.DataFrame(columns=self.__col)
    def __init__(self, feed, instrument, fastPeriod, slowPeriod, rsiPeriod,
                 overboughtThreshold, oversoldThreshold):
        # define the initial budget
        super(RSIMovingAverageStrategy, self).__init__(feed, INITIAL_BUDGET)
        # track the position

        self.longPosition = None
        self.shortPosition = None
        self.oversoldThreshold = oversoldThreshold
        self.overboughtThreshold = overboughtThreshold

        self.instrument = instrument
        # adjusted closing prices instead of regular closing prices
        self.setUseAdjustedValues(True)
        #fast MA indicator
        self.fastMA = ma.SMA(feed[instrument].getPriceDataSeries(), fastPeriod)
        #slow MA indicator
        self.slowMA = ma.SMA(feed[instrument].getPriceDataSeries(), slowPeriod)
        # RSI model
        self.rsi = rsi.RSI(feed[instrument].getPriceDataSeries(), rsiPeriod)
Ejemplo n.º 26
0
 def __init__(self, feed, instrument, fastPeriod, slowPeriod, rsiPeriod,
              overboughtThreshold, oversoldThreshold):
     #this is where we have to define the initial budget
     super(RSIMovingAverageStrategy, self).__init__(feed, INITIAL_BUDGET)
     #we can track the position: long or short positions
     #if it is None we know we can open one
     self.longPosition = None
     self.shortPosition = None
     self.oversoldThreshold = oversoldThreshold
     self.overboughtThreshold = overboughtThreshold
     #the given stock (for example AAPL)
     self.instrument = instrument
     #if we want to use adjusted closing prices instead of regular closing prices
     self.setUseAdjustedValues(True)
     #fast moving average indicator (short-term trend) period is smaller
     self.fastMA = ma.EMA(feed[instrument].getPriceDataSeries(), fastPeriod)
     #slow moving average indicator (long-term trend) period is larger
     self.slowMA = ma.EMA(feed[instrument].getPriceDataSeries(), slowPeriod)
     #define the RSI model
     self.rsi = rsi.RSI(feed[instrument].getPriceDataSeries(), rsiPeriod)
Ejemplo n.º 27
0
 def __init__(self, feed, companyID, smaPeriod, rsiPeriod, invest_amount):
     strategy.BacktestingStrategy.__init__(self, feed, invest_amount)
     self.__sma = ma.SMA(
         feed.getDataSeries(companyID).getCloseDataSeries(), smaPeriod)
     self.__sma60 = ma.SMA(
         feed.getDataSeries(companyID).getCloseDataSeries(), 60)
     self.__sma90 = ma.SMA(
         feed.getDataSeries(companyID).getCloseDataSeries(), 90)
     self.__rsi = rsi.RSI(
         feed.getDataSeries(companyID).getCloseDataSeries(), rsiPeriod)
     self.__bbands = bollinger.BollingerBands(
         feed[companyID].getCloseDataSeries(), bBandsPeriod, 2)
     self.__position = None
     self.__boxFloor = 1000
     self.__boxCeiling = 0
     self.__cmpID = companyID
     self.__amount = invest_amount
     self.__strengthIndex = None
     self.__discount = None
     self.__fee = 0
     self.__lastStatus = False
     self.__cross_lower = 0
     self.__buyin_price = 0
Ejemplo n.º 28
0
 def __init__(self, feed, instrument, nper):
     super(RSIStrategy, self).__init__(feed)
     self.position = None
     self.instrument = instrument
     self.rsi = rsi.RSI(feed[instrument].getPriceDataSeries(), nper)
Ejemplo n.º 29
0
 def testStockChartsRSI(self):
     # Test data from http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:relative_strength_in
     common.test_from_csv(self, "rsi-test.csv",
                          lambda inputDS: rsi.RSI(inputDS, 14), 3)
Ejemplo n.º 30
0
 def __buildRSI(self, values, period, rsiMaxLen=None):
     seqDS = dataseries.SequenceDataSeries()
     ret = rsi.RSI(seqDS, period, rsiMaxLen)
     for value in values:
         seqDS.append(value)
     return ret