def evaluate_moving_avg(number_of_twisted_points=3, from_last_twisted_point_to_forward=3, direction_error=5 / 100, consecutive_error=10 / 100, ema_fast_v=14, ema_slow_v=21, prediction_index=30): print("--start--") print(number_of_twisted_points, from_last_twisted_point_to_forward, direction_error, consecutive_error, ema_fast_v, ema_slow_v, prediction_index) corrections = [] for idx in tqdm(range(100, len(price) - prediction_index)): try: values = price.values[idx - 100:idx] feature_values = price.values[idx - 100:idx + prediction_index] prediction_values = price.values[idx:idx + prediction_index] ema_fast = simple_moving_average(values, ema_fast_v) sma_slow = simple_moving_average(values, ema_slow_v) max_cut_point = max([ema_slow_v, ema_fast_v]) values, feature_values, ema_fast, sma_slow = values[ max_cut_point:], feature_values[max_cut_point:], ema_fast[ max_cut_point:], sma_slow[max_cut_point:] pattern, x_point = moving_average_signal( values, ema_fast, sma_slow, number_of_twisted_points=number_of_twisted_points, from_last_twisted_point_to_forward= from_last_twisted_point_to_forward, consecutive_error=consecutive_error, direction_error=direction_error) if pattern is not np.nan: true_value = prediction_values[0] - prediction_values[-1] real_trend = 0 if true_value > 0: real_trend = -1 else: real_trend = 1 corrections.append(real_trend == pattern) # except Exception as e: print(e) e.with_traceback(traceback) traceback.print_tb(e.__traceback__) finally: pass corrections = np.array(corrections) correction_val = len(np.where(corrections)[0]) * 100 / len(corrections) prediction_rate = len(corrections) * 100 / idx print( f"Correction {len(corrections)},{idx} {prediction_rate} {correction_val}" ) print(f"Rate {(correction_val + prediction_rate) / 2}") return (correction_val + prediction_rate) / 2
def relative_sma(data, short, long): sma_short = simple_moving_average(data, period=short) sma_long = simple_moving_average(data, period=long) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) smadiff = sma_short - sma_long rsma = np.divide(smadiff, sma_long) return fill_for_noncomputable_vals(data, rsma)
def test_simple_moving_average_invalid_period(self): period = 128 with self.assertRaises(Exception) as cm: simple_moving_average.simple_moving_average(self.data, period) expected = "Error: data_len < period" self.assertEqual(str(cm.exception), expected)
def test_simple_moving_average_period_10(self): period = 10 sma = simple_moving_average.simple_moving_average(self.data, period) np.testing.assert_array_equal(sma, self.sma_perio_10_expected)
def data_to_indicators(data, o, h, l, c, v, window) -> pd.DataFrame: """ Given a DataFrame of stock prices, return the data along with the corresponding indicators :param data: Data in C-OHLV format :param window: default value of window for indicators (only for indicators that support this) :param o: name of column containing 'OPEN' values :param h: name of column containing 'HIGH' values :param l: name of column containing 'LOW' values :param c: name of column containing 'CLOSE' values :param v: name of column containing 'VOLUME' values :return: DataFrame with all indicators """ df = data.reset_index(drop=True) # Momentum # TODO PMO df['macd_' + str(window)] = macd(df[c], n_fast=int(window / 2), n_slow=window) df['rsi_' + str(window)] = rsi(df[c], n=window) df['wr_' + str(window)] = wr(df[h], df[l], df[c], lbp=window) df['mfi_' + str(window)] = money_flow_index(df[h], df[l], df[c], df[v], n=window) df['stochk_' + str(window)] = stoch(df[h], df[l], df[c], n=window) df['stochd_' + str(window)] = stoch_signal(df[h], df[l], df[c], n=window, d_n=3) # ROC df['roc_' + str(window)] = [(df[c][i] - df[c][i - window]) / df[c][i - window] if i >= window else np.nan for i in range(0, df[c].size)] # Smoothing df['sma_' + str(window)] = simple_moving_average.simple_moving_average(df[c], period=window) df['wma_' + str(window)] = weighted_moving_average.weighted_moving_average(df[c], period=window) df['ema_' + str(window)] = exponential_moving_average.exponential_moving_average(np.array(df[c]), period=window) df['hma_' + str(window)] = hull_moving_average.hull_moving_average(np.array(df[c]), period=window) # df['cma_' + str(window)] = [df[c][i - int(window / 2): i + int(window / 2)].mean() # if (i >= int(window / 2) and (i + int(window / 2)) < df[c].size) else np.nan # for i in range(0, df[c].size)] # Overbought/Oversold Signals df['cci_' + str(window)] = cci(df[h], df[l], df[c], n=window, c=0.015) # Volume df['adl'] = acc_dist_index(df[h], df[l], df[c], df[v]) df['cmf_' + str(window)] = chaikin_money_flow(df[h], df[l], df[c], df[v], n=window) df['obv'] = on_balance_volume(df[c], df[v]) df['emv_' + str(window)] = ease_of_movement(df[h], df[l], df[c], df[v], n=window) # Volatility df['atr_' + str(window)] = average_true_range(df[h], df[l], df[c], n=window) df['mass_ind_' + str(window)] = mass_index(df[h], df[l], n=window / 2, n2=window) # Trends # How will model know b/w Ichmoku A and B? df['ichimoku_a'] = ichimoku_a(df[h], df[l], n1=9, n2=26) df['ichimoku_b'] = ichimoku_b(df[h], df[l], n2=26, n3=52) series_aroon_up = aroon_up(df[c], n=window) series_aroon_down = aroon_down(df[c], n=window) df['aroon_ind_' + str(window)] = series_aroon_up - series_aroon_down df['adx_' + str(window)] = adx(df[h], df[l], df[c], n=window) return df
def read_float_with_comma(x): y = [] for i in x: y.append(float(i.replace(",", ""))) return y period = 10 dataset_train = pd.read_csv( '/Users/T/Desktop/ML/StockIndicators/RBMtime/Google_Stock_Price_Train.csv') dataset_test = pd.read_csv( '/Users/T/Desktop/ML/StockIndicators/RBMtime/Google_Stock_Price_Test.csv') #dataset_train = dataset_test from pyti.simple_moving_average import simple_moving_average x = dataset_train.iloc[:, 4].values ans = simple_moving_average(read_float_with_comma(x), 10) open = dataset_train.iloc[:, 1].values high = dataset_train.iloc[:, 2].values low = dataset_train.iloc[:, 3].values close = read_float_with_comma(dataset_train.iloc[:, 4].values) volume = read_float_with_comma(dataset_train.iloc[:, 5].values) from pyti.simple_moving_average import simple_moving_average sma = simple_moving_average(close, period) from pyti.weighted_moving_average import weighted_moving_average wma = weighted_moving_average(close, period) from pyti.momentum import momentum mome = momentum(close, period)
def convert(str): period = 10 dataset_train = pd.read_csv(str) x = dataset_train.iloc[:, 4].values try: open = dataset_train.iloc[:, 1].values except Exception: open = read_float_with_comma(dataset_train.iloc[:, 1].values) try: high = dataset_train.iloc[:, 2].values except Exception: high = read_float_with_comma(dataset_train.iloc[:, 2].values) try: low = dataset_train.iloc[:, 3].values except Exception: low = read_float_with_comma(dataset_train.iloc[:, 3].values) try: close = dataset_train.iloc[:, 4].values except Exception: close = read_float_with_comma(dataset_train.iloc[:, 4].values) try: volume = dataset_train.iloc[:, 5].values except Exception: volume = read_float_with_comma(dataset_train.iloc[:, 5].values) from pyti.simple_moving_average import simple_moving_average sma = simple_moving_average(close, period) from pyti.weighted_moving_average import weighted_moving_average wma = weighted_moving_average(close, period) from pyti.momentum import momentum mome = momentum(close, period) from pyti.relative_strength_index import relative_strength_index rsi = relative_strength_index(close, period) from pyti.moving_average_convergence_divergence import moving_average_convergence_divergence macd = moving_average_convergence_divergence(close, short_period=1, long_period=10) from pyti.commodity_channel_index import commodity_channel_index cci = commodity_channel_index(close, high_data=high, low_data=low, period=period) from pyti.williams_percent_r import williams_percent_r willr = williams_percent_r(close) from pyti.accumulation_distribution import accumulation_distribution acd = accumulation_distribution(close_data=close, low_data=low, high_data=high, volume=volume) X = [] Y = [] for _ in range(10, len(open)): tmp = [] tmp.append(sma[_]) tmp.append(wma[_]) tmp.append(mome[_]) tmp.append(rsi[_]) tmp.append(macd[_]) tmp.append(cci[_]) tmp.append(willr[_]) X.append(tmp) Y.append([close[_]]) X, Y = np.array(X), np.array(Y) return X, Y
def simplemovingAvg(dataset): cap='SimpleMovingAverage' period = 6 sma = simple_moving_average.simple_moving_average(dataset, period) np.testing.assert_array_equal(sma, functions.setUp().sma_period_6_expected) return dataset