def backtest_exit(self, current_position, data): try: self.condictions_state_backtest = { 'buy': { 'ema': False, }, 'sell': { 'ema': False, } } if len(data.date) > max(self.ema_1_period, self.ema_2_period): data['ema_1'] = ema(list(data.bidclose), self.ema_1_period) data['ema_2'] = ema(list(data.bidclose), self.ema_2_period) if current_position == 'buy': if ((data.ema_1.iloc[-1] > data.ema_2.iloc[-1])): self.condictions_state_backtest['sell']['ema'] = True self.condictions_state_backtest['buy']['ema'] = False return 'exit' elif current_position == 'sell': if ((data.ema_1.iloc[-1] < data.ema_2.iloc[-1])): self.condictions_state_backtest['buy']['ema'] = True self.condictions_state_backtest['sell']['ema'] = False return 'exit' else: self.condictions_state_backtest['buy']['ema'] = False self.condictions_state_backtest['sell']['ema'] = False return None else: return None except: return None
def ma(data: list, data_properties: dict, ma_type: int = 0) -> dict: """ Strategy for moving averages. :param data: list[numeric] :param data_properties: dict :param ma_type: Moving Average Type SMA = 0 (Default case) EMA = 1 :return: dict Result from strategy_builder """ close = data_parser.get_close(data) if ma_type == 1: ma50 = indicators.ema(close, period=50) ma200 = indicators.ema(close, period=200) else: ma50 = indicators.sma(close, period=50) ma200 = indicators.sma(close, period=200) buy = Condition(data1=ma50, data2=ma200, operation=Operation.CROSSOVER) sell = Condition(data1=ma50, data2=ma200, operation=Operation.CROSSUNDER) chart_1 = ChartElement(data=ma50, label="ma50", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS) chart_2 = ChartElement(data=ma200, label="ma200", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS) charts = [chart_1, chart_2] result = strategy_builder(data_properties=data_properties, data_list=data, strategy=BUY, buy=buy, sell=sell, charts=charts) return result
def _candle_indicators(): # with dpg.collapsing_header(label='indicators'): indicators.rlines() indicators.sma() indicators.ema() indicators.rsi() indicators.bbands()
def setup(self, client=None): tod = datetime.today() fromdt = (tod - timedelta(days=120)).date() todt = (tod - timedelta(days=1)).date() nifty = client.get_instrument_by_symbol('nse_index', N50_SYMBOL) ohlc_arr = self._get_ohlc(client, nifty, fromdt, todt) import csv with open('nifty_ohlc_sample.csv', 'w') as cfile: fields = ['timestamp', 'open', 'high', 'low', 'close'] writer = csv.DictWriter(cfile, fieldnames=fields) writer.writeheader() for ohlc in ohlc_arr: row = { 'timestamp': ts_to_datetime(ohlc['timestamp']).strftime('%d-%m-%Y'), 'open': ohlc['open'], 'high': ohlc['high'], 'low': ohlc['low'], 'close': ohlc['close'] } writer.writerow(row) for i, ohlc in enumerate(ohlc_arr): if i <= SLOW_EMA + 1: continue ema_3 = [] ema_5 = [] ema_3 = (ema(ohlc_arr[i - FAST_EMA - 2:i - 1], n=FAST_EMA, seed=None), ema(ohlc_arr[i - FAST_EMA - 1:i], n=FAST_EMA, seed=None)) ema_5 = (ema(ohlc_arr[i - SLOW_EMA - 2:i - 1:], n=SLOW_EMA, seed=None), ema(ohlc_arr[i - SLOW_EMA - 1:i], n=SLOW_EMA, seed=None)) cross = self._check_crossover(ema_3, ema_5) if cross is not None: d = ts_to_datetime(ohlc['timestamp']).date() self.logger.debug('Crossover on %s. Direction = %s' % (d.strftime('%d-%m-%Y'), cross)) self.logger.debug('3 EMAs = %.2f | %.2f' % (ema_3[0], ema_3[1])) self.logger.debug('5 EMAs = %.2f | %.2f' % (ema_5[0], ema_5[1])) self.logger.debug('-------------------------------\n')
def backtest_entry(self, data): try: self.condictions_state_backtest = { 'buy': { 'ema': False, }, 'sell': { 'ema': False, } } if len(data.date) > max(self.ema_1_period, self.ema_2_period): data['ema_1'] = ema(list(data.bidclose), self.ema_1_period) data['ema_2'] = ema(list(data.bidclose), self.ema_2_period) if ((data.ema_1.iloc[-1] > data.ema_2.iloc[-1])): self.condictions_state_backtest['sell']['ema'] = True self.condictions_state_backtest['buy']['ema'] = False elif ((data.ema_1.iloc[-1] < data.ema_2.iloc[-1])): self.condictions_state_backtest['buy']['ema'] = True self.condictions_state_backtest['sell']['ema'] = False else: self.condictions_state_backtest['buy']['ema'] = False self.condictions_state_backtest['sell']['ema'] = False self.required_score collected_score_buy = 0 collected_score_sell = 0 for k, v in self.conditions_weights.items(): if self.condictions_state_backtest['buy'][k] == True: collected_score_buy += v elif self.condictions_state_backtest['sell'][k] == True: collected_score_sell += v if collected_score_buy >= self.required_score: return 'buy' elif collected_score_sell >= self.required_score: return 'sell' else: return None else: return None except Exception as e: print(e, 11111111111111) return None
def short_close(data_open, data_close): current_price = 0.0 ema_thirty_close = ind.ema(data_close, 30) ema_close = ind.ema(data_close, 9) ema_open = ind.ema(data_open, 9) boolean = False logging.info('9Ema: {} - 30Ema: {}'.format(ema_close, ema_thirty_close)) if (ema_close > ema_thirty_close) and (ema_open < ema_thirty_close): boolean = True logging.info('Short close: {}'.format(boolean)) return boolean
def testPolicy(symbol='JPM', sd=dt.datetime(2008, 1, 1), ed=dt.datetime(2009, 12, 31)): bb_indicator = bb(symbol=[symbol], sd=sd, ed=ed) sma_indicator = sma(symbol=[symbol], sd=sd, ed=ed) ema_indicator = ema(symbol=[symbol], sd=sd, ed=ed) #create new strategy df strategy = pd.DataFrame(index=bb_indicator.index) #thresholds and buy/sell/hold flags strategy['sma'] = [ -1 if x > 1.02 else 1 if x < 0.98 else 0 for x in sma_indicator ] strategy['bb'] = [ -1 if x > 1.5 else 1 if x < -.5 else 0 for x in bb_indicator ] strategy['ema'] = [ -1 if x > 1.02 else 1 if x < .98 else 0 for x in ema_indicator ] strategy['holding'] = [ 0 if x == 0 else 1000 if x > 0 else -1000 for x in strategy.sum(axis=1) ] # print strategy strategy[symbol] = 0 strategy[symbol].values[ 1:] = strategy['holding'].values[1:] - strategy['holding'].values[:-1] df_trades = strategy[[symbol]] return df_trades # if __name__ == "__main__": # df_trades = testPolicy() # print df_trades
def short_open(data_open, data_close): current_price = 0.0 alma_close = ind.alma(data_close, 300) ema_close = ind.ema(data_close, 9) ema_open = ind.ema(data_open, 9) boolean = False logging.info('9Ema Close: {} - 9Ema Open: {} - 300Alma: {}'.format( ema_close, ema_open, alma_close)) if (ema_close < alma_close) and (ema_open > alma_close): boolean = True logging.info('Short open: {}'.format(boolean)) return boolean
def add_ema_to_dataframe(df, period=21): ema_array = pd.DataFrame(df['Close']).to_numpy() ema_data = ema(ema_array, period) padding = [None for _ in range(period)] ema_data = np.insert(ema_data, 0, padding) name = f'ema{period}' df[name] = pd.Series(ema_data) return df
def get_discretized_indicators(sd, ed, symbol): prices, _ = get_df_prices(sd, ed, symbol) # EMA 2 States: Price <= EMA: 0, Price > EMA: 1 ema_20 = indicators.ema(sd, ed, symbol, window_size=20) ema_30 = indicators.ema(sd, ed, symbol, window_size=30) ema_50 = indicators.ema(sd, ed, symbol, window_size=50) ema_20 = (prices > ema_20) * 1 ema_30 = (prices > ema_30) * 1 ema_50 = (prices > ema_50) * 1 # MACD 2 States: MACD <= Signal: 0, MACD > Signal: 1 macd_raw, macd_signal = indicators.macd(sd, ed, symbol) macd = (macd_raw > macd_signal) * 1 # TSI 2 States: TSI <= 0: 0, TSI > 0: 1 tsi = indicators.tsi(sd, ed, symbol) tsi = (tsi > 0) * 1 return ema_20, ema_30, ema_50, macd, tsi
def backtest_exit(self, current_position, data): try: self.condictions_state_backtest = { 'buy': { 'linear_regression_channel': False, 'r_percent': False, 'cmf': False }, 'sell': { 'linear_regression_channel': False, 'r_percent': False, 'cmf': False } } if len(data.date) > exit * 2: data = data.iloc[(len(data.date) - (2 * max(self.lrc_period_1, self. lrc_period_2, self.lrc_period_3))):] linear_regression_exit, upper_line_exit, lower_line_exit, slope_exit, channel_width_exit = linear_regression_channel( data, self.lrc_period_exit, self.lrc_std_exit) data['cmf'] = cmf(list(data.bidclose), list(data.bidhigh), list(data.bidlow), list(data.tickqty), self.cmf_period) data['cmf_ma'] = ema(list(data.cmf), self.cmf_ma_period) data['r_percent'] = r_percent(data, self.r_percent_period) if current_position == 'buy': if ((data.bidclose.iloc[-1] > upper_line_exit[-1])): self.condictions_state_backtest['sell'][ 'linear_regression_channel'] = True self.condictions_state_backtest['buy'][ 'linear_regression_channel'] = False return 'exit' elif current_position == 'sell': if ((data.bidclose.iloc[-1] < lower_line_exit[-1])): self.condictions_state_backtest['buy'][ 'linear_regression_channel'] = True self.condictions_state_backtest['sell'][ 'linear_regression_channel'] = False return 'exit' else: self.condictions_state_backtest['buy'][ 'linear_regression_channel'] = False self.condictions_state_backtest['sell'][ 'linear_regression_channel'] = False return None else: return None except: return None
def check_entry(self): try: self.get_data() self.data['ema_1'] = ema(list(self.data.bidclose), self.ema_1_period) self.data['ema_2'] = ema(list(self.data.bidclose), self.ema_2_period) if ((self.data.ema_1.iloc[-1] > self.data.ema_2.iloc[-1])): self.condictions_state['sell']['ema'] = True self.condictions_state['buy']['ema'] = False elif ((self.data.ema_1.iloc[-1] < self.data.ema_2.iloc[-1])): self.condictions_state['buy']['ema'] = True self.condictions_state['sell']['ema'] = False else: self.condictions_state['buy']['ema'] = False self.condictions_state['sell']['ema'] = False collected_score_buy = 0 collected_score_sell = 0 for k, v in self.conditions_weights.items(): if self.condictions_state['buy'][k] == True: collected_score_buy += v elif self.condictions_state['sell'][k] == True: collected_score_sell += v if collected_score_buy >= self.required_score: return 'buy' elif collected_score_sell >= self.required_score: return 'sell' else: return None except Exception as e: print(e, 98555555986668) return None
def check_exit(self, current_position): try: self.get_data() self.data['ema_1'] = ema(list(self.data.bidclose), self.ema_1_period) self.data['ema_2'] = ema(list(self.data.bidclose), self.ema_2_period) if current_position == 'buy': if ((self.data.ema_1.iloc[-1] > self.data.ema_2.iloc[-1])): self.condictions_state['sell']['ema'] = True self.condictions_state['buy']['ema'] = False return 'exit' elif current_position == 'sell': if ((self.data.ema_1.iloc[-1] < self.data.ema_2.iloc[-1])): self.condictions_state['buy']['ema'] = True self.condictions_state['sell']['ema'] = False return 'exit' else: self.condictions_state['buy']['ema'] = False self.condictions_state['sell']['ema'] = False return None except Exception as e: print(e, 454545)
def add_dataframe_indicators(stock_frame: pd.DataFrame) -> pd.DataFrame: """Adds the different technical indicator to our DataFrame. ### Parameters ---------- stock_frame : pd.DataFrame A pandas DataFrame with the Open, Close, High, and Low price. ### Returns ------- pd.DataFrame A Pandas DataFrame with the indicators added to the data frame. """ # Add the MACD Indicator. stock_frame = macd(stock_frame=stock_frame, fast_period=12, slow_period=26) # Add the EMA Indicator. stock_frame = ema(stock_frame=stock_frame, period=50, alpha=1.0) return stock_frame
def check_exit(self, current_position): try: self.get_data() linear_regression_exit, upper_line_exit, lower_line_exit, slope_exit, channel_width_exit = linear_regression_channel( self.data, self.lrc_period_exit, self.lrc_std_exit) self.data['cmf'] = cmf(list(self.data.bidclose), list(self.data.bidhigh), list(self.data.bidlow), list(self.data.tickqty), self.cmf_period) self.data['cmf_ma'] = ema(list(self.data.cmf), self.cmf_ma_period) self.data['r_percent'] = r_percent(self.data, self.r_percent_period) if current_position == 'buy': if ((self.data.bidclose.iloc[-1] > upper_line_exit[-1])): self.condictions_state['sell'][ 'linear_regression_channel'] = True self.condictions_state['buy'][ 'linear_regression_channel'] = False return 'exit' elif current_position == 'sell': if ((self.data.bidclose.iloc[-1] < lower_line_exit[-1])): self.condictions_state['buy'][ 'linear_regression_channel'] = True self.condictions_state['sell'][ 'linear_regression_channel'] = False return 'exit' else: self.condictions_state['buy'][ 'linear_regression_channel'] = False self.condictions_state['sell'][ 'linear_regression_channel'] = False return None except Exception as e: print(e) return None
data = get_google_finance_intraday(ticker, period=900, days=100) #30 mins #data = get_google_finance_intraday(ticker, period=1800, days=100) #60 mins #data = get_google_finance_intraday(ticker, period=3600, days=100) #daily chart #data = get_google_finance_intraday(ticker, period=86400, days=100) #data = get_google_finance_intraday("HCLTECH", 600) #data.reset_index(drop=False) #new_index = ['CLOSE','OPEN'] #data.reindex(new_index) #print data #exit(0) #print ema(data) ema(data, 5, 'CLOSE') ema(data, 10, 'CLOSE') #ema2 = ema(data, 5, 'CLOSE') print " ---------------------" add_row_count(data) #print data #print ema2 #print money_flow_index(data) #data2 = data #print data print " ---------------------" # RSI calculation ##['money_flow_index'] data2 = data data = data.set_index('row_index')
def check_entry(self): try: self.get_data() linear_regression_1, upper_line_1, lower_line_1, slope_1, channel_width_1 = linear_regression_channel( self.data, self.lrc_period_1, self.lrc_std_1) linear_regression_2, upper_line_2, lower_line_2, slope_2, channel_width_2 = linear_regression_channel( self.data, self.lrc_period_2, self.lrc_std_2) linear_regression_3, upper_line_3, lower_line_3, slope_3, channel_width_3 = linear_regression_channel( self.data, self.lrc_period_3, self.lrc_std_3) self.data['cmf'] = cmf(list(self.data.bidclose), list(self.data.bidhigh), list(self.data.bidlow), list(self.data.tickqty), self.cmf_period) self.data['cmf_ma'] = ema(list(self.data.cmf), self.cmf_ma_period) self.data['r_percent'] = r_percent(self.data, self.r_percent_period) if ((self.data.bidclose.iloc[-1] > upper_line_1[-1]) or (self.data.bidclose.iloc[-1] > upper_line_2[-1]) or (self.data.bidclose.iloc[-1] > upper_line_3[-1])): self.condictions_state['sell'][ 'linear_regression_channel'] = True self.condictions_state['buy'][ 'linear_regression_channel'] = False elif ((self.data.bidclose.iloc[-1] < lower_line_1[-1]) or (self.data.bidclose.iloc[-1] < lower_line_2[-1]) or (self.data.bidclose.iloc[-1] < lower_line_3[-1])): self.condictions_state['buy'][ 'linear_regression_channel'] = True self.condictions_state['sell'][ 'linear_regression_channel'] = False else: self.condictions_state['buy'][ 'linear_regression_channel'] = False self.condictions_state['sell'][ 'linear_regression_channel'] = False if self.data.r_percent.iloc[-2] > -20 and self.data.r_percent.iloc[ -1] < -20: self.condictions_state['sell']['r_percent'] = True self.condictions_state['buy']['r_percent'] = False elif self.data.r_percent.iloc[ -2] < -80 and self.data.r_percent.iloc[-1] > -80: self.condictions_state['buy']['r_percent'] = True self.condictions_state['sell']['r_percent'] = False else: self.condictions_state['buy']['r_percent'] = False self.condictions_state['sell']['r_percent'] = False if self.data.cmf.iloc[-1] > self.data.cmf_ma.iloc[-1]: self.condictions_state['sell']['cmf'] = False self.condictions_state['buy']['cmf'] = True else: self.condictions_state['sell']['cmf'] = True self.condictions_state['buy']['cmf'] = False collected_score_buy = 0 collected_score_sell = 0 for k, v in self.conditions_weights.items(): if self.condictions_state['buy'][k] == True: collected_score_buy += v elif self.condictions_state['sell'][k] == True: collected_score_sell += v if collected_score_buy >= self.required_score: return 'buy' elif collected_score_sell >= self.required_score: return 'sell' else: return None except Exception as e: print(e, 9898989898) return None
def emaCloseBelow(): return bars['C'] <= ind.ema(bars['C'], 20)
def backtest_entry(self, data): try: self.condictions_state_backtest = { 'buy': { 'linear_regression_channel': False, 'r_percent': False, 'cmf': False }, 'sell': { 'linear_regression_channel': False, 'r_percent': False, 'cmf': False } } if len(data.date) > max(self.lrc_period_1, self.lrc_period_2, self.lrc_period_3): data = data.iloc[(len(data.date) - (2 * max(self.lrc_period_1, self. lrc_period_2, self.lrc_period_3))):] linear_regression_1, upper_line_1, lower_line_1, slope_1, channel_width_1 = linear_regression_channel( data, self.lrc_period_1, self.lrc_std_1) linear_regression_2, upper_line_2, lower_line_2, slope_2, channel_width_2 = linear_regression_channel( data, self.lrc_period_2, self.lrc_std_2) linear_regression_3, upper_line_3, lower_line_3, slope_3, channel_width_3 = linear_regression_channel( data, self.lrc_period_3, self.lrc_std_3) data['cmf'] = cmf(list(data.bidclose), list(data.bidhigh), list(data.bidlow), list(data.tickqty), self.cmf_period) data['cmf_ma'] = ema(list(data.cmf), self.cmf_ma_period) data['r_percent'] = r_percent(data, self.r_percent_period) if ((data.bidclose.iloc[-1] > upper_line_1[-1]) or (data.bidclose.iloc[-1] > upper_line_2[-1]) or (data.bidclose.iloc[-1] > upper_line_3[-1])): self.condictions_state_backtest['sell'][ 'linear_regression_channel'] = True self.condictions_state_backtest['buy'][ 'linear_regression_channel'] = False elif ((data.bidclose.iloc[-1] < lower_line_1[-1]) or (data.bidclose.iloc[-1] < lower_line_2[-1]) or (data.bidclose.iloc[-1] < lower_line_3[-1])): self.condictions_state_backtest['buy'][ 'linear_regression_channel'] = True self.condictions_state_backtest['sell'][ 'linear_regression_channel'] = False else: self.condictions_state_backtest['buy'][ 'linear_regression_channel'] = False self.condictions_state_backtest['sell'][ 'linear_regression_channel'] = False if data.r_percent.iloc[-2] > -10 and data.r_percent.iloc[ -1] < -20: self.condictions_state_backtest['sell']['r_percent'] = True self.condictions_state_backtest['buy']['r_percent'] = False elif data.r_percent.iloc[-2] < -90 and data.r_percent.iloc[ -1] > -80: self.condictions_state_backtest['buy']['r_percent'] = True self.condictions_state_backtest['sell'][ 'r_percent'] = False else: self.condictions_state_backtest['buy']['r_percent'] = False self.condictions_state_backtest['sell'][ 'r_percent'] = False if data.cmf.iloc[-1] > data.cmf_ma.iloc[-1]: self.condictions_state_backtest['sell']['cmf'] = False self.condictions_state_backtest['buy']['cmf'] = True else: self.condictions_state_backtest['sell']['cmf'] = True self.condictions_state_backtest['buy']['cmf'] = False collected_score_buy = 0 collected_score_sell = 0 for k, v in self.conditions_weights.items(): if self.condictions_state_backtest['buy'][k] == True: collected_score_buy += v elif self.condictions_state_backtest['sell'][k] == True: collected_score_sell += v if collected_score_buy >= self.required_score: return 'buy' elif collected_score_sell >= self.required_score: return 'sell' else: return None else: return None except Exception as e: print(e, 11111111111111) return None
import client import indicators import pandas as pd df = pd.read_csv('equities.csv', index_col='symbol') df['price'] = pd.Series() df['average_volatility'] = pd.Series() df['average_volume'] = pd.Series() for index, item in df.iterrows(): symbol = item.name equity = client.get_history(symbol) equity = indicators.day_range_pct(equity) equity = indicators.ema(equity, 'volume', 'ema_volume') equity = equity.join( pd.Series(equity['ema_volume'] / 1000000, name="vol(M)")) equity = indicators.ema(equity, 'day_range_pct', 'ema_day_range_pct') if len(equity) > 0: df.loc[symbol, 'price'] = equity['close'].tail(1).values df.loc[symbol, 'average_volatility'] = equity['ema_day_range_pct'].tail( 1).values df.loc[symbol, 'average_volume'] = equity['vol(M)'].tail(1).values df.to_pickle('./equities.pkl')
def emaCloseAbove(): return bars['C'] >= ind.ema(bars['C'], 20)
def AmazingCrossoverStrategy(accountID, token, instrument, window, weight): api = API(token, accountID) history = api.get_candles(instrument, window) try: n = len(history) - 1 price = history['Close'][n] decimal = len(price.split('.')[1]) price = float(price) history['High'] = history['High'].astype(float) history['Low'] = history['Low'].astype(float) history['median_price'] = (history['High'] + history['Low']) / 2 history['rsi'] = rsi(history['median_price'], 10) history['fast_sma'] = ema(history['Close'], 5) history['slow_sma'] = ema(history['Close'], 10) history[-1:].to_sql(instrument + '_' + window, conn, if_exists='append') oo = api.openOrders() # long logic if history['fast_sma'][n] > history['slow_sma'][n]: if instrument in oo: if oo[instrument]['Bias'] == 'Short': api.close(instrument) else: tradeID = oo[instrument]['tradeIDs'][0] price = history['Close'][n] tsl = api.update_order(tradeID, price, endpoint='trailingStopLoss') print("AMAZING TRAILING STOP LOSS UPDATED") else: # if not look for an opportunity #if history['rsi'][n] > 50.0: stop_loss = str(round(float(price - (price * 0.002)), decimal)) take_profit = str(round(float(price + (price * 0.02)), decimal)) try: mo = api.order(instrument, weight, price, stop_loss, take_profit) print("AMAZING went long %s" % instrument) except Exception as e: print(e) if history['fast_sma'][n] < history['slow_sma'][n]: if instrument in oo: if oo[instrument]['Bias'] == 'Long': api.close(instrument) else: tradeID = oo[instrument]['tradeIDs'][0] price = history['Close'][n] tsl = api.update_order(tradeID, price, endpoint='trailingStopLoss') print("AMAZING TRAILING STOP LOSS UPDATED") else: #if history['rsi'][n] < 50.0: stop_loss = str(round(float(price + (price * 0.002)), decimal)) take_profit = str(round(float(price - (price * 0.02)), decimal)) try: mo = api.order(instrument, -weight, price, stop_loss, take_profit) print("AMAZING went short %s" % instrument) except Exception as e: print(e) except: print("candles unavailable right now: %s" % instrument)
def testPolicy(self, symbol, sd, ed, sv): # setting up symbol = symbol[0] df = get_data([symbol], pd.date_range(sd, ed)) df_price = df[[symbol]] df_price = df_price.ffill().bfill() normalized_df_price = df_price[symbol] / df_price[symbol][0] df_trades = df[['SPY']] df_trades = df_trades.rename(columns={ 'SPY': symbol }).astype({symbol: 'int32'}) df_trades[:] = 0 dates = df_trades.index # getting indicators ema_20 = indicators.ema(sd, ed, symbol, plot=True, window_size=20) macd_raw, macd_signal = indicators.macd(sd, ed, symbol, plot=True) tsi = indicators.tsi(sd, ed, symbol, plot=True) # current_cash = sv current_position = 0 last_action = 0 # making trades for i in range(len(dates)): today = dates[i] last_action += 1 # EMA_20 Vote normalized_df_price_today = normalized_df_price.loc[today] ema_20_today = ema_20.loc[today] # if normalized_df_price_today > ema_20_today + 0.1: if normalized_df_price_today > ema_20_today: ema_vote = 1 # elif normalized_df_price_today < ema_20_today - 0.1: elif normalized_df_price_today < ema_20_today: ema_vote = -1 else: ema_vote = 0 # MACD Vote macd_raw_today = macd_raw.loc[today].loc[symbol] macd_signal_today = macd_signal.loc[today].loc[symbol] # if macd_signal_today > macd_raw_today + 0.2: if macd_signal_today > macd_raw_today: macd_vote = 2 # elif macd_signal_today < macd_raw_today - 0.2: elif macd_signal_today < macd_raw_today: macd_vote = -10 else: macd_vote = 1 # TSI vote tsi_today = tsi.loc[today].loc[symbol] # if tsi_today > 0.05: if tsi_today > 0.1: tsi_vote = 1 # elif tsi_today < -0.05: elif tsi_today < 0.1: tsi_vote = -1 else: tsi_vote = 0 # pooling the votes pool = macd_vote + tsi_vote + ema_vote if pool >= 3: # long action = 1000 - current_position elif pool <= -3: # short action = -1000 - current_position else: # out action = -current_position # don't trade too frequent if last_action >= 3: df_trades.loc[dates[i]].loc[symbol] = action current_position += action last_action = 0 return df_trades
def emaCloseBelow(): return bars['C'] <= ind.ema(bars['C'], 20)
def emaCloseAbove(): return bars['C'] >= ind.ema(bars['C'], 20)
def chart(): """ For plotting normal candle chart or along with indicators :return: None """ # prop, data = data_parser.get_data(start_date="2017-08-18") # result = Strategies.rsi(data, data_properties=prop) # data_properties = result['data_properties'] # main_chart = [] # for key, values in data_properties.items(): # main_chart.append([key, values]) # params = result['params'] # data = result['data'] # print(params,data_with_indicators) # final_data = data_with_indicators[1:] # print(final_data) data_prop, data = data_parser.get_data(start_date="2007-01-18") high = data_parser.get_high(data) low = data_parser.get_low(data) close = data_parser.get_close(data) sma = indicators.sma(close) ema = indicators.ema(close) macd = indicators.macd(close) rsi = indicators.rsi(close) stoch = indicators.stoch(high, low, close) bbands = indicators.bollinger_bands(close) pivot = indicators.pivot(data) chart_1 = ChartElement(data=sma, label="sma", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.YELLOW) chart_2 = ChartElement(data=ema, label="ema", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.PINK) chart_3 = ChartElement(data=stoch, label="stoch", chart_type=ChartType.LINE, plot=ChartAxis.DIFFERENT_AXIS, color=ChartColor.PURPLE) chart_4 = ChartElement(data=bbands, label="bbands", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.BLUE) chart_5 = ChartElement(data=pivot, label="pivot", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.GREEN) chart_6 = ChartElement(data=rsi, label="rsi", chart_type=ChartType.LINE, plot=1, color=ChartColor.RED) chart_7 = ChartElement(data=macd, label="macd", chart_type=ChartType.LINE, plot=2, color="magenta") charts = [chart_4, chart_6] buy = Condition(data1=sma, data2=ema, operation=Operation.CROSSOVER) sell = Condition(data1=rsi, data2=70, operation=Operation.GREATER_THAN) result = strategy.strategy_builder(data_properties=data_prop, data_list=data, charts=charts, buy=buy, sell=sell, target=1.0, sl=0.5, strategy=strategy.BUY) # strategy.show_back_testing_reports(result, auto_open=True) data_properties = result['data_properties'] main_chart = [] for key, values in data_properties.items(): main_chart.append([key, values]) params = result['params'] # print(params) data_list = result['data'] return render_template("chart.html", chartData=data_list, chart_params=params, main_chart_properties=main_chart)
def cum_pl_short(): """ Chart for back test reports of Cumulative profit and loss :return: None """ data_prop, data = data_parser.get_data(start_date="2000-01-18") high = data_parser.get_high(data) low = data_parser.get_low(data) close = data_parser.get_close(data) sma = indicators.sma(close) ema = indicators.ema(close) macd = indicators.macd(close) rsi = indicators.rsi(close) stoch = indicators.stoch(high, low, close) bbands = indicators.bollinger_bands(close) pivot = indicators.pivot(data) chart_1 = ChartElement(data=sma, label="sma", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.YELLOW) chart_2 = ChartElement(data=ema, label="ema", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.PINK) chart_3 = ChartElement(data=stoch, label="stoch", chart_type=ChartType.LINE, plot=ChartAxis.DIFFERENT_AXIS, color=ChartColor.PURPLE) chart_4 = ChartElement(data=bbands, label="bbands", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.BLUE) chart_5 = ChartElement(data=pivot, label="pivot", chart_type=ChartType.LINE, plot=ChartAxis.SAME_AXIS, color=ChartColor.GREEN) chart_6 = ChartElement(data=rsi, label="rsi", chart_type=ChartType.LINE, plot=1, color=ChartColor.RED) chart_7 = ChartElement(data=macd, label="macd", chart_type=ChartType.LINE, plot=2, color="magenta") charts = [chart_1, chart_2, chart_3, chart_6] buy = Condition(data1=sma, data2=ema, operation=Operation.CROSSOVER) sell = Condition(data1=rsi, data2=70, operation=Operation.GREATER_THAN) result = strategy.strategy_builder(data_properties=data_prop, data_list=data, charts=charts, buy=buy, sell=sell, target=1.0, sl=0.5, strategy=strategy.BUY) cum_short = result['short']['DATE_CUM_PL'] # print(cum_short) return render_template("cum_pl_short.html", shortData=cum_short)
import numpy as np import sys import indicators CANDLE_SIZE = 10 inds = [ indicators.ema(5), indicators.ema(10), indicators.ema(50), indicators.ema(100), indicators.ema(200), indicators.sma(20), indicators.sma(50), indicators.rsi(14), indicators.macd(12, 26), indicators.accdistdelt(), indicators.ichimoku_tenkan(), indicators.ichimoku_kijun() ] def main(): print "Loadng from txt" idata = np.genfromtxt(sys.argv[1], delimiter=',', skip_header=2, usecols=[1, 2, 3, 4, 6]) i = 0
def test_ema(self): input_quotes = [1.1403,1.1406,1.1406,1.1404,1.1406,1.1406,1.1405,1.1405,1.1406,1.1406,1.1406,1.1404,1.1405,1.1405,1.1405,1.1403,1.1404,1.1404,1.1405,1.1408,1.1406,1.1406,1.1404,1.1403,1.1404,1.1402,1.1401,1.1401,1.1388,1.1389,1.139,1.1391,1.139,1.1392,1.1392,1.1391,1.1396,1.14,1.1399,1.14,1.1401,1.1401,1.1399,1.1401,1.14,1.1396,1.1396,1.1398,1.14,1.1401,1.1402,1.1402,1.1401,1.14,1.1405,1.1407,1.1408,1.1411,1.1411,1.1413,1.1413,1.1408,1.1415,1.1415,1.1416,1.1415,1.1416,1.1418,1.1417,1.1415,1.142,1.1421,1.1421,1.1416,1.1415] wanted_ema = [1.1405,1.14053333333333,1.14052222222222,1.14051481481481,1.14054320987654,1.1405621399177,1.14057475994513,1.14051650663009,1.14051100442006,1.14050733628004,1.14050489085336,1.14043659390224,1.14042439593483,1.14041626395655,1.14044417597103,1.14056278398069,1.14057518932046,1.14058345954697,1.14052230636465,1.1404482042431,1.14043213616207,1.14035475744138,1.14026983829425,1.1402132255295,1.139742150353,1.13946143356867,1.13930762237911,1.13923841491941,1.13915894327961,1.13917262885307,1.13918175256871,1.13915450171248,1.13930300114165,1.13953533409443,1.13965688939629,1.13977125959753,1.13988083973168,1.13995389315446,1.13993592876964,1.13999061917976,1.13999374611984,1.13986249741323,1.13977499827548,1.13978333218366,1.1398555547891,1.13993703652607,1.14002469101738,1.14008312734492,1.14008875156328,1.14005916770885,1.1402061118059,1.14037074120394,1.14051382746929,1.14070921831286,1.14083947887524,1.14099298591683,1.14109532394455,1.1409968826297,1.1411645884198,1.14127639227987,1.14138426151991,1.14142284101327,1.14148189400885,1.14158792933923,1.14162528622616,1.14158352415077,1.14172234943385,1.1418482329559,1.14193215530393,1.14182143686929,1.14171429124619] def minus(x, y): return x-y diff = map(minus, wanted_ema, indicators.ema(input_quotes,5)) #diff for each item must be near zero self.assertTrue(sum(diff)/len(diff)<0.000001)
import client import indicators from datetime import datetime, timedelta import pandas as pd import matplotlib.pyplot as plt # retrieve history symbol = "AC" df = client.get_history(symbol, days=800) df # %% df['date'] = pd.to_datetime(df['date']) df.set_index('date', inplace=True) date_ago = (datetime.now() - timedelta(days=365)).strftime('%Y-%m-%d') # %% dd = indicators.ema(df, "close", "ema_close", n=200) dd = dd[date_ago:] fw_low = dd[date_ago:]['close'].min() fw_high = dd[date_ago:]['close'].max() # normalize dd # %% dd[['close','ema_close']].plot() plt.show()