def test_exponential_moving_average(self): indicator_ema = RSI(window=10, alpha=0.99) indicator = RSI(window=10, alpha=None) prices = np.concatenate((np.linspace(1, 5, 20)[::-1], np.linspace(1, 5, 20)), axis=0) indicator.step(price=0) for price in prices: indicator.step(price=price) indicator_ema.step(price=price) indicator_value = indicator.value indicator_ema_value = indicator_ema.value print("indicator_value: {:.6f} | ema: {:.6f}".format(indicator_value, indicator_ema_value)) self.assertNotAlmostEqual(indicator_value, indicator_ema_value, msg='indicator_value is {} and should be {}'.format( indicator_value, indicator_ema_value)) self.assertNotAlmostEqual(1., indicator_ema_value, msg='indicator_ema_value is {} and should be {}'.format( indicator_ema_value, 1.)) self.assertAlmostEqual(1., indicator_value, msg='indicator_value is {} and should be {}'.format( indicator_value, 1.))
def test_rsi_down(self): indicator = RSI(window=10) prices = np.linspace(1, 5, 50)[::-1] indicator.step(price=0) for price in prices: indicator.step(price=price) indicator_value = indicator.value self.assertEqual(float(-1), indicator_value, msg='indicator_value is {} and should be {}'.format( indicator_value, float(-1)))
def __init__(self, start_date, end_date, initial_position, market, params, h5file=None): Strategy.__init__(self, start_date, end_date, initial_position, market, params, h5file) for symbol in initial_position.keys(): if symbol == "$": continue self.addIndicator(symbol, "value", SimpleValue()) try: short = params['short'] except KeyError: short = Trending.DEF_SHORT_DAYS self.addIndicator(symbol, "short", EMA(short)) try: long_ = params['long'] except KeyError: long_ = Trending.DEF_LONG_DAYS self.addIndicator(symbol, "long", EMA(long_)) try: rsi = params['rsi'] except KeyError: rsi = Trending.DEF_RSI_PERIOD self.addIndicator(symbol, "rsi", RSI(rsi)) # Backfill the indicators try: backfill = params['backfill'] except KeyError: backfill = long_ d = start_date - (backfill * ONE_DAY) self.updateIndicators(d, start_date)
def test_manager_ema(self): manager = IndicatorManager() alpha = [0.99, 0.999, 0.9999] windows = [5, 15] for window in windows: manager.add((f'RSI_{window}', RSI(window=window, alpha=alpha))) data_set = np.cumsum(np.random.rand(1000) - 0.45) * 10. for i, data in enumerate(data_set): manager.step(price=data) if i < max(windows) + 1: continue tmp = np.asarray(manager.get_value()) print(f"tmp.shape -> {tmp.shape}") self.assertIsNot(tmp.min(), np.nan, msg=f'ERROR: NAN number in tmp: P{tmp}') for i, window in enumerate(windows): print(f"window[{window}]\t= {tmp[i]}") print("Done.")
reportSignals.SetStockCode(args.stockCode) # Get stock data # ##################################################### stockAssets = StockAssets() stockData = StockData(args.stockCode, start_date, end_date) stockData.SetAssets(stockAssets) stockData.SetCurrencySymbol(info.GetCurrency()) # Create oscillators/indicators # ##################################################### closePriceTotal = stockData.GetAllData('Close') closePrice = stockData.GetData('Close') alligator = CreateWilliamsAlligator(closePrice) macd = CreateMACD(closePrice) rsi = RSI(closePrice) cci = CreateCCI(stockData.GetData('High'), stockData.GetData('Low'), stockData.GetData('Close')) stoch = CreateStoch(stockData.GetData('High'), stockData.GetData('Low'), stockData.GetData('Close')) bollinger = CreateBollinger(closePrice) atr = CreateATR(stockData.GetData('High'), stockData.GetData('Low'), stockData.GetData('Close')) dmi = CreateDMI(stockData.GetData('High'), stockData.GetData('Low'), atr.GetAtr()) ichimoku = Ichimoku(stockData.GetData('Open'), stockData.GetData('High'), stockData.GetData('Low'), stockData.GetData('Close')) zigzag = ZigZag(stockData.GetData('Open'), stockData.GetData('High'), stockData.GetData('Low'), stockData.GetData('Close')) if (stockData.hasVolume()): mfi = CreateMoneyFlowIndex(stockData.GetData('High'),
def main(ticker): """engine to run script""" TIME_DEBUG = 0 MAX_ITER_DEBUG = 1000 CONTROL_BOUGHT = None CONTROL_SALE = None CONTROL_BEGIN = None CONTROL_END = None market_data_client = MarketDataClient('data/stooq_hourly/wmt.us.txt', ticker) market_data_stream = MarketDataStream(STREAM_PERIOD) portfolio = Portfolio([ticker]) decision_client = AlgoSignals() try: for _ in range(WARMUP_DATA_COUNT): # saturate the stream tick_data = market_data_client.get_parsed_tick_data() market_data_stream.update( tick_data['open'], tick_data['high'], tick_data['low'], tick_data['close']) CONTROL_BEGIN = tick_data['date'] CONTROL_BOUGHT = tick_data['open'] sma = SimpleMovingAverage() stochk = StochasticOscillatorK() stochd = StochasticOscillatorD() stochdslow = StochasticOscillatorD() rsi = RSI(market_data_stream.open, market_data_stream.close) while True: tick_data = market_data_client.get_parsed_tick_data() market_data_stream.update( tick_data['open'], tick_data['high'], tick_data['low'], tick_data['close']) sma.calc(market_data_stream.close) stochk.calc(market_data_stream.high, market_data_stream.low, market_data_stream.close) stochd.calc(stochk) stochdslow.calc(stochd) rsi.calc(market_data_stream.open, market_data_stream.close) if ( sma.saturated() and stochk.saturated() and stochd.saturated() and rsi.saturated() ): # ASSET TRANSACTION LOGIC, THIS CUSTOM LOGIC ENSURES # THAT BUYING AND SELLING CANNOT HAPPEN AT THE SAME TIME # this is changeable decision = decision_client.buy( portfolio, market_data_client.ticker, market_data_stream.close.curr(), rsi, stochk, stochd) TIME_DEBUG += 1 MAX_ITER_DEBUG -= 1 if decision['make_transaction']: print 'Buying {} at {} after {} ticks'.format( decision['amount'], decision['price'], TIME_DEBUG) TIME_DEBUG = 0 print portfolio.cash print sma print stochk print stochd print stochdslow print rsi portfolio.purchase( market_data_client.ticker, decision['amount'], decision['price']) #input('Press enter to continue: ') continue decision = decision_client.sell( portfolio, market_data_client.ticker, market_data_stream.close.curr(), rsi, stochk, stochd) if decision['make_transaction']: print 'Selling {} at {} after {} ticks'.format( decision['amount'], decision['price'], TIME_DEBUG) portfolio.sale(ticker, decision['amount'], decision['price']) print 'cash at hand: {}'.format(portfolio.cash) TIME_DEBUG = 0 #input('Press enter to continue: ') if portfolio.cash < 0: raise Exception('wtf, you really messed up') if MAX_ITER_DEBUG < 0: CONTROL_END = tick_data['date'] raise IndexError('normal') CONTROL_SALE = tick_data['close'] except IndexError: # terrible hack to know when we reach end of file print 'BOUGHT AT {}, SOLD AT {}'.format(CONTROL_BOUGHT, CONTROL_SALE) print 'from {} to {}'.format(CONTROL_BEGIN, CONTROL_END)