def get_89_ema_high_low_trend(stock_latest_data): stock_data_high_prices_series = util.get_panda_series_of_stock_closing_prices (stock_latest_data,'high') stock_data_low_prices_series = util.get_panda_series_of_stock_closing_prices (stock_latest_data, 'low') _89_day_high_EMA_series = ind.ema (stock_data_high_prices_series, 89) _89_day_low_EMA_series = ind.ema (stock_data_low_prices_series, 89) stock_data_closing_prices_series = util.get_panda_series_of_stock_closing_prices (stock_latest_data, 'close') trend = Trend.uptrend for i in range (1, min_no_of_values_to_scan_for_89_ema_trend): if (stock_data_closing_prices_series.iloc[-i] > _89_day_high_EMA_series.iloc[-i] and stock_data_closing_prices_series.iloc[-i] > _89_day_low_EMA_series.iloc[-i]) == False: trend = Trend.notrend break if(trend.value==Trend.uptrend.value): return trend else: trend = Trend.downtrend for i in range (1, min_no_of_values_to_scan_for_89_ema_trend): if (stock_data_closing_prices_series.iloc[-i] < _89_day_high_EMA_series.iloc[-i] and stock_data_closing_prices_series.iloc[-i] < _89_day_low_EMA_series.iloc[-i]) == False: trend = Trend.notrend break return trend
def obv_opt(ohlc_df): short_period = range(5, 16) long_period = range(25, 81) obv_data = np.zeros((short_period[-1] + 1, long_period[-1] + 1)) for i in short_period: for j in long_period: ta_df['obv{}_{}'.format(i, j)] = ta.obv(ohlc_df, i, j) obv_cols = [f for f in list(ta_df) if 'obv' in f] obv_corrs = ut.correlation(ta_df[obv_cols + ['next return']], col='next return', ret_col=True) for i in short_period: for j in long_period: obv_data[i, j] = obv_corrs['obv{}_{}'.format(i, j)] maxloc = np.unravel_index(obv_data.argmax(), obv_data.shape) print(maxloc) plt.figure(figsize=(20, 16 / 3)) plt.plot([maxloc[1] + 0.5, 74.5], [9.5, 10.5], '*', color='gold', ms=18) vmin = np.min(obv_data[np.nonzero(obv_data)]) ax = sns.heatmap(obv_data, vmin=vmin) plt.xlabel('Long Time Period (Hours)', fontsize=18) plt.ylabel('Short Time Period (Hours)', fontsize=18) plt.xlim([long_period[-1] - 1, long_period[0]]) ax.set_ylim(top=11) plt.savefig('Figures/obv_opt.png', bbox_inches='tight', format='png', dpi=300) plt.show()
def add_indicators(df): df.reset_index(inplace=True) df.set_index("Date", inplace=True) df['Weekly EMA'] = i.faster_ema(aux.to_weekly(df)) df['Daily EMA'] = i.fast_ema(df) df['Weekly MACD'] = i.macd_hist(aux.to_weekly(df)) df['Daily MACD'] = i.macd_hist(df) df['RSI'] = i.rsi(df) df['Force Index'] = i.force_index(df) return df
def get_nasdaq_daily_data_ind(symbol='', trade_date='', start_date='', end_date='', append_ind=False): con = db.connect('localhost', 'root', 'root', 'stock') df = pd.DataFrame() sql = "SELECT symbol,date,open,close,adj_close,high,low,volume FROM nasdaq_daily where 1=1 " if (len(symbol) > 0) & (not symbol.isspace()): sql += "and symbol = %(symbol)s " if (len(trade_date) > 0) & (not trade_date.isspace()): sql += "and date = %(date)s " if (len(start_date) > 0) & (not start_date.isspace()): sql += "and date >= %(start_date)s " if (len(end_date) > 0) & (not end_date.isspace()): sql += "and date <= %(end_date)s " sql += "order by date asc " print sql data = pd.read_sql(sql, params={'symbol': symbol, 'date': trade_date, 'start_date': start_date, 'end_date': end_date}, con=con) if append_ind: open, close, high, low, volume = data['open'], data['close'], data['high'], data['low'], data['volume'] ochl2ind = ind.ochl2ind(open, close, high, low, volume) data = data.join(ochl2ind, how='left') df = df.append(data) con.close() return df
def run_analysis(configfile, resultsdir): """ master function that runs line profile analysis of the dataset """ # Header InOut.print_head() #reading config from configfile listname, filetype, selected_indicators, RVext = InOut.read_config( configfile) #read observations from obslist file_names, dataset, BJDs, RVextvalues = InOut.read_obslist( listname, filetype, RVext) #fit Gaussian function to the data Gauss_params = Gaussfitting.dataset_gaussfit(dataset) # Identify selected indicators IndicatorList = ["BIS", "BIS-", "BIS+", "biGauss", "Vasy", "Vspan", "FWHM"] IndSelected = [ ind for ind, selected in zip(IndicatorList, selected_indicators) if selected == 1 ] #Apply indicators output_ASCII_list = [ Indicators.run_indicator_analysis(ind, dataset, Gauss_params, file_names, resultsdir, RVextvalues) for ind in IndSelected ] #Wrap the results in one single file InOut.wrapRes(output_ASCII_list, BJDs, resultsdir) # The End InOut.print_foot()
def data(symbol, timeframe, sma_len): # get our data # valid downloadable periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max df = yf.download(symbol, period='1y', interval=timeframe) df['SMA'] = Indicators.SMA(df['Close'], int(sma_len)) # should you wish to use another strategy # add your indicators here buy = [] sell = [] tpbuy = [] tpsell = [] for i in range(0, len(df['Close'])): buy.append(np.nan) tpbuy.append(np.nan) sell.append(np.nan) tpsell.append(np.nan) df['Long'] = buy df['Short'] = sell df['TP Long'] = tpbuy df['TP Short'] = tpsell # strategy in backtest long = [] short = [] tpLong = [] tpShort = [] isLong = False isShort = False isTPLong = False isTPShort = False '''hereunder an example of strategy using simple moving average in the last X periods (SMA) you may change with your own strategy buy orders when current SMA is above last SMA sell orders when current SMA is below last SMA creation of a list for backtesting and chart purpose for every buy, sell, take profit buy, take profit sell orders including time and price value at candle close''' for i in range(1, len(df['Close'])): sma = df['SMA'][i] sma1 = df['SMA'][i - 1] if not isLong and sma > sma1: long.append([df.index[i], df['Close'][i]]) df['Long'][i] = df['Close'][i] isLong = True isTPLong = False elif isLong and not isTPLong and sma < sma1: tpLong.append([df.index[i], df['Close'][i]]) df['TP Long'][i] = df['Close'][i] isLong = False isTPLong = True elif not isShort and sma < sma1: short.append([df.index[i], df['Close'][i]]) df['Short'][i] = df['Close'][i] isShort = True isTPShort = False elif isShort and not isTPShort and sma > sma1: tpShort.append([df.index[i], df['Close'][i]]) df['TP Short'][i] = df['Close'][i] isShort = False isTPShort = True return df, long, short, tpLong, tpShort
def re_test_ma_strategy(stock_latest_data, mares, no_of_sessions_back_to_start_i, ignore_min_session_len = False): stock_latest_data_effective_len = len (stock_latest_data) sold_mas = None if (ignore_min_session_len or stock_latest_data_effective_len > ma.MA_Strategy_Name._13_21_34_DAY_EMA.max_session_size) and mares.ma_strategy_name.value==ma.MA_Strategy_Name._13_21_34_DAY_EMA.value: stock_data_closing_prices_series = util.get_panda_series_of_stock_closing_prices (stock_latest_data) _13_day_EMA_series = ind.ema (stock_data_closing_prices_series, 13) _21_day_EMA_series = ind.ema (stock_data_closing_prices_series, 21) _34_day_EMA_series = ind.ema (stock_data_closing_prices_series, 34) while _13_day_EMA_series.iloc[no_of_sessions_back_to_start_i] > _21_day_EMA_series.iloc[ no_of_sessions_back_to_start_i] and _21_day_EMA_series.iloc[no_of_sessions_back_to_start_i] > \ _34_day_EMA_series.iloc[no_of_sessions_back_to_start_i] and is_up_slopes_of_mas (_13_day_EMA_series, _21_day_EMA_series, _34_day_EMA_series, pos=no_of_sessions_back_to_start_i): no_of_sessions_back_to_start_i += 1 if no_of_sessions_back_to_start_i >= stock_latest_data_effective_len: break if no_of_sessions_back_to_start_i < stock_latest_data_effective_len: sold_mas = [ _13_day_EMA_series.iloc[no_of_sessions_back_to_start_i], _21_day_EMA_series.iloc[no_of_sessions_back_to_start_i], _34_day_EMA_series.iloc[no_of_sessions_back_to_start_i]] elif (ignore_min_session_len or stock_latest_data_effective_len > ma.MA_Strategy_Name.IDENTIFY_LONG_TERM_STOCK_BEFORE_RALLY.max_session_size) and mares.ma_strategy_name.value==ma.MA_Strategy_Name.IDENTIFY_LONG_TERM_STOCK_BEFORE_RALLY.value: stock_data_closing_prices_series = util.get_panda_series_of_stock_closing_prices (stock_latest_data) _50_day_SMA_series = ind.sma (stock_data_closing_prices_series, 50) _150_day_SMA_series = ind.sma (stock_data_closing_prices_series, 150) _200_day_SMA_series = ind.sma (stock_data_closing_prices_series, 200) while _50_day_SMA_series.iloc[no_of_sessions_back_to_start_i] > _150_day_SMA_series.iloc[ no_of_sessions_back_to_start_i] and _150_day_SMA_series.iloc[no_of_sessions_back_to_start_i] > \ _200_day_SMA_series.iloc[no_of_sessions_back_to_start_i] and is_up_slopes_of_mas (_50_day_SMA_series, _150_day_SMA_series, pos=no_of_sessions_back_to_start_i): no_of_sessions_back_to_start_i += 1 if no_of_sessions_back_to_start_i >= stock_latest_data_effective_len: break if no_of_sessions_back_to_start_i < stock_latest_data_effective_len: sold_mas = [_50_day_SMA_series.iloc[no_of_sessions_back_to_start_i],_150_day_SMA_series.iloc[no_of_sessions_back_to_start_i],_200_day_SMA_series.iloc[no_of_sessions_back_to_start_i]] elif (ignore_min_session_len or stock_latest_data_effective_len > ma.MA_Strategy_Name.GUPPY_MULTIPLE_MOVING_AVERAGE_INDICATOR.max_session_size) and mares.ma_strategy_name.value==ma.MA_Strategy_Name.GUPPY_MULTIPLE_MOVING_AVERAGE_INDICATOR.value: stock_data_closing_prices_series = util.get_panda_series_of_stock_closing_prices (stock_latest_data) _3_day_EMA_series = ind.ema (stock_data_closing_prices_series, 3) _5_day_EMA_series = ind.ema (stock_data_closing_prices_series, 5) _8_day_EMA_series = ind.ema (stock_data_closing_prices_series, 8) _10_day_EMA_series = ind.ema (stock_data_closing_prices_series, 10) _12_day_EMA_series = ind.ema (stock_data_closing_prices_series, 12) _18_day_EMA_series = ind.ema (stock_data_closing_prices_series, 18) _30_day_EMA_series = ind.ema (stock_data_closing_prices_series, 30) _35_day_EMA_series = ind.ema (stock_data_closing_prices_series, 35) _40_day_EMA_series = ind.ema (stock_data_closing_prices_series, 40) _45_day_EMA_series = ind.ema (stock_data_closing_prices_series, 45) _50_day_EMA_series = ind.ema (stock_data_closing_prices_series, 50) _60_day_EMA_series = ind.ema (stock_data_closing_prices_series, 60) while _3_day_EMA_series.iloc[no_of_sessions_back_to_start_i] > _5_day_EMA_series.iloc[ no_of_sessions_back_to_start_i] and _5_day_EMA_series.iloc[no_of_sessions_back_to_start_i] > \ _8_day_EMA_series.iloc[no_of_sessions_back_to_start_i] and _8_day_EMA_series.iloc[ no_of_sessions_back_to_start_i] > _10_day_EMA_series.iloc[no_of_sessions_back_to_start_i] and \ _10_day_EMA_series.iloc[no_of_sessions_back_to_start_i] > _12_day_EMA_series.iloc[ no_of_sessions_back_to_start_i] and _12_day_EMA_series.iloc[no_of_sessions_back_to_start_i] > \ _18_day_EMA_series.iloc[no_of_sessions_back_to_start_i] and _18_day_EMA_series.iloc[ no_of_sessions_back_to_start_i] > _30_day_EMA_series.iloc[no_of_sessions_back_to_start_i] and \ _30_day_EMA_series.iloc[no_of_sessions_back_to_start_i] > _35_day_EMA_series.iloc[ no_of_sessions_back_to_start_i] and _35_day_EMA_series.iloc[no_of_sessions_back_to_start_i] > \ _40_day_EMA_series.iloc[no_of_sessions_back_to_start_i] and _40_day_EMA_series.iloc[ no_of_sessions_back_to_start_i] > _45_day_EMA_series.iloc[no_of_sessions_back_to_start_i] and \ _45_day_EMA_series.iloc[no_of_sessions_back_to_start_i] > _50_day_EMA_series.iloc[ no_of_sessions_back_to_start_i] and _50_day_EMA_series.iloc[no_of_sessions_back_to_start_i] > \ _60_day_EMA_series.iloc[no_of_sessions_back_to_start_i] and is_up_slopes_of_mas (_3_day_EMA_series, _5_day_EMA_series, _8_day_EMA_series, _10_day_EMA_series, _12_day_EMA_series, _18_day_EMA_series, _30_day_EMA_series, _35_day_EMA_series, _40_day_EMA_series, _45_day_EMA_series, _50_day_EMA_series, _60_day_EMA_series, pos=no_of_sessions_back_to_start_i): no_of_sessions_back_to_start_i +=1 if no_of_sessions_back_to_start_i >= stock_latest_data_effective_len: break if no_of_sessions_back_to_start_i < stock_latest_data_effective_len: sold_mas = [_3_day_EMA_series.iloc[no_of_sessions_back_to_start_i],_5_day_EMA_series.iloc[no_of_sessions_back_to_start_i],_8_day_EMA_series.iloc[no_of_sessions_back_to_start_i],_10_day_EMA_series.iloc[no_of_sessions_back_to_start_i],_12_day_EMA_series.iloc[no_of_sessions_back_to_start_i], _18_day_EMA_series.iloc[no_of_sessions_back_to_start_i]] elif (ignore_min_session_len or stock_latest_data_effective_len > ma.MA_Strategy_Name._100_DAY_EMA_WITH_200_DAY_EMA.max_session_size) and mares.ma_strategy_name.value == ma.MA_Strategy_Name._100_DAY_EMA_WITH_200_DAY_EMA.value: stock_data_closing_prices_series = util.get_panda_series_of_stock_closing_prices (stock_latest_data) _100_day_EMA_series = ind.ema (stock_data_closing_prices_series, 100) _200_day_EMA_series = ind.ema (stock_data_closing_prices_series, 200) while _100_day_EMA_series.iloc[no_of_sessions_back_to_start_i] > _200_day_EMA_series.iloc[ no_of_sessions_back_to_start_i] and is_up_slopes_of_mas (_100_day_EMA_series, _200_day_EMA_series, pos=no_of_sessions_back_to_start_i): no_of_sessions_back_to_start_i += 1 if no_of_sessions_back_to_start_i >= stock_latest_data_effective_len: break if no_of_sessions_back_to_start_i < stock_latest_data_effective_len: sold_mas = [_100_day_EMA_series.iloc[no_of_sessions_back_to_start_i],_200_day_EMA_series.iloc[no_of_sessions_back_to_start_i]] elif (ignore_min_session_len or stock_latest_data_effective_len > ma.MA_Strategy_Name._50_DAY_EMA_WITH_100_DAY_EMA.max_session_size) and mares.ma_strategy_name.value == ma.MA_Strategy_Name._50_DAY_EMA_WITH_100_DAY_EMA.value: stock_data_closing_prices_series = util.get_panda_series_of_stock_closing_prices (stock_latest_data) # _50_day_EMA_series = ind.ema (stock_data_closing_prices_series, 50) # _100_day_EMA_series = ind.ema (stock_data_closing_prices_series, 100) macd_series = ind.macd (stock_data_closing_prices_series) # while _50_day_EMA_series.iloc[no_of_sessions_back_to_start_i] > _100_day_EMA_series.iloc[ # no_of_sessions_back_to_start_i] and is_up_slopes_of_mas (_50_day_EMA_series, _100_day_EMA_series, # pos=no_of_sessions_back_to_start_i): while is_up_slopes_of_mas (macd_series, pos=no_of_sessions_back_to_start_i): no_of_sessions_back_to_start_i += 1 if no_of_sessions_back_to_start_i >= stock_latest_data_effective_len: break if no_of_sessions_back_to_start_i < stock_latest_data_effective_len: # sold_mas = [_50_day_EMA_series.iloc[no_of_sessions_back_to_start_i], _100_day_EMA_series.iloc[no_of_sessions_back_to_start_i]] sold_mas = [] elif (ignore_min_session_len or stock_latest_data_effective_len > ma.MA_Strategy_Name.MOVING_AVERAGE_RIBBON.max_session_size) and mares.ma_strategy_name.value == ma.MA_Strategy_Name.MOVING_AVERAGE_RIBBON.value: stock_data_closing_prices_series = util.get_panda_series_of_stock_closing_prices (stock_latest_data, 'close') _34_day_EMA_close_series = ind.ema (stock_data_closing_prices_series, 34) stock_data_high_prices_series = util.get_panda_series_of_stock_closing_prices (stock_latest_data, 'high') _34_day_EMA_high_series = ind.ema (stock_data_high_prices_series, 34) stock_data_low_prices_series = util.get_panda_series_of_stock_closing_prices (stock_latest_data, 'low') _34_day_EMA_low_series = ind.ema (stock_data_low_prices_series, 34) while stock_latest_data[no_of_sessions_back_to_start_i]['close'] > _34_day_EMA_close_series.iloc[ no_of_sessions_back_to_start_i] and stock_latest_data[no_of_sessions_back_to_start_i]['close'] > \ _34_day_EMA_high_series.iloc[no_of_sessions_back_to_start_i] and \ stock_latest_data[no_of_sessions_back_to_start_i]['close'] > _34_day_EMA_low_series.iloc[ no_of_sessions_back_to_start_i] and is_up_slopes_of_mas (_34_day_EMA_close_series, _34_day_EMA_high_series, _34_day_EMA_low_series, pos=no_of_sessions_back_to_start_i): no_of_sessions_back_to_start_i +=1 if no_of_sessions_back_to_start_i >= stock_latest_data_effective_len: break if no_of_sessions_back_to_start_i < stock_latest_data_effective_len: sold_mas = [_34_day_EMA_high_series.iloc[no_of_sessions_back_to_start_i],_34_day_EMA_close_series.iloc[no_of_sessions_back_to_start_i], _34_day_EMA_low_series.iloc[no_of_sessions_back_to_start_i]] if no_of_sessions_back_to_start_i >= stock_latest_data_effective_len: return None else: stock_latest_data[no_of_sessions_back_to_start_i].update({'sold_mas':sold_mas}) return stock_latest_data[no_of_sessions_back_to_start_i]
def moving_average_ribbon(stock_data, backtesting=True): mares = MASResponse () mares.fetched_dataset = stock_data mares.ma_strategy_name = MA_Strategy_Name.MOVING_AVERAGE_RIBBON mares.fetch_date = util.get_date_from_timestamp(stock_data[-1]['timestamp']) stock_data_closing_prices_series = util.get_panda_series_of_stock_closing_prices (stock_data,'close') _34_day_EMA_close_series = ind.ema (stock_data_closing_prices_series, 34) stock_data_high_prices_series = util.get_panda_series_of_stock_closing_prices (stock_data, 'high') _34_day_EMA_high_series = ind.ema (stock_data_high_prices_series, 34) stock_data_low_prices_series = util.get_panda_series_of_stock_closing_prices (stock_data, 'low') _34_day_EMA_low_series = ind.ema (stock_data_low_prices_series, 34) average_volume = util.calculate_last_10_days_average_volume (stock_data[-10:]) mares.average_volume = average_volume mares.stoploss = _34_day_EMA_low_series.iloc[-1] if (average_volume > min_average_volume_to_consider) == False: mares.errors.append ("Last 10 day average volume:" + str ( average_volume) + "not greater than min average volume to consider:" + str (min_average_volume_to_consider)) mares.high_volumes = False trend = get_89_ema_high_low_trend (stock_data) mares.trend = trend if (trend.value == Trend.uptrend.value) == False: mares.errors.append("No clear uptrend") mares.correct_trend = False current_day_current_price = util.get_current_day_current_price (stock_data[-1]) mares.current_day_current_price = current_day_current_price if (calculate_slope (_34_day_EMA_close_series).value == Slope.UP.value) == False: mares.errors.append ("_34_day_EMA_close_series not sloping upwards.") mares.sma_high_slope = False if (calculate_slope (_34_day_EMA_high_series).value == Slope.UP.value) == False: mares.errors.append ("_34_day_EMA_high_series not sloping upwards.") mares.sma_high_slope = False if (calculate_slope (_34_day_EMA_low_series).value == Slope.UP.value) == False: mares.errors.append ("_34_day_EMA_low_series not sloping upwards.") mares.sma_high_slope = False mares.lma_high_slope = None mares.sma_greater_than_lma=None mares.sma.append (append_ma_series ('34_day_EMA_close', _34_day_EMA_close_series)) mares.sma.append (append_ma_series ('34_day_EMA_high', _34_day_EMA_high_series)) mares.sma.append (append_ma_series ('34_day_EMA_low', _34_day_EMA_low_series)) if (current_day_current_price > _34_day_EMA_close_series.iloc[-1] and current_day_current_price > _34_day_EMA_high_series.iloc[-1] and current_day_current_price > _34_day_EMA_low_series.iloc[-1]) == False: mares.errors.append ( "Current day current price:" + str (current_day_current_price) + " not greater than three 34 day EMAs(high, low & close):" + str(_34_day_EMA_high_series.iloc[-1])+","+ str(_34_day_EMA_low_series.iloc[-1])+","+ str(_34_day_EMA_close_series.iloc[-1])+".") mares.stock_price_greater_than_mas = False if backtesting: days_back_when_stock_price_less_than_sma = 0 while days_back_when_stock_price_less_than_sma < len(stock_data): if (stock_data[-2 - days_back_when_stock_price_less_than_sma]['close'] > _34_day_EMA_high_series.iloc[ -2 - days_back_when_stock_price_less_than_sma]) == False: break days_back_when_stock_price_less_than_sma += 1 mares.days_back_when_stock_price_less_than_sma = days_back_when_stock_price_less_than_sma macd_series = ind.macd (stock_data_closing_prices_series) mares.macd.append (append_ma_series ('MACD', macd_series)) if (calculate_slope (macd_series).value == Slope.UP.value) == False: mares.errors.append ("MACD_series not sloping upwards.") mares.macd_high_slope = False if (macd_series.iloc[-1] > 0) == False: mares.errors.append ("MACD:" + str (macd_series.iloc[-1]) + "not greater than 0 ") mares.macd_greater_than_9_day_ema = False return mares
def get_pattern_recognition_response_result( stocks_pattern_recognition_response, stock_latest_data, desired_risk_reward_ratio, position_to_scan, lot): pattern_recognition_result = { 'res': stocks_pattern_recognition_response, 'sl_trigged': 0, 'trigged_on': None, 'tg_trigged': 0, 'exit_price': 0, 'exit_price_profit_%': 0, 'rsi_pat_ok': 1, 'buy_on': util.get_date_from_timestamp(stock_latest_data[position_to_scan - 1]['timestamp']), 'earning': 0 } stock_data_subset = stock_latest_data[position_to_scan:] buy_price = stock_latest_data[position_to_scan - 1]['close'] stoploss = 0 target = 0 if stocks_pattern_recognition_response.action.value == pr.Action.LONG.value: stoploss = get_stop_loss( buy_price, stocks_pattern_recognition_response.volatility_stop_loss[0], stocks_pattern_recognition_response.support, stocks_pattern_recognition_response.action.value, lot) # stoploss = \ # [stocks_pattern_recognition_response.volatility_stop_loss[0], stocks_pattern_recognition_response.support][ # stocks_pattern_recognition_response.support < stocks_pattern_recognition_response.volatility_stop_loss[ # 0]] target = (desired_risk_reward_ratio * (buy_price - stoploss)) + buy_price elif stocks_pattern_recognition_response.action.value == pr.Action.SHORT.value: stoploss = get_stop_loss( buy_price, stocks_pattern_recognition_response.volatility_stop_loss[1], stocks_pattern_recognition_response.resistance, stocks_pattern_recognition_response.action.value, lot) # stoploss = \ # [stocks_pattern_recognition_response.volatility_stop_loss[1], # stocks_pattern_recognition_response.resistance][ # stocks_pattern_recognition_response.resistance > # stocks_pattern_recognition_response.volatility_stop_loss[ # 1]] target = buy_price - (desired_risk_reward_ratio * (stoploss - buy_price)) rsis = ind.rsi( util.get_panda_series_of_stock_closing_prices(stock_latest_data), 14) current_position = position_to_scan for stock_data in stock_data_subset: if (stocks_pattern_recognition_response.action.value == pr.Action.LONG.value and stock_data['low'] < stoploss ) or (stocks_pattern_recognition_response.action.value == pr.Action.SHORT.value and stock_data['high'] > stoploss): pattern_recognition_result.update({ 'sl_trigged': 1, 'trigged_on': util.get_date_from_timestamp(stock_data['timestamp']), 'tg_trigged': 0, 'exit_price': [stock_data['high'], stock_data['low'] ][stocks_pattern_recognition_response.action.value == pr.Action.LONG.value] }) break if (stocks_pattern_recognition_response.action.value == pr.Action.LONG.value and stock_data['high'] > target) or ( stocks_pattern_recognition_response.action.value == pr.Action.SHORT.value and stock_data['low'] < target): pattern_recognition_result.update({ 'sl_trigged': 0, 'tg_trigged': 1, 'trigged_on': util.get_date_from_timestamp(stock_data['timestamp']), 'exit_price': [stock_data['low'], stock_data['high'] ][stocks_pattern_recognition_response.action.value == pr.Action.LONG.value] }) break current_position += 1 rsis_list = [] while position_to_scan <= current_position + 2: if position_to_scan < len(rsis): rsis_list.append(rsis.iloc[position_to_scan]) position_to_scan += 1 pattern_recognition_result.update({ 'target': target, 'stoploss': stoploss, 'rsi_smas': rsis_list, 'buy_price': buy_price }) if pattern_recognition_result['trigged_on']: pattern_recognition_result.update({ 'earning': (pattern_recognition_result['exit_price'] - buy_price) * lot * [1, -1][stocks_pattern_recognition_response.action.value == pr.Action.SHORT.value] }) return pattern_recognition_result
def calcSimpleMovingAverage(days:int, closePrices:list): g = Indicators.simpleMovingAverage(days) return g.execute(closePrices)
def getCSResAndErrors(stock_latest_info, stock_latest_data, stocks_pattern_recognition_responses, exception_errors, market_previous_trend, no_of_sessions_to_scan_forstocks, no_of_sessions_to_scan_for_RSI, no_of_sessions_to_scan_for_volatility, no_of_days_for_volatility_stop_loss): stock_data_closing_prices_series = util.get_panda_series_of_stock_closing_prices( stock_latest_data) # supports_resistances = sr.get_supports_resistances (stock_latest_data) supports_resistances = [] # if len (supports_resistances) == 0: # exception_errors.append ( # "******** No support or resistance found for stock:" + stock_latest_info[nse_bse.STOCK_ID]) # return # stock_latest_data_len = len (stock_latest_data) # if (stock_latest_data_len < no_of_sessions_to_scan_forstocks): # exception_errors.append ( # "Stock data session size:" + str (stock_latest_data_len) + " less than required session size: " + str ( # no_of_sessions_to_scan_forstocks)) # return # rsi_series = ind.rsi(stock_data_closing_prices_series, no_of_sessions_to_scan_for_RSI) rsi = rsi_series.iloc[-1] # rsi_14_9_period_SMA_series = util.get_rsi_14_9_period_SMA (stock_data_closing_prices_series) # rsi_14_9_period_SMA = rsi_14_9_period_SMA_series.iloc[-1] # # volatility = outil.get_daily_volatility ( # outil.get_daily_returns (stock_latest_data[-no_of_sessions_to_scan_for_volatility: -1])) # volatility_stop_loss = outil.get_volatility_based_stoploss (stock_latest_data[-1]['close'], volatility, # no_of_days_for_volatility_stop_loss) volatility_stop_loss = 0 rsi_14_9_period_SMA = 0 # print ("---Testing various candlestick patterns for stock:" + stock_latest_info[nse_bse.STOCK_ID]) evening_star_res = pr.Recognize_Evening_Star_pattern( stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) evening_star_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] evening_star_res.fetched_dataset = stock_latest_data evening_star_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(evening_star_res) morning_star_res = pr.Recognize_Morning_Star_pattern( stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) morning_star_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] morning_star_res.fetched_dataset = stock_latest_data morning_star_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(morning_star_res) bearish_harami_res = pr.Recognize_Bearish_Harami_pattern( stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) bearish_harami_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] bearish_harami_res.fetched_dataset = stock_latest_data bearish_harami_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(bearish_harami_res) bullish_harami_res = pr.Recognize_Bullish_Harami_pattern( stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) bullish_harami_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] bullish_harami_res.fetched_dataset = stock_latest_data bullish_harami_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(bullish_harami_res) bearish_engulfing_res = pr.Recognize_Bearish_Engulfing_pattern( stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) bearish_engulfing_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] bearish_engulfing_res.fetched_dataset = stock_latest_data bearish_engulfing_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(bearish_engulfing_res) bullish_engulfing_res = pr.Recognize_Bullish_Engulfing_pattern( stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) bullish_engulfing_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] bullish_engulfing_res.fetched_dataset = stock_latest_data bullish_engulfing_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(bullish_engulfing_res) shooting_star_res = pr.Recognize_Shooting_Star(stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) shooting_star_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] shooting_star_res.fetched_dataset = stock_latest_data shooting_star_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(shooting_star_res) hanging_man_res = pr.Recognize_Hanging_Man(stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) hanging_man_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] hanging_man_res.fetched_dataset = stock_latest_data hanging_man_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(hanging_man_res) hammer_res = pr.Recognize_Hammer(stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) hammer_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] hammer_res.fetched_dataset = stock_latest_data hammer_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(hammer_res) bearish_marubozo_res = pr.Recognize_Bearish_Marubozo( stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) bearish_marubozo_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] bearish_marubozo_res.fetched_dataset = stock_latest_data bearish_marubozo_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(bearish_marubozo_res) bullish_marubozo_res = pr.Recognize_Bullish_Marubozo( stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) bullish_marubozo_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] bullish_marubozo_res.fetched_dataset = stock_latest_data bullish_marubozo_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(bullish_marubozo_res) doji_res = pr.Recognize_Doji(stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) doji_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] doji_res.fetched_dataset = stock_latest_data doji_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(doji_res) gap_up_down_res = pr.Recognize_Gap_Up_Down(stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) gap_up_down_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] gap_up_down_res.fetched_dataset = stock_latest_data gap_up_down_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(gap_up_down_res) inverted_hammer_res = pr.Recognize_Inverted_Hammer(stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) inverted_hammer_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] inverted_hammer_res.fetched_dataset = stock_latest_data inverted_hammer_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(inverted_hammer_res) bullish_piercing_res = pr.Recognize_Bullish_Piercing_pattern( stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) bullish_piercing_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] bullish_piercing_res.fetched_dataset = stock_latest_data bullish_piercing_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(bullish_piercing_res) bearish_piercing_res = pr.Recognize_Bearish_Piercing_pattern( stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) bearish_piercing_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] bearish_piercing_res.fetched_dataset = stock_latest_data bearish_piercing_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(bearish_piercing_res) uptrend_res = pr.Recognize_Uptrend_pattern(stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) uptrend_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] uptrend_res.fetched_dataset = stock_latest_data uptrend_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(uptrend_res) downtrend_res = pr.Recognize_Downtrend_pattern(stock_latest_data, supports_resistances, rsi, rsi_14_9_period_SMA, market_previous_trend) downtrend_res.stock_id = stock_latest_info[nse_bse.STOCK_ID] downtrend_res.fetched_dataset = stock_latest_data downtrend_res.volatility_stop_loss = volatility_stop_loss stocks_pattern_recognition_responses.append(downtrend_res)
df_temp = pd.DataFrame(data['Date']) df_temp['time'] = data['Time'] df_temp['change'] = data['change'] df_temp['volume'] = data['Vol'] df_temp['close'] = data['Close'] df_temp['open'] = data['Open'] #Create Lags onwards and backwards for i in range(1, max_lag + 1): #Onward lags for output df_temp['change-' + str(i) + '-out'] = df_temp['change'].shift(-i) #Put Indicators Ind = Indicators.Indicator(df_temp['close']) df_temp['Trend_Strength'] = Ind.Trend_Strength(50) df_temp['RSI'] = Ind.RSI(20) df_temp['RSI_MA2'] = df_temp['RSI'].rolling(10).mean() df_temp['RSI_MA1'] = df_temp['RSI'].rolling(5).mean() df_temp['EMA-10'] = Ind.EMA(10) df_temp['EMA-20'] = Ind.EMA(20) df_temp['MACD'] = Ind.MACD_Delta(26, 12, 9) df_temp['MACD_MA2'] = df_temp['MACD'].rolling(10).mean() df_temp['MACD_MA1'] = df_temp['MACD'].rolling(5).mean() #Eliminate first max_lag elements of the day i = 1 while i < df_temp.shape[0]:
def market(currency): dfy = pd.read_excel( 'Historical_Data/{} price history.xlsx'.format(currency), index_col=0) dfy.index = pd.to_datetime(dfy.index, errors='coerce') # Calculate daily returns dfy['return'] = dfy['close'].shift(-1) / dfy['close'] - 1 def y_move(val): if float(val) > 0: return 1 else: return 0 # Find if price moved up or down dfy['move'] = dfy['return'].apply(lambda x: y_move(x)) # Calculate technical indicators dfy['rsi 5'] = ta.rsi(dfy['return'], 5) dfy['rsi 10'] = ta.rsi(dfy['return'], 10) dfy['rsi 23'] = ta.rsi(dfy['return'], 23) dfy['rsi 33'] = ta.rsi(dfy['return'], 33) dfy['rsi 62'] = ta.rsi(dfy['return'], 62) dfy['cci 6'] = ta.cci(dfy, 6) dfy['cci 11'] = ta.cci(dfy, 11) dfy['cci 45'] = ta.cci(dfy, 45) dfy['bb 8'] = ta.bb(dfy['close'], 8) dfy['bb 11'] = ta.bb(dfy['close'], 11) dfy['bb 74'] = ta.bb(dfy['close'], 74) dfy['macd 5-35-5'] = ta.macd(dfy['close'], (5, 35, 5)) dfy['macd 12-26-9'] = ta.macd(dfy['close'], (12, 26, 9)) dfy['wr 6'] = ta.wr(dfy, 6) dfy['wr 13'] = ta.wr(dfy, 13) dfy['wr 48'] = ta.wr(dfy, 48) dfy['wr 76'] = ta.wr(dfy, 76) dfy['atr 5'] = ta.atr(dfy, 5) dfy['atr 14'] = ta.atr(dfy, 14) dfy['atr 69'] = ta.atr(dfy, 69) dfy['obv 6-40'] = ta.obv(dfy, 6, 40) dfy['obv 5-74'] = ta.obv(dfy, 5, 74) # Shift price mc3_p1.data by 1 hour dfy['return'] = dfy['return'].shift(-1) dfy['move'] = dfy['move'].shift(-1) return dfy
def simulate(trn, tst): start = time.time() b_tp = b_fp = b_tn = b_fn = 0 s_tp = s_fp = s_tn = s_fn = 0 b_min = s_min = 1000000 b_max = s_max = 0 b_money = s_money = 0 b_money_vec = [0] s_money_vec = [0] b_gain = s_gain = 0 b_loss = s_loss = 0 b_draw = s_draw = 0 b_gain_vec = [] s_gain_vec = [] b_loss_vec = [] s_loss_vec = [] b_max_drawdown = s_max_drawdown = 0 b_pos = s_pos = False time_vec = [] aux_ii = len(tst) - 1 for t, val in enumerate(tst): start_i = time.time() if t == 201: continue if t == 0: tst[0, 5] = id.log_return(tst[0, 0], tst[0, 3], trn[-1, 0], trn[-1, 3]) else: tst[t, 5] = id.log_return(tst[t, 0], tst[t, 3], trn[t - 1, 0], trn[t - 1, 3]) tst[t, 6] = mnm.get(val[5]) tst[t, 7] = obv.get_obv(val[3], val[4]) aux = bbs.sma(val[3]) if aux is not None: tst[t, 8], tst[t, 9] = aux aux_9 = m_9.ema(val[3]) aux12 = m12.ema(val[3]) aux26 = m26.ema(val[3]) tst[t, 10] = aux12 - aux26 tst[t, 11] = tst[t, 10] - aux_9 aux = trn[-1000:] aux_i = [(i[1] - mn[i[0]]) * mx[i[0]] for i in enumerate(tst[t, :12])] # aux_j = trn[-1000:, :] b_elm = ELMClassifier(random_state=0, n_hidden=200, activation_func='sigmoid', alpha=0.0) b_elm.fit(aux[:, :12], aux[:, 12]) b_res = b_elm.predict([aux_i[:12]]) s_elm = ELMClassifier(random_state=0, n_hidden=200, activation_func='sigmoid', alpha=0.0) s_elm.fit(aux[:, :12], aux[:, 13]) s_res = s_elm.predict([aux_i[:12]]) if b_res == 1.0: if val[12] == 1.0: b_tp += 1 else: b_fp += 1 if not b_pos: # Entra b_money -= val[3] b_pos = True else: if val[12] == 0.0: b_tn += 1 else: b_fn += 1 if b_pos: # Sai b_money += val[3] b_pos = False if b_money < b_money_vec[-1]: b_loss += 1 b_loss_vec.append(b_money_vec[-1] - b_money) elif b_money > b_money_vec[-1]: b_gain += 1 b_gain_vec.append(b_money - b_money_vec[-1]) else: b_draw += 1 if val[14] == 1.0: # Sai b_money += val[3] b_pos = False if b_money < b_money_vec[-1]: b_loss += 1 b_loss_vec.append(b_money_vec[-1] - b_money) elif b_money > b_money_vec[-1]: b_gain += 1 b_gain_vec.append(b_money - b_money_vec[-1]) else: b_draw += 1 if b_pos: b_money_vec.append(b_money_vec[-1]) else: b_money_vec.append(b_money) if b_money > b_max: b_max = b_money if b_money < b_min: b_min = b_money if s_res == 1.0: if val[13] == 1.0: s_tp += 1 else: s_fp += 1 if not s_pos: # Entra s_money += val[3] s_pos = True else: if val[13] == 0.0: s_tn += 1 else: s_fn += 1 if s_pos: # Sai s_money -= val[3] s_pos = False if s_money < s_money_vec[-1]: s_loss += 1 s_loss_vec.append(s_money_vec[-1] - s_money) elif s_money > s_money_vec[-1]: s_gain += 1 s_gain_vec.append(s_money - s_money_vec[-1]) else: s_draw += 1 if val[14] == 1.0: # Sai s_money -= val[3] s_pos = False if s_money < s_money_vec[-1]: s_loss += 1 s_loss_vec.append(s_money_vec[-1] - s_money) elif s_money > s_money_vec[-1]: s_gain += 1 s_gain_vec.append(s_money - s_money_vec[-1]) else: s_draw += 1 if s_pos: s_money_vec.append(s_money_vec[-1]) else: s_money_vec.append(s_money) if s_money > s_max: s_max = s_money if s_money < s_min: s_min = s_money # print(aux_i + list(tst[t, 12:])) trn = np.append(trn, [aux_i + list(tst[t, 12:])], axis=0) time_vec.append(time.time() - start_i) sys.stdout.write('\r' + '%6d / %d' % (t, aux_ii) + '\033[K') sys.stdout.write('\r' + '>> %6.2f: Simulation Done!\n\n' % (time.time() - start) + '\033[K') print('#### ' + sys.argv[1] + ' ####') print('Tempo médio: %f' % np.mean(time_vec)) print('Final : %5.5f | %5.5f' % (b_money, s_money)) # print('Final : %5.5f | %5.5f' % (b_money_vec[-1], s_money_vec[-1])) print('Minimo : %5.5f | %5.5f' % (b_min, s_min)) print('Maximo : %5.5f | %5.5f' % (b_max, s_max)) print('Ganho qtd : %10d | %10d' % (b_gain, s_gain)) print('Perda qtd : %10d | %10d' % (b_loss, s_loss)) print('Empate qtd : %10d | %10d' % (b_draw, s_draw)) print('Ganho medio: %5.5f | %5.5f' % (np.mean(b_gain_vec), np.mean(s_gain_vec))) print('Perda media: %5.5f | %5.5f' % (np.mean(b_loss_vec), np.mean(s_loss_vec))) print('TP : %10d | %10d' % (b_tp, s_tp)) print('FP : %10d | %10d' % (b_fp, s_fp)) print('TN : %10d | %10d' % (b_tn, s_tn)) print('FN : %10d | %10d' % (b_fn, s_fn)) plot(b_money_vec, s_money_vec, sys.argv[1], tst[:, 3])
def prep_data(trn, tst): global mn global mx global mnm mnm = id.Momentum() global obv obv = id.OBV() global bbs bbs = id.Bbands() global m_9 m_9 = id.EMA(9) global m12 m12 = id.EMA(12) global m26 m26 = id.EMA(26) start = time.time() aux_ii = len(trn) - 1 for idx, val in enumerate(trn): if idx == 0: trn[idx, 5] = id.log_return(val[0], val[3], val[0], val[3]) else: trn[idx, 5] = id.log_return(val[0], val[3], trn[idx - 1, 0], trn[idx - 1, 3]) trn[idx, 6] = mnm.get(val[5]) trn[idx, 7] = obv.get_obv(val[3], val[4]) aux = bbs.sma(val[3]) if aux is not None: trn[idx, 8], trn[idx, 9] = aux aux_9 = m_9.ema(val[3]) aux12 = m12.ema(val[3]) aux26 = m26.ema(val[3]) trn[idx, 10] = aux12 - aux26 trn[idx, 11] = trn[idx, 10] - aux_9 sys.stdout.write('\r' + '%6d / %d' % (idx, aux_ii) + '\033[K') for idx, val in enumerate(trn[:-1]): if trn[idx + 1, 5] > 0.0: trn[idx, 12] = 1.0 trn[idx, 13] = 0.0 elif trn[idx + 1, 5] < 0.0: trn[idx, 12] = 0.0 trn[idx, 13] = 1.0 else: trn[idx, 12] = 0.0 trn[idx, 13] = 0.0 if tst[0, 5] > 0.0: trn[-1, 12] = 1.0 trn[-1, 13] = 0.0 elif tst[0, 5] < 0.0: trn[-1, 12] = 0.0 trn[-1, 13] = 1.0 else: trn[-1, 12] = 0.0 trn[-1, 13] = 0.0 for idx, val in enumerate(tst): if idx == 0: tst[idx, 5] = id.log_return(val[0], val[3], val[0], val[3]) else: tst[idx, 5] = id.log_return(val[0], val[3], trn[idx - 1, 0], trn[idx - 1, 3]) for idx, val in enumerate(tst[:-1]): if tst[idx + 1, 5] > 0.0: tst[idx, 12] = 1.0 tst[idx, 13] = 0.0 elif tst[idx + 1, 5] < 0.0: tst[idx, 12] = 0.0 tst[idx, 13] = 1.0 else: tst[idx, 12] = 0.0 tst[idx, 13] = 0.0 for i in goers_tst[1:]: tst[i - 1, 14] = 1.0 tst[-1, 14] = 1.0 for i in range(len(trn[0, :12])): mn.append(min(trn[:, i])) mx.append(1 / (max(trn[:, i]) - mn[i])) for i in enumerate(trn): for j in enumerate(i[1][:12]): trn[i[0], j[0]] = (j[1] - mn[j[0]]) * mx[j[0]] sys.stdout.write('\r' + '>> %6.2f: Data Prep Done!\n' % (time.time() - start) + '\033[K') return np.delete(trn, list(range(21)) + goers_trn, axis=0), tst
def __init__(self): self.config = Helper.Config() self.tradedatalength = self.config.overalldatalenght self.indicators = Indicators.TradingIndicators() self.printer = Printer.AplicationPrinter()
def __init__(self): self.config = Helper.Config() self.indicatorslength = self.config.indicatorsLength self.indicators = Indicators.TradingIndicators()
# FOR TOMORROW'S TRADING SESSION """ import pandas as pd import Indicators import matplotlib.pyplot as plt import numpy as np import matplotlib.finance as fnc fName = '/home/ale/Documenti/Trading Studies/Data/FIB_Data_New.xlsx' data = pd.read_excel(fName, Sheetname='1M') #%% df = pd.DataFrame(data['Close']) #Put Indicators Ind = Indicators.Indicator(df['Close']) df['Trend_Strength'] = Ind.Trend_Strength(50) df['RSI'] = Ind.RSI(20) df['RSI_MA2'] = df['RSI'].rolling(10).mean() df['RSI_MA1'] = df['RSI'].rolling(5).mean() df['EMA-10'] = Ind.EMA(10) df['EMA-20'] = Ind.EMA(20) df['MACD'] = Ind.MACD_Delta(50, 20, 10) df['MACD_MA2'] = df['MACD'].rolling(10).mean() df['MACD_MA1'] = df['MACD'].rolling(5).mean() #%% start = 6500 stop = 6700
def which_combo(api_info: list, indisignal: str) -> None: """figures out which signal/indicator function to call depending on input""" indisignal = indisignal.split() buy = sell = [] if indisignal[0] == "TR": indicator = Indicators.true_range() for item in api_info: temp = indicator.calculations(item) true_range_signal = signal_strategies.true_range( indisignal[1], indisignal[2]) buy_or_sell = true_range_signal.buy_or_sell_option(temp, item) if buy_or_sell == "": buy.append("") sell.append("") elif buy_or_sell == "BUY": buy.append(buy_or_sell) sell.append("") elif buy_or_sell == "SELL": sell.append(buy_or_sell) buy.append("") elif indisignal[0] == "MP": indicator = Indicators.moving_average(indisignal[1]) for item in api_info: temp = indicator.calculate(item) moving_avg_signal = signal_strategies.moving_average() buy_or_sell = moving_avg_signal.buy_or_sell_option(temp, item) if buy_or_sell == "": buy.append("") sell.append("") elif buy_or_sell == "BUY": buy.append(buy_or_sell) sell.append("") elif buy_or_sell == "SELL": sell.append(buy_or_sell) buy.append("") elif indisignal[0] == "MV": indicator = Indicators.moving_average_volume(indisignal[1]) for item in api_info: temp = indicator.calculate(item) moving_avg_vol_signal = signal_strategies.moving_average_volume() buy_or_sell = moving_avg_vol_signal.buy_or_sell_option(temp, item) if buy_or_sell == "": buy.append("") sell.append("") elif buy_or_sell == "BUY": buy.append(buy_or_sell) sell.append("") elif buy_or_sell == "SELL": sell.append(buy_or_sell) buy.append("") elif indisignal[0] == "DP": indicator = Indicators.directional_closing_indicator(indisignal[1]) for item in api_info: temp = indicator.calculations(item) directional_signal = signal_strategies.directional_closing_signal( indisignal[2], indisignal[3]) buy_or_sell = directional_signal.buy_or_sell_option(temp, item) if buy_or_sell == "": buy.append("") sell.append("") elif buy_or_sell == "BUY": buy.append(buy_or_sell) sell.append("") elif buy_or_sell == "SELL": sell.append(buy_or_sell) buy.append("") elif indisignal[0] == "DV": indicator = Indicators.directional_vol_indicator(indisignal[1]) for item in api_info: temp = indicator.calculations(item) directional_vol_signal = signal_strategies.directional_vol_signal( indisignal[2], indisignal[3]) buy_or_sell = directional_vol_signal.buy_or_sell_option(temp, item) if buy_or_sell == "": buy.append("") sell.append("") elif buy_or_sell == "BUY": buy.append(buy_or_sell) sell.append("") elif buy_or_sell == "SELL": sell.append(buy_or_sell) buy.append("") return [buy, sell, indicator]
def impulse_macd(df,n): df_macd = i.macd_hist(df) if df_macd.iloc[-n]>df_macd.iloc[-n-1]: return True return False
'PROFIT/LOSS %', 'VOL' ]] no_of_successful_cases = 0 no_of_failed_cases = 0 for stock_latest_info in stocks_latest_info: try: stock_latest_data = util.get_stock_latest_data( stock_latest_info[nse_bse.STOCK_ID], upstox_api, start_date, end_date, stock_latest_info[nse_bse.EXCHANGE]) stock_data_closing_prices_series = util.get_panda_series_of_stock_closing_prices( stock_latest_data) rsi_series = ind.rsi(stock_data_closing_prices_series, no_of_sessions_to_scan_for_RSI) i = no_of_sessions_to_skip_from_start while i + no_of_sessions_to_buffer_from_end < len(stock_latest_data): pivot = 1 if rsi_series.iloc[i] <= lower_limit_for_rsi: for j in range(i + 2, len(stock_latest_data)): pivot = j # print(stock_latest_data[i]) # exit(0) if rsi_series.iloc[j - 1] > upper_limit_for_rsi: if stock_latest_data[ j - 1]['close'] > stock_latest_data[i + 1]['open']:
def _100_day_EMA_with_200_Day_EMA(stock_data, backtesting=True): mares = MASResponse () mares.fetched_dataset=stock_data mares.ma_strategy_name = MA_Strategy_Name._100_DAY_EMA_WITH_200_DAY_EMA mares.fetch_date = util.get_date_from_timestamp(stock_data[-1]['timestamp']) stock_data_closing_prices_series=util.get_panda_series_of_stock_closing_prices(stock_data) _100_day_EMA_series=ind.ema(stock_data_closing_prices_series,100) _200_day_EMA_series = ind.ema(stock_data_closing_prices_series, 200) average_volume=util.calculate_last_10_days_average_volume (stock_data[-10:]) mares.average_volume = average_volume mares.stoploss = _100_day_EMA_series.iloc[-1] trend = get_89_ema_high_low_trend (stock_data) mares.trend = trend if (trend.value == Trend.uptrend.value) == False: mares.errors.append("No clear uptrend") mares.correct_trend = False if (average_volume > min_average_volume_to_consider) == False: mares.errors.append ("Last 10 day average volume:" + str (average_volume) + " not greater than min average volume to consider:" + str (min_average_volume_to_consider)) mares.high_volumes=False current_day_current_price = util.get_current_day_current_price (stock_data[-1]) mares.current_day_current_price=current_day_current_price if (calculate_slope (_100_day_EMA_series).value == Slope.UP.value) == False: mares.errors.append("_100_day_EMA_series not sloping upwards.") mares.sma_high_slope=False if (calculate_slope (_200_day_EMA_series).value == Slope.UP.value) == False: mares.errors.append ("_200_day_EMA_series not sloping upwards.") mares.lma_high_slope = False if(_100_day_EMA_series.iloc[-1]>_200_day_EMA_series.iloc[-1])== False: mares.errors.append ("100 day EMA:"+str(_100_day_EMA_series.iloc[-1])+" not greater than 200 day EMA:"+str(_200_day_EMA_series.iloc[-1])) mares.sma_greater_than_lma=False if (_100_day_EMA_series.iloc[-2] < _200_day_EMA_series.iloc[-2]) == False: mares.errors.append ( "Prev 100 day EMA:" + str (_100_day_EMA_series.iloc[-2]) + " not less than 200 day EMA:" + str ( _200_day_EMA_series.iloc[-2])) mares.prev_sma_less_than_lma = False mares.sma.append (append_ma_series ('100_day_EMA', _100_day_EMA_series)) mares.lma.append (append_ma_series ('200_day_EMA', _200_day_EMA_series)) if (current_day_current_price>_100_day_EMA_series.iloc[-1]) == False: mares.errors.append ("Current day current price:"+str(current_day_current_price)+" not greater than 100 day SMA:"+str(_100_day_EMA_series.iloc[-1])) mares.stock_price_greater_than_mas=False if backtesting: days_back_when_stock_price_less_than_sma=0 while days_back_when_stock_price_less_than_sma<len(stock_data): if (_100_day_EMA_series.iloc[-2 - days_back_when_stock_price_less_than_sma] > _200_day_EMA_series.iloc[ -2 - days_back_when_stock_price_less_than_sma]) == False: break days_back_when_stock_price_less_than_sma+=1 mares.days_back_when_stock_price_less_than_sma = days_back_when_stock_price_less_than_sma macd_series = ind.macd (stock_data_closing_prices_series) mares.macd.append (append_ma_series ('MACD', macd_series)) if (calculate_slope (macd_series).value == Slope.UP.value) == False: mares.errors.append ("MACD_series not sloping upwards.") mares.macd_high_slope = False if (macd_series.iloc[-1] > 0) == False: mares.errors.append ("MACD:" + str (macd_series.iloc[-1]) + "not greater than 0 ") mares.macd_greater_than_9_day_ema = False return mares
import seaborn as sns # Read mc3_p1.data df = pd.read_excel('Historical_Data/bitcoin price history.xlsx', index_col=0) df.index = pd.to_datetime(df.index, errors='coerce') # Calculate daily returns df['return'] = df['close'] / df['close'].shift(1) - 1 ta_df = df[['open', 'high', 'low', 'close', 'volume', 'return']].ix[1:] ta_df['next return'] = ta_df['return'].shift(-1) ta_df = ta_df.ix[:-1] # Technical analysis for i in range(5, 81): ta_df['rsi{}'.format(i)] = ta.rsi(ta_df['return'], i) ta_df['cci{}'.format(i)] = ta.cci(ta_df, i) ta_df['bb{}'.format(i)] = ta.bb(ta_df['close'], i) ta_df['wr{}'.format(i)] = ta.wr(ta_df, i) ta_df['atr{}'.format(i)] = ta.atr(ta_df, i) # Optomize obv indicator with two time periods def obv_opt(ohlc_df): short_period = range(5, 16) long_period = range(25, 81) obv_data = np.zeros((short_period[-1] + 1, long_period[-1] + 1)) for i in short_period: for j in long_period: ta_df['obv{}_{}'.format(i, j)] = ta.obv(ohlc_df, i, j)
def identify_long_term_stock_before_rally(stock_data, backtesting=True): mares = MASResponse () mares.fetched_dataset=stock_data mares.ma_strategy_name = MA_Strategy_Name.IDENTIFY_LONG_TERM_STOCK_BEFORE_RALLY mares.fetch_date = util.get_date_from_timestamp(stock_data[-1]['timestamp']) stock_data_closing_prices_series=util.get_panda_series_of_stock_closing_prices(stock_data) _50_day_SMA_series = ind.sma (stock_data_closing_prices_series, 50) _150_day_SMA_series=ind.sma(stock_data_closing_prices_series,150) _200_day_SMA_series = ind.sma(stock_data_closing_prices_series, 200) average_volume=util.calculate_last_10_days_average_volume (stock_data[-10:]) mares.average_volume = average_volume mares.stoploss = _50_day_SMA_series.iloc[-1] if (average_volume > min_average_volume_to_consider) == False: mares.errors.append ("Last 10 day average volume:" + str (average_volume) + " not greater than min average volume to consider:" + str (min_average_volume_to_consider)) mares.high_volumes=False trend = get_89_ema_high_low_trend (stock_data) mares.trend = trend if (trend.value == Trend.uptrend.value) == False: mares.errors.append("No clear uptrend") mares.correct_trend = False current_day_current_price = util.get_current_day_current_price (stock_data[-1]) mares.current_day_current_price=current_day_current_price if (calculate_slope (_50_day_SMA_series).value == Slope.UP.value) == False: mares.errors.append("_50_day_SMA_series not sloping upwards.") mares.sma_high_slope=False if (calculate_slope (_150_day_SMA_series).value == Slope.UP.value) == False: mares.errors.append ("_150_day_SMA_series not sloping upwards.") mares.lma_high_slope = False if (calculate_slope (_200_day_SMA_series, 30).value == Slope.UP.value) == False: mares.errors.append ("_200_day_SMA_series not sloping upwards for period:."+str(30)) mares.lma_high_slope = False if(_50_day_SMA_series.iloc[-1]>_150_day_SMA_series.iloc[-1] and _150_day_SMA_series.iloc[-1]>_200_day_SMA_series.iloc[-1])== False: mares.errors.append ("50 day EMA:"+str(_50_day_SMA_series.iloc[-1])+" not greater than 150 day SMA:"+str(_150_day_SMA_series.iloc[-1])+" not greater than 200 day EMA:"+str(_200_day_SMA_series.iloc[-1])) mares.sma_greater_than_lma=False if (_50_day_SMA_series.iloc[-2] < _150_day_SMA_series.iloc[-2] and _50_day_SMA_series.iloc[-2] < _200_day_SMA_series.iloc[-2]) == False: mares.errors.append ( "Prev 50 day EMA:" + str (_50_day_SMA_series.iloc[-2]) + " not less than 150 day SMA:" + str ( _150_day_SMA_series.iloc[-2]) + " not less than 200 day EMA:" + str (_200_day_SMA_series.iloc[-2])) mares.prev_sma_less_than_lma = False mares.sma.append (append_ma_series ('50_day_SMA', _50_day_SMA_series)) mares.lma.append (append_ma_series ('150_day_SMA', _150_day_SMA_series)) mares.lma.append (append_ma_series ('200_day_SMA', _200_day_SMA_series)) if (current_day_current_price > (_50_day_SMA_series.iloc[-1])) == False: mares.errors.append ("Current day current price:"+str(current_day_current_price)+" not greater than 50 day SMA:"+str(_50_day_SMA_series.iloc[-1])) mares.stock_price_greater_than_mas=False if backtesting: days_back_when_stock_price_less_than_sma=0 while days_back_when_stock_price_less_than_sma<len(stock_data): if (_50_day_SMA_series.iloc[-2 - days_back_when_stock_price_less_than_sma] > _150_day_SMA_series.iloc[ -2 - days_back_when_stock_price_less_than_sma]) == False: break days_back_when_stock_price_less_than_sma += 1 mares.days_back_when_stock_price_less_than_sma = days_back_when_stock_price_less_than_sma macd_series = ind.macd (stock_data_closing_prices_series) mares.macd.append (append_ma_series ('MACD', macd_series)) if (calculate_slope (macd_series).value == Slope.UP.value) == False: mares.errors.append ("MACD_series not sloping upwards.") mares.macd_high_slope = False if (macd_series.iloc[-1] > 0) == False: mares.errors.append ("MACD:" + str (macd_series.iloc[-1]) + "not greater than 0 ") mares.macd_greater_than_9_day_ema = False if (current_day_current_price>(1.3*float(stock_data[-1]['yearly_low'])))== False: mares.errors.append ( "Current day current price:" + str (current_day_current_price) + " not greater than 30% of yearly low:" + str ( stock_data[-1]['yearly_low'])) mares.stock_price_appropriately_placed_between_yearly_highs_lows=False if (current_day_current_price>(.75*float(stock_data[-1]['yearly_high'])))== False: mares.errors.append ( "Current day current price:" + str ( current_day_current_price) + " not greater than 75% of yearly high:" + str ( stock_data[-1]['yearly_high'])) mares.stock_price_appropriately_placed_between_yearly_highs_lows = False if(mares.stock_price_appropriately_placed_between_yearly_highs_lows==None): mares.stock_price_appropriately_placed_between_yearly_highs_lows=True rsi_series = ind.rsi (stock_data_closing_prices_series, 14) mares.rsi=rsi_series.iloc[-1] if (mares.rsi >70) == False: mares.errors.append ("<70 RSI value"+str(mares.rsi)) mares.correct_rsi=False if (mares.correct_rsi == None): mares.correct_rsi = True return mares
def signal_strategy(): Download.url=HTTP Final_url = Download._final_url_contents() Date = Final_url[0] date_list=[] closing_price_list=[] for i in Date: Day=i date_list.insert(0, Day) date_list.insert(0,'Date') date_list.pop() Title_closing_prices=Final_url[1] sma_list=[] Ticker_closing_prices=(Title_closing_prices[1:]) prices=Title_closing_prices[0:] for i in range(len(Ticker_closing_prices)): Ticker_closing_prices[i] = float(Ticker_closing_prices[i]) for i in prices: closing_price_list.append(i) response=input('What signal strategy would you like to use?(directional or sma)') if response=='sma': sma_list=[] strategy_list=[] days=signal_days() Indicator=Indicators.execute(Indicators.Simple_moving_average(days),Ticker_closing_prices) sma_list.append('Sma') for i in Indicator: myIndicator=i if i != None: myIndicator=str(i)[:6] sma_list.append(myIndicator) Strategy=Signal_strategies.execute(Signal_strategies.Signal_sma(Indicators.execute(Indicators.Simple_moving_average(days), Ticker_closing_prices),Ticker_closing_prices)) print(Strategy) strategy_list.append('Signal_strategies') for i in Strategy: myStrategy=i strategy_list.append(myStrategy) print(len(date_list)) print(len(closing_price_list)) print(len(sma_list)) print(len(strategy_list)) for i in range(len(date_list)): print('{:10} {:10} {:10} {:10}'.format(date_list[i], closing_price_list[i], sma_list[i],strategy_list[i])) elif response=='directional': indicator_list=[] strategy_list=[] days=signal_days() buy_threshold=int(input('What is the buy threshold')) sell_threshold=int(input('What is the sell threshold')) Indicator=Indicators.execute(Indicators.Directional_indicator(days),Ticker_closing_prices) indicator_list.append('Indicator') for i in Indicator: myIndicator=i indicator_list.append(myIndicator) Strategy=Signal_strategies.execute(Signal_strategies.Signal_Directional(Indicators.execute(Indicators.Directional_indicator(days),Ticker_closing_prices),buy_threshold,sell_threshold)) strategy_list.append('Signal_strategies') for i in Strategy: myStrategy=i strategy_list.append(myStrategy) for i in range(len(date_list)): print('{:10} {:10} {:10} {:10}'.format(date_list[i], closing_price_list[i], indicator_list[i], strategy_list[i])) else: print('You did not select simple-moving-average or directional. Please try again.') signal_strategy()
def guppy_multiple_moving_average_indicator(stock_data, backtesting=True): mares = MASResponse () mares.fetched_dataset=stock_data mares.ma_strategy_name = MA_Strategy_Name.GUPPY_MULTIPLE_MOVING_AVERAGE_INDICATOR mares.fetch_date = util.get_date_from_timestamp(stock_data[-1]['timestamp']) stock_data_closing_prices_series=util.get_panda_series_of_stock_closing_prices(stock_data) _3_day_EMA_series = ind.ema (stock_data_closing_prices_series, 3) _5_day_EMA_series = ind.ema (stock_data_closing_prices_series, 5) _8_day_EMA_series = ind.ema (stock_data_closing_prices_series, 8) _10_day_EMA_series = ind.ema (stock_data_closing_prices_series, 10) _12_day_EMA_series = ind.ema (stock_data_closing_prices_series, 12) _18_day_EMA_series = ind.ema (stock_data_closing_prices_series, 18) _30_day_EMA_series = ind.ema (stock_data_closing_prices_series, 30) _35_day_EMA_series = ind.ema (stock_data_closing_prices_series, 35) _40_day_EMA_series = ind.ema (stock_data_closing_prices_series, 40) _45_day_EMA_series = ind.ema (stock_data_closing_prices_series, 45) _50_day_EMA_series = ind.ema (stock_data_closing_prices_series, 50) _60_day_EMA_series = ind.ema (stock_data_closing_prices_series, 60) average_volume=util.calculate_last_10_days_average_volume (stock_data[-10:]) mares.average_volume = average_volume mares.stoploss = _3_day_EMA_series.iloc[-1] if (average_volume > min_average_volume_to_consider) == False: mares.errors.append ("Last 10 day average volume:" + str (average_volume) + "not greater than min average volume to consider:" + str (min_average_volume_to_consider)) mares.high_volumes=False trend = get_89_ema_high_low_trend (stock_data) mares.trend = trend if (trend.value == Trend.uptrend.value) == False: mares.errors.append("No clear uptrend") mares.correct_trend = False current_day_current_price = util.get_current_day_current_price (stock_data[-1]) mares.current_day_current_price=current_day_current_price if (calculate_slope (_3_day_EMA_series, 3).value == Slope.UP.value) == False: mares.errors.append("_3_day_EMA_series not sloping upwards.") mares.sma_high_slope=False if (calculate_slope (_5_day_EMA_series, 5).value == Slope.UP.value) == False: mares.errors.append ("_5_day_EMA_series not sloping upwards.") mares.sma_high_slope = False if (calculate_slope (_8_day_EMA_series).value == Slope.UP.value) == False: mares.errors.append ("_8_day_EMA_series not sloping upwards.") mares.sma_high_slope = False if (calculate_slope (_10_day_EMA_series).value == Slope.UP.value) == False: mares.errors.append ("_10_day_EMA_series not sloping upwards.") mares.sma_high_slope = False if (calculate_slope (_12_day_EMA_series).value == Slope.UP.value) == False: mares.errors.append ("_12_day_EMA_series not sloping upwards.") mares.sma_high_slope = False if (calculate_slope (_18_day_EMA_series).value == Slope.UP.value) == False: mares.errors.append ("_18_day_EMA_series not sloping upwards.") mares.sma_high_slope = False if (calculate_slope (_30_day_EMA_series).value == Slope.UP.value) == False: mares.errors.append ("_30_day_EMA_series not sloping upwards.") mares.lma_high_slope = False if (calculate_slope (_35_day_EMA_series).value == Slope.UP.value) == False: mares.errors.append ("_35_day_EMA_series not sloping upwards for period.") mares.lma_high_slope = False if (calculate_slope (_40_day_EMA_series).value == Slope.UP.value) == False: mares.errors.append ("_40_day_EMA_series not sloping upwards for period.") mares.lma_high_slope = False if (calculate_slope (_45_day_EMA_series).value == Slope.UP.value) == False: mares.errors.append ("_45_day_EMA_series not sloping upwards for period.") mares.lma_high_slope = False if (calculate_slope (_50_day_EMA_series).value == Slope.UP.value) == False: mares.errors.append ("_50_day_EMA_series not sloping upwards for period.") mares.lma_high_slope = False if (calculate_slope (_60_day_EMA_series).value == Slope.UP.value) == False: mares.errors.append ("_60_day_EMA_series not sloping upwards for period.") mares.lma_high_slope = False if(_3_day_EMA_series.iloc[-1]>_5_day_EMA_series.iloc[-1] and _5_day_EMA_series.iloc[-1]>_8_day_EMA_series.iloc[-1]and _8_day_EMA_series.iloc[-1]>_10_day_EMA_series.iloc[-1]and _10_day_EMA_series.iloc[-1]>_12_day_EMA_series.iloc[-1] and _12_day_EMA_series.iloc[-1]>_18_day_EMA_series.iloc[-1] and _18_day_EMA_series.iloc[-1]>_30_day_EMA_series.iloc[-1] and _30_day_EMA_series.iloc[-1]>_35_day_EMA_series.iloc[-1] and _35_day_EMA_series.iloc[-1]>_40_day_EMA_series.iloc[-1] and _40_day_EMA_series.iloc[-1]>_45_day_EMA_series.iloc[-1] and _45_day_EMA_series.iloc[-1]>_50_day_EMA_series.iloc[-1] and _50_day_EMA_series.iloc[-1]>_60_day_EMA_series.iloc[-1] )== False: mares.errors.append ("SEMAs & LEMAs not in increasing order:"+str(_3_day_EMA_series.iloc[-1])+", "+str(_5_day_EMA_series.iloc[-1])+", "+str(_8_day_EMA_series.iloc[-1])+", "+str(_10_day_EMA_series.iloc[-1])+", "+str(_12_day_EMA_series.iloc[-1])+", "+str(_18_day_EMA_series.iloc[-1])+", "+str(_30_day_EMA_series.iloc[-1])+", "+str(_35_day_EMA_series.iloc[-1])+", "+str(_40_day_EMA_series.iloc[-1])+", "+str(_45_day_EMA_series.iloc[-1])+", "+str(_50_day_EMA_series.iloc[-1])+", "+str(_60_day_EMA_series.iloc[-1])+".") mares.sma_greater_than_lma=False if (_3_day_EMA_series.iloc[-2] < _5_day_EMA_series.iloc[-2] and _3_day_EMA_series.iloc[-2] < _8_day_EMA_series.iloc[ -2]) == False: mares.errors.append ( "Prev 3 day EMA:" + str (_3_day_EMA_series.iloc[-2]) + " not less than 5 day SMA:" + str ( _5_day_EMA_series.iloc[-2]) + " not less than 8 day EMA:" + str (_8_day_EMA_series.iloc[-2])) mares.prev_sma_less_than_lma = False if (divergence_exists(mares, [_3_day_EMA_series,_5_day_EMA_series,_8_day_EMA_series,_10_day_EMA_series,_12_day_EMA_series, _18_day_EMA_series, _30_day_EMA_series,_35_day_EMA_series,_40_day_EMA_series,_45_day_EMA_series, _50_day_EMA_series,_60_day_EMA_series]) == True) == False: mares.errors.append ("No upward divergence between MAs.") mares.mas_diverging = False if mares.mas_diverging==None: mares.mas_diverging = True mares.sma.append (append_ma_series ('3_day_EMA', _3_day_EMA_series)) mares.sma.append (append_ma_series ('5_day_EMA', _5_day_EMA_series)) mares.sma.append (append_ma_series ('8_day_EMA', _8_day_EMA_series)) mares.sma.append (append_ma_series ('10_day_EMA', _10_day_EMA_series)) mares.sma.append (append_ma_series ('12_day_EMA', _12_day_EMA_series)) mares.sma.append (append_ma_series ('18_day_EMA', _18_day_EMA_series)) mares.lma.append (append_ma_series ('30_day_EMA', _30_day_EMA_series)) mares.lma.append (append_ma_series ('35_day_EMA', _35_day_EMA_series)) mares.lma.append (append_ma_series ('40_day_EMA', _40_day_EMA_series)) mares.lma.append (append_ma_series ('45_day_EMA', _45_day_EMA_series)) mares.lma.append (append_ma_series ('50_day_EMA', _50_day_EMA_series)) mares.lma.append (append_ma_series ('60_day_EMA', _60_day_EMA_series)) if (current_day_current_price>_3_day_EMA_series.iloc[-1]) == False: mares.errors.append ("Current day current price:"+str(current_day_current_price)+" not greater than 3 day SMA:"+str(_3_day_EMA_series.iloc[-1])) mares.stock_price_greater_than_mas=False if backtesting: days_back_when_stock_price_less_than_sma=0 while days_back_when_stock_price_less_than_sma<len(stock_data): if (_3_day_EMA_series.iloc[-2 - days_back_when_stock_price_less_than_sma] > _5_day_EMA_series.iloc[ -2 - days_back_when_stock_price_less_than_sma]) == False: break days_back_when_stock_price_less_than_sma += 1 mares.days_back_when_stock_price_less_than_sma = days_back_when_stock_price_less_than_sma macd_series = ind.macd (stock_data_closing_prices_series) mares.macd.append (append_ma_series ('MACD', macd_series)) if (calculate_slope (macd_series).value == Slope.UP.value) == False: mares.errors.append ("MACD_series not sloping upwards.") mares.macd_high_slope = False if (macd_series.iloc[-1] > 0) == False: mares.errors.append ("MACD:" + str (macd_series.iloc[-1]) + "not greater than 0 ") mares.macd_greater_than_9_day_ema = False return mares
def calcDirectional(days:int, closePrices:list): g = Indicators.directionalIndicator(days) return g.execute(closePrices)
def _50_week_SMA_20_day_RSI(stock_data, backtesting=True): mares = MASResponse () mares.fetched_dataset=stock_data mares.ma_strategy_name = MA_Strategy_Name._50_WEEK_SMA_20_DAY_RSI mares.fetch_date = util.get_date_from_timestamp(stock_data[-1]['timestamp']) stock_data_closing_prices_series=util.get_panda_series_of_stock_closing_prices(stock_data) _250_day_SMA_series=ind.sma(stock_data_closing_prices_series,250) mares.sma_greater_than_lma=None average_volume=util.calculate_last_10_days_average_volume (stock_data[-10:]) mares.average_volume = average_volume mares.stoploss = _250_day_SMA_series.iloc[-1] if (average_volume > min_average_volume_to_consider) == False: mares.errors.append ("Last 10 day average volume:" + str (average_volume) + "not greater than min average volume to consider:" + str (min_average_volume_to_consider)) mares.high_volumes=False trend = get_89_ema_high_low_trend (stock_data) mares.trend = trend if (trend.value == Trend.uptrend.value) == False: mares.errors.append("No clear uptrend") mares.correct_trend = False current_day_current_price = util.get_current_day_current_price (stock_data[-1]) mares.current_day_current_price=current_day_current_price mares.sma_high_slope=None if (calculate_slope (_250_day_SMA_series).value == Slope.UP.value) == False: mares.errors.append("_250_day_SMA_series not sloping upwards.") mares.lma_high_slope=False mares.lma.append (append_ma_series ('250_day_SMA', _250_day_SMA_series)) if (current_day_current_price>_250_day_SMA_series.iloc[-1] ) == False: mares.errors.append ("Current day current price:"+str(current_day_current_price)+" not greater than 250 day SMA:"+str(_250_day_SMA_series.iloc[-1])) mares.stock_price_greater_than_mas=False if backtesting: days_back_when_stock_price_less_than_sma=0 while days_back_when_stock_price_less_than_sma<len(stock_data): earlier_mares=_50_week_SMA_20_day_RSI(stock_data[:-1-days_back_when_stock_price_less_than_sma],False) if earlier_mares.is_strategy_tradable()==False: break days_back_when_stock_price_less_than_sma+=1 mares.days_back_when_stock_price_less_than_sma = days_back_when_stock_price_less_than_sma macd_series = ind.macd (stock_data_closing_prices_series) mares.macd.append (append_ma_series ('MACD', macd_series)) if (calculate_slope (macd_series).value == Slope.UP.value) == False: mares.errors.append ("MACD_series not sloping upwards.") mares.macd_high_slope = False if (macd_series.iloc[-1] > 0) == False: mares.errors.append ("MACD:" + str (macd_series.iloc[-1]) + "not greater than 0 ") mares.macd_greater_than_9_day_ema = False rsi_series = ind.rsi (stock_data_closing_prices_series, 20) mares.rsi = rsi_series.iloc[-1] if (mares.rsi>50) == False: mares.errors.append ("<50 RSI value"+str(mares.rsi)) mares.correct_rsi = False if (mares.correct_rsi == None): mares.correct_rsi = True return mares