def addRsi(df, fibos): log.info('Adding RSI {0}'.format(fibos)) rsis = {} for n in fibos: rsis[n] = rsi(df, n) for i, n in enumerate(fibos): for m in fibos[i+1:]: df['rsi_{0}_{1}'.format(n, m)] = rsis[n] / rsis[m] df.replace(to_replace=[np.inf, -np.inf], value=0, method='ffil', inplace=True) df.fillna(0, inplace=True) log.info('Added RSI {0}'.format(fibos))
def addEvidence(self, symbol = "IBM", \ sd=dt.datetime(2008,1,1), \ ed=dt.datetime(2009,1,1), \ sv = 10000): # example usage of the old backward compatible util function syms = [symbol] dates = pd.date_range(sd + dt.timedelta(-30), ed) prices_all = ut.get_data(syms, dates) # automatically adds SPY prices = prices_all[syms] # only portfolio symbols prices_SPY = prices_all['SPY'] # only SPY, for comparison later #if self.verbose: print prices # indicators cross, macd = indicators.macd(prices) rsi, ind = indicators.rsi(prices) sma = indicators.rolling_mean(prices) macd = macd[macd.index > sd] rsi = rsi[rsi.index > sd] sma = sma[sma.index > sd] prices = prices[prices.index > sd] #discretization macd_bin = pd.cut(macd.transpose().iloc[0], 5, labels=[0, 1, 2, 3, 4]).astype(int) rsi_bin = pd.cut(rsi.transpose().iloc[0], 5, labels=[0, 1, 2, 3, 4]).astype(int) sma_bin = pd.cut(sma.transpose().iloc[0], 5, labels=[0, 1, 2, 3, 4]).astype(int) state = macd_bin + rsi_bin * 5 + sma_bin * 25 epoch = 0 temp = 0 total_reward = 10 # # add your code to do learning here while temp != total_reward and epoch < 200: #print(temp, total_reward) #print(state) epoch += 1 temp = total_reward action = self.learner.querysetstate(0) #print("a",action) holdings = 0 port_val = 0 total_reward = 0 cash = sv for i in range(1, len(prices)): if (action == 0): pass elif (action == 1): #buy or long position if (holdings == 1000): pass elif (holdings == 0): #buy 1000 shares holdings += 1000 cash -= (holdings * prices.iloc[i - 1] * (1 + self.impact)) port_val += (holdings * prices.iloc[i - 1] * (1 + self.impact)) elif (holdings == -1000): #buy 2000 shares holdings += 2000 cash -= (holdings * prices.iloc[i - 1] * (1 + self.impact)) port_val += (holdings * prices.iloc[i - 1] * (1 + self.impact)) elif (action == 2): #sell or short position if (holdings == -1000): pass elif (holdings == 0): #short 1000 shares holdings -= 1000 cash += (holdings * prices.iloc[i - 1] * (1 - self.impact)) port_val -= (holdings * prices.iloc[i - 1] * (1 - self.impact)) elif (holdings == 1000): #short 2000 shares holdings -= 2000 cash += (holdings * prices.iloc[i - 1] * (1 - self.impact)) port_val -= (holdings * prices.iloc[i - 1] * (1 - self.impact)) #stepreward = int((prices.iloc[i] - prices.iloc[i-1]))*holdings*(1-self.impact) stepreward = ( (float((prices.iloc[i] - prices.iloc[i - 1])) / float(prices.iloc[i - 1])) - self.impact) * holdings action = self.learner.query(state[i], stepreward) total_reward += stepreward
def testPolicy(self, symbol = "IBM", \ sd=dt.datetime(2009,1,1), \ ed=dt.datetime(2010,1,1), \ sv = 10000): # here we build a fake set of trades # your code should return the same sort of data dates = pd.date_range(sd, ed) prices_all = ut.get_data([symbol], dates) # automatically adds SPY prices = prices_all[[symbol]] # only portfolio symbols prices_SPY = prices_all['SPY'] # only SPY, for comparison later #if self.verbose: print prices # indicators cross, macd = indicators.macd(prices) rsi, ind = indicators.rsi(prices) sma = indicators.rolling_mean(prices) macd_bin = pd.cut(macd.transpose().iloc[0], 5, labels=[0, 1, 2, 3, 4]).astype(int) rsi_bin = pd.cut(rsi.transpose().iloc[0], 5, labels=[0, 1, 2, 3, 4]).astype(int) sma_bin = pd.cut(sma.transpose().iloc[0], 5, labels=[0, 1, 2, 3, 4]).astype(int) state = macd_bin + rsi_bin * 5 + sma_bin * 25 holdings = 0 total_reward = 0 port_val = sv #trades trades = prices_all[[ symbol, ]] # only portfolio symbols trades_SPY = prices_all['SPY'] # only SPY, for comparison later trades.values[:, :] = 0 for j, i in state.iteritems(): #print(int(port_val)) action = np.argmax(self.learner.Q[i]) if action == 0: reward = int((prices.iloc[i] - prices.iloc[i - 1]) * holdings * (1 - self.impact)) total_reward += reward elif action == 2: #selling if holdings == 0: reward = int((prices.iloc[i] - prices.iloc[i - 1]) * -1000 * (1 - self.impact)) holdings -= 1000 trades.loc[j][0] = -1000 total_reward += reward port_val -= prices.iloc[i - 1] * 1000 elif holdings == 1000: reward = int((prices.iloc[i] - prices.iloc[i - 1]) * -2000 * (1 - self.impact)) holdings -= 2000 trades.loc[j][0] = -2000 total_reward += reward port_val -= prices.iloc[i - 1] * 2000 elif action == 1: #buying if holdings == -1000: reward = int((prices.iloc[i] - prices.iloc[i - 1]) * 2000 * (1 - self.impact)) holdings += 2000 trades.loc[j][0] = 2000 total_reward += reward port_val += prices.iloc[i - 1] * 2000 elif holdings == 0: reward = int((prices.iloc[i] - prices.iloc[i - 1]) * 1000 * (1 - self.impact)) holdings += 1000 trades.loc[j][0] = 1000 total_reward += reward port_val += prices.iloc[i - 1] * 1000 if self.verbose: print type(trades) # it better be a DataFrame! if self.verbose: print trades if self.verbose: print prices_all return trades
average2 = sum(contra_media) / len(contra_media) return contra_media[0], average2 def getNparse_candles(market='BTCUSDT', limit=100, period=14: # get and write init data orders = {} url = 'https://api.binance.com/api/v3/trades?symbol=' + market + '&limit=' + str(limit) + '' init_candles = requests.get(url).json() # get penta rsi my_rsi = rsi(np.array([float(prz['price']) for prz in init_candles]), period) # relleno los valores del periodo faltante para casar con la tabla pad = [50 for _ in range(period)] my_rsi = np.insert(my_rsi, 0, pad) for candle in init_candles: order_id = candle['id'] price = float(candle['price']) qty = float(candle['qty']) timestamp = candle['time'] rsi_index = float(my_rsi[init_candles.index(candle)]) my_date = datetime.fromtimestamp(timestamp / 1000) # print({order_id: [my_date, price, qty, rsi_index]}) orders.update({order_id: [my_date, price, qty, rsi_index]})
def testPolicy(self, symbol="IBM", \ sd=dt.datetime(2009, 1, 1), \ ed=dt.datetime(2010, 1, 1), \ sv=10000): ''' # # here we build a fake set of trades # # your code should return the same sort of data # dates = pd.date_range(sd, ed) # prices_all = ut.get_data([symbol], dates) # automatically adds SPY # prices = prices_all[[symbol, ]] # trading_days = prices.index # # price_sma, rsi, macd_hist = get_indicators(prices) # # xvalues = pd.concat([price_sma, rsi, macd_hist], ignore_index=True, axis=1) # # print '=====xvalues=====\n', xvalues # xvalues.fillna(value=0, inplace=True) # testX = np.array(xvalues) ''' # stock_older_days = 30 symbols = [symbol] prices, sma, p_to_sma = indicators.price_sma(start_date=sd, end_date=ed, symbols=symbols) prices.columns = ['Price'] sma.columns = ['sma'] p_to_sma.columns = ['p/sma'] rsi = indicators.rsi(start_date=sd, end_date=ed, symbols=symbols) mfi = indicators.mfi(start_date=sd, end_date=ed, symbols=symbols) vix = indicators.vix(start_date=sd, end_date=ed, symbols=symbols) rsi.columns = ['RSI'] mfi.columns = ['MFI'] vix.columns = ['VIX'] portfolio = prices.copy() portfolio.iloc[:, :] = np.nan Xtrain = pd.concat([p_to_sma, rsi, mfi, vix], axis=1) Xtrain.fillna(value=0, inplace=True) # print '=========Xtrain=======\n', Xtrain trading_days = Xtrain.index testX = Xtrain.values[:, 1:] # print '=========trainX=======\n', testX # print '==========textX====\n', testX triggers = self.learner.query(testX) # print '==========triggers====\n', triggers triggers = pd.DataFrame(triggers[0], index=trading_days) # use this for bag learner: triggers = pd.DataFrame(triggers[0], index=trading_days) status = 'cash' trades = prices.copy() trades.values[:, :] = 0 # set them all to nothing total_triggers = triggers.shape[0] trading_days = list(prices.index) j = 0 for i in range(total_triggers): # option = triggers.ix[i, symbol][0] option = triggers.ix[i, 0] gap = trading_days.index(triggers.index[i]) - trading_days.index(triggers.index[j]) if status == 'cash': if option == 1.0: trades.ix[triggers.index[i], :] = 1000 status = 'long' j = i elif option == -1.0: trades.ix[triggers.index[i], :] = -1000 status = 'short' j = i elif status == 'long': if (option == 0.0) & (gap >= self.N): trades.ix[triggers.index[i], :] = -1000 status = 'cash' j = i elif (option == -1.0) & (gap >= self.N): trades.ix[triggers.index[i], :] = -2000 status = 'short' j = i elif status == 'short': if (option == 0.0) & (gap >= self.N): trades.ix[triggers.index[i], :] = 1000 status = 'cash' j = i elif (option == 1.0) & (gap >= self.N): trades.ix[triggers.index[i], :] = 2000 status = 'long' j = i if self.verbose: print type(trades) # it better be a DataFrame! if self.verbose: print trades return trades
'ma_med_5'] / stocks_dict[ticker]['Close'] stocks_dict[ticker]['ma_med_34_ratio'] = stocks_dict[ticker][ 'ma_med_34'] / stocks_dict[ticker]['Close'] stocks_dict[ticker]['macd'], stocks_dict[ticker][ 'macd_signal'] = get_macd_columns_for_stock(stocks_dict[ticker], 12, 26, 9) stocks_dict[ticker]['atr'] = get_ATR_column_for_stock( stocks_dict[ticker], 14) stocks_dict[ticker][ 'distance_from_10_ma'] = get_distance_between_columns_for_stock( stocks_dict[ticker], 'Close', '10_ma') stocks_dict[ticker]['adx'], stocks_dict[ticker]['+di'], stocks_dict[ ticker]['-di'] = get_adx_column_for_stock(stocks_dict[ticker], 14) stocks_dict[ticker]['adx_ma_med_5_rat'] = stocks_dict[ticker][ 'adx'] * stocks_dict[ticker]['ma_med_5_ratio'] stocks_dict[ticker]['rsi'] = rsi(stocks_dict[ticker], 2) # changed from 14 stocks_dict[ticker]['stochastic_k'], stocks_dict[ticker][ 'stochastic_d'] = stochastic(stocks_dict[ticker], 14, 3) stocks_dict[ticker]['atr_volatility'], stocks_dict[ticker][ 'atr_volatility_ma'] = get_volatility_from_atr(stocks_dict[ticker], 14) stocks_dict[ticker]['signal_type'] = '' stocks_dict[ticker]['signal_direction'] = '' stocks_dict[ticker]['indicators_mid_levels_signal'] = '' stocks_dict[ticker]['indicators_mid_level_direction'] = '' stocks_dict[ticker]['cross_20_signal'] = '' stocks_dict[ticker]['cross_20_direction'] = '' stocks_dict[ticker]['cross_50_signal'] = '' stocks_dict[ticker]['cross_50_direction'] = '' # signal_type and signal_direction columns are the columns that determine the actual orders! # stocks_dict[ticker] = indicators_mid_levels_signal(stocks_dict[ticker], 'indicators_mid_level_direction', 'indicators_mid_levels_signal') # stocks_dict[ticker] = cross_20_ma(stocks_dict[ticker], 'cross_20_direction', 'cross_20_signal')
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)
def get_fx_file_paths(fx_pair, agg_level, agg_magnitude, tech_indicators, data_dir, is_test = False, train_end = '2019-02-01'): input_path = os.path.join(data_dir, 'csv') output_path = os.path.join(data_dir, 'npy') train_end = np.datetime64(train_end) phases = ['train', 'test'] file_paths = {phase : os.path.join(output_path, f"""{fx_pair.upper()}_{str(agg_magnitude)}_{agg_level}_{phase}_{'_'.join([str(y) for x in list(tech_indicators.items()) for y in x]).replace(', ', '_')}.npy""") for phase in phases} # Return if data exists if os.path.exists(file_paths['train']): return file_paths['train'] # Otherwise create it print(f'Creating data {file_paths}') file_list = [x for x in os.listdir(input_path) if fx_pair in x] fx_npy = {x : None for x in phases} for file_name in tqdm(file_list, total = len(file_list)): # Read file and setup df = pd.read_csv(os.path.join(input_path, file_name), header = None, names = ['fx_pair', 'timestamp', 'bid', 'ask']) df = df.drop('fx_pair', axis = 1) df['timestamp'] = pd.to_datetime(df['timestamp'], format = '%Y%m%d %H:%M:%S.%f') df = df.dropna() df = df[['timestamp', 'bid', 'ask']] df['price'] = df[['bid', 'ask']].mean(axis = 1) df = df.drop(['bid', 'ask'], axis = 1) # Set phase if df['timestamp'].max() < train_end: phase = 'train' else: phase = 'test' # Aggregate data at level and magnitude df = df.set_index('timestamp') df = df.resample(f'{agg_magnitude}{agg_level}', label = 'right').ohlc()['price'].reset_index() df['timestamp'] = df['timestamp'].astype(int) # Calc technical indicators for indicator,params in tech_indicators.items(): if indicator == 'macd': df = indicators.macd(df, *params) elif indicator == 'rsi': df = indicators.rsi(df, *params) elif indicator == 'adx': df = indicators.adx(df, *params) else: raise Exception(f'Unrecognized technical indicator {indicator}') # Add to phase numpy array df_np = df.dropna().to_numpy() assert np.sum(np.isnan(df_np)) == 0 if fx_npy[phase] is None: fx_npy[phase] = df_np else: fx_npy[phase] = np.vstack([fx_npy[phase], df_np]) for phase in fx_npy.keys(): np.save(file_paths[phase], fx_npy[phase]) file_path = file_paths['test'] if is_test else file_paths['train'] return file_path
def addEvidence(self, symbol = "IBM", \ sd=dt.datetime(2008,1,1), \ ed=dt.datetime(2009,1,1), \ sv = 10000): ## Initialize Q Learner self.learner = ql.QLearner(num_states=3000, \ num_actions=3, \ alpha=0.2, \ gamma=0.9, \ rar=0.98, \ radr=0.999, \ dyna=0, \ verbose=False) ## 14 day lookback period lookback_dates = pd.date_range(sd - dt.timedelta(days=30), ed) ## Get Prices prices = ut.get_data([symbol], lookback_dates) prices = prices.ix[:, [symbol]] prices = prices.fillna(method='ffill', inplace=False) prices = prices.fillna(method='bfill', inplace=False) ## Get indicators priceOverSMAValues = priceOverSMA(prices) bbpValues = bbp(prices) rsiValues = rsi(prices) self.prices = prices.ix[sd:] self.symbol = symbol ## Discretize priceOverSMAValues = priceOverSMAValues.ix[sd:] priceOverSMAValues[symbol] = pd.qcut(priceOverSMAValues[symbol].values, 10).codes bbpValues = bbpValues.ix[sd:] bbpValues[symbol] = pd.qcut(bbpValues[symbol].values, 10).codes rsiValues = rsiValues.ix[sd:] rsiValues[symbol] = pd.qcut(rsiValues[symbol].values, 10).codes ## Set up state states = (priceOverSMAValues * 100) + (bbpValues * 10) + rsiValues * 1 ##Update Q Table until converged converged = False prev_total_reward = 0 reward_match_count = 0 while not converged: state = states.ix[0, symbol] action = self.learner.querysetstate(state) net_position = self.NONE total_days = states.shape[0] total_reward = 0 for day in range(1, total_days): net_position = action reward = self.getReward(net_position, day) total_reward += reward state = states.ix[day, symbol] action = self.learner.query(state, reward) prev_total_reward = total_reward if total_reward == prev_total_reward: reward_match_count += 1 if reward_match_count == 5: converged = True
def addEvidence(self, symbol="IBM", \ sd=dt.datetime(2008, 1, 1), \ ed=dt.datetime(2009, 1, 1), \ sv=10000): '''Firstly assemble the indicators into the trainning Dataframe (Xtrain and Ytrain), then train the RTLearner''' '''calculate indicators''' stock_older_days = 45 symbols = [symbol] prices, unused_a, unused_b = indicators.price_sma( start_date=(sd - dt.timedelta(days=stock_older_days)), end_date=ed, symbols=symbols) first_trading_day = sd while first_trading_day not in prices.index: first_trading_day += dt.timedelta(days=1) prices = prices / prices.loc[first_trading_day] sma = prices.copy().rolling(14).mean() p_to_sma = prices / sma prices.columns = ['Price'] sma.columns = ['sma'] p_to_sma.columns = ['p/sma'] rsi = indicators.rsi(start_date=(sd - dt.timedelta(days=stock_older_days)), end_date=ed, symbols=symbols) mfi = indicators.mfi(start_date=(sd - dt.timedelta(days=stock_older_days)), end_date=ed, symbols=symbols) vix = indicators.vix(start_date=sd, end_date=ed, symbols=symbols) rsi.columns = ['RSI'] mfi.columns = ['MFI'] vix.columns = ['VIX'] '''cut indicators into proper size. i.e. betyween start_date and end_date''' prices = prices.loc[first_trading_day:] sma = sma.loc[first_trading_day:] p_to_sma = p_to_sma.loc[first_trading_day:] rsi = rsi.loc[first_trading_day:] mfi = mfi.loc[first_trading_day:] vix = vix.loc[first_trading_day:] '''assemble Xtrain''' Xtrain = pd.concat([p_to_sma, rsi, mfi, vix], axis=1) # Xtrain.fillna(value=0, inplace=True) # print '=========Xtrain=======\n' # print Xtrain Xtrain = Xtrain.values[:, 1:] # print '=========trainX=======\n' # print trainX '''assemble Ytrain''' Ytrain = (prices.shift(-self.lookback) / prices) - 1 # Ytrain is 14 day return # print '=========Ytrain=======\n', Ytrain Ytrain[Ytrain > 0] = prices.shift(-self.lookback) / ( prices * (1.0 + 2 * self.impact)) - 1.0 Ytrain[Ytrain < 0] = prices.shift(-self.lookback) / ( prices * (1.0 - 2 * self.impact)) - 1.0 Ytrain = Ytrain.values # Ytrain.nan_to_num(0, copy=True)shift # print '=========Ytrain=======\n', Ytrain YBUY = 0.08 YSELL = -0.08 for i in range(len(Ytrain)): if Ytrain[i] > YBUY: Ytrain[i] = 1 elif Ytrain[i] < YSELL: Ytrain[i] = -1 else: Ytrain[i] = 0 # print '=========Ytrain=======\n', Ytrain # print 'self.learner_1=======\n', self.learner_1 '''use Xtain and Ytrain to train the random table''' self.learner.addEvidence(Xtrain, Ytrain) self.Y_in = self.learner.query(Xtrain)
def testPolicy(self, symbol="IBM", \ sd=dt.datetime(2009, 1, 1), \ ed=dt.datetime(2010, 1, 1), \ sv=10000): '''Firstly assemble the indicators into the testing Dataframe (Xtest), then query the RTLearner for Ytrain''' '''calculate indicators''' stock_older_days = 45 symbols = [symbol] prices, unused_a, unused_b = indicators.price_sma( start_date=(sd - dt.timedelta(days=stock_older_days)), end_date=ed, symbols=symbols) first_trading_day = sd while first_trading_day not in prices.index: first_trading_day += dt.timedelta(days=1) prices = prices / prices.loc[first_trading_day] sma = prices.copy().rolling(14).mean() p_to_sma = prices / sma prices.columns = ['Price'] sma.columns = ['sma'] p_to_sma.columns = ['p/sma'] rsi = indicators.rsi(start_date=(sd - dt.timedelta(days=stock_older_days)), end_date=ed, symbols=symbols) mfi = indicators.mfi(start_date=(sd - dt.timedelta(days=stock_older_days)), end_date=ed, symbols=symbols) vix = indicators.vix(start_date=sd, end_date=ed, symbols=symbols) rsi.columns = ['RSI'] mfi.columns = ['MFI'] vix.columns = ['VIX'] '''cut indicators into proper size. i.e. betyween start_date and end_date''' prices = prices.loc[first_trading_day:] sma = sma.loc[first_trading_day:] p_to_sma = p_to_sma.loc[first_trading_day:] rsi = rsi.loc[first_trading_day:] mfi = mfi.loc[first_trading_day:] vix = vix.loc[first_trading_day:] '''' make empty portfolio for future use''' portfolio = prices.copy() portfolio.iloc[:, :] = np.nan '''assemble Xtest''' Xtest = pd.concat([p_to_sma, rsi, mfi, vix], axis=1, join_axes=[vix.index]) # Xtrain.fillna(value=0, inplace=True) # print '=========Xtrain=======\n', Xtrain date_index = Xtest.index Xtest = Xtest.values[:, 1:] # print '=========Xtest=======\n', Xtest '''query for Ytest, then assemble it back to a dataframe for the market simulator''' Ytest = self.learner.query(Xtest) # print list(self.y_nparray[0]) # print '=========Y_in=======\n', self.y_nparray y_df = pd.DataFrame(data=list(Ytest[0]), index=date_index, columns=['Ytest']) # note: use (data=list(self.y_nparray[0]) for bagged # print '====y_df====\n', y_df # print y_df '''simulating market, enter a position, then exit the position until lookback days passed ''' curr_state = 'neutral' long_entry = [] long_exit = [] short_entry = [] short_exit = [] entry_point = 0 for i in range(len(y_df)): if ((int(y_df.iloc[i])) == 1) & (curr_state == 'neutral'): # if (int(y_df.iloc[i])) == 1: curr_state = 'long' portfolio.iloc[i, 0] = 1000 entry_point = i long_entry.append(portfolio.iloc[i:].index[0]) elif ((int(y_df.iloc[i])) == -1) & (curr_state == 'neutral'): # elif (int(y_df.iloc[i])) == -1: curr_state = 'short' portfolio.iloc[i, 0] = -1000 entry_point = i short_entry.append(portfolio.iloc[i:].index[0]) if (i >= entry_point + self.lookback) & (curr_state == 'long'): portfolio.iloc[i, 0] = 0 curr_state = 'neutral' entry_point = 0 long_exit.append(portfolio.iloc[i:].index[0]) elif (i >= entry_point + self.lookback) & (curr_state == 'short'): portfolio.iloc[i, 0] = 0 curr_state = 'neutral' entry_point = 0 short_exit.append(portfolio.iloc[i:].index[0]) '''good old market simulator, generating the df_trade''' portfolio.fillna(method='ffill', inplace=True) portfolio.fillna(0, inplace=True) # print '======end portfolio====\n', portfolio df_trade = portfolio - portfolio.shift(1) df_trade.iloc[0] = portfolio.iloc[0] # print '=====df_ttrade=====\n', type(df_trade) return df_trade
import numpy as np import pandas as pd import indicators as ind df = pd.read_csv("AAPL.csv") adjClose = df['Adj Close'].tolist() rsi = ind.rsi(adjClose) df['rsi'] = rsi rsiCross30 = ind.list_cross_above_value(rsi, 30) df['crossAbove30'] = rsiCross30 lookback = ind.lookback(rsiCross30, 10) df['lookback10'] = lookback df.to_csv("value_check.csv")
def testPolicy(self, symbol="AAPL", sd=dt.datetime(2010, 1, 1), ed=dt.datetime(2011, 12, 31), sv=100000): syms = [symbol] dates = pd.date_range(sd - dt.timedelta(days=20), ed + dt.timedelta(days=1)) prices_all = get_data(syms, dates) # automatically adds SPY prices_SPY = prices_all['SPY'] prices_SPY = prices_SPY.fillna(method='ffill', inplace=False) prices_SPY = prices_SPY.fillna(method='bfill', inplace=False) prices = prices_all[syms] # only portfolio symbols prices = prices.fillna(method='ffill', inplace=False) prices = prices.fillna(method='bfill', inplace=False) cols = ['Date', 'Symbol', 'Order', 'Shares'] ms_df = pd.DataFrame(columns=cols) ms_df = ms_df.set_index('Date') priceOverSMAValues = priceOverSMA(prices) # priceOverEMAClubbedValues = priceOverEMAClubbed(prices) bband, bbp = bbands(prices) rsiJPM = rsi(prices) rsiSPY = rsi(prices_SPY) prices = prices[prices.index >= sd] priceOverSMAValues = priceOverSMAValues[priceOverSMAValues.index >= sd] bbp = bbp[bbp.index >= sd] rsiJPM = rsiJPM[rsiJPM.index >= sd] rsiSPY = rsiSPY[rsiSPY.index >= sd] net_position = 0 for i in range(prices.size - 1): # print prices.index[i] # print prices.ix[prices.index[i],symbol] # print prices.ix[prices.index[i+1],symbol] # print "------------" i += 1 priceOverSMAValue = priceOverSMAValues.ix[prices.index[i], 'Price/SMA'] priceOverSMAValuePrior = priceOverSMAValues.ix[prices.index[i - 1], 'Price/SMA'] bbpValue = bbp.ix[prices.index[i], 'BBP'] rsiJPMValue = rsiJPM.ix[prices.index[i], 'RSI'] rsiSPYValue = rsiSPY.ix[prices.index[i], 'RSI'] # print "index={},priceOverSMA={},bbp={},rsiJPM={},rsiSPY={}".format(prices.index[i],priceOverSMAValue,bbpValue,rsiJPMValue,rsiSPYValue) if priceOverSMAValue > 1.05 and bbpValue > 1 and rsiJPMValue > 60: self.short_entry_x.append(prices.index[i]) if net_position == 0: ms_df.ix[prices.index[i], 'Symbol'] = symbol ms_df.ix[prices.index[i], 'Order'] = 'SELL' ms_df.ix[prices.index[i], 'Shares'] = 1000 net_position -= 1000 if net_position == 1000: ms_df.ix[prices.index[i], 'Symbol'] = symbol ms_df.ix[prices.index[i], 'Order'] = 'SELL' ms_df.ix[prices.index[i], 'Shares'] = 2000 net_position -= 2000 elif priceOverSMAValue < 0.95 and bbpValue > 0 and rsiJPMValue < 25: self.long_entry_x.append(prices.index[i]) if net_position == 0: ms_df.ix[prices.index[i], 'Symbol'] = symbol ms_df.ix[prices.index[i], 'Order'] = 'BUY' ms_df.ix[prices.index[i], 'Shares'] = 1000 net_position += 1000 if net_position == -1000: ms_df.ix[prices.index[i], 'Symbol'] = symbol ms_df.ix[prices.index[i], 'Order'] = 'BUY' ms_df.ix[prices.index[i], 'Shares'] = 2000 net_position += 2000 # elif priceOverSMAValue >= 1 and priceOverSMAValuePrior < 1 and net_position>0: # ms_df.ix[prices.index[i], 'Symbol'] = symbol # ms_df.ix[prices.index[i], 'Order'] = 'SELL' # ms_df.ix[prices.index[i], 'Shares'] = 1000 # net_position = 0 # elif priceOverSMAValue <= 1 and priceOverSMAValuePrior > 1 and net_position<0: # ms_df.ix[prices.index[i], 'Symbol'] = symbol # ms_df.ix[prices.index[i], 'Order'] = 'BUY' # ms_df.ix[prices.index[i], 'Shares'] = 1000 # net_position = 0 else: pass prices.to_csv("prices.csv") ms_df.to_csv("ms.csv") # print bps_df return ms_df
ax2.set_ylabel('rsi', color=color) # we already handled the x-label with ax1 ax2.set_ylim(0, 400) ax2.plot(timestamps, rsi, color=color, linewidth=0.5) ax2.tick_params(axis='y', labelcolor=color) fig.tight_layout() # otherwise the right y-label is slightly clipped plt.show() # test market = 'BTCUSDT' interval = '1m' rsi_interval = 14 # get data from binance_requests.py candles = get_candles(market, interval, 1000) closes = get_closes(candles) timestamps = get_timestamp(candles) time = np.array(timestamps) # convert to numpy for rsi calculation prices = np.array(closes) rsi_result = rsi(prices, rsi_interval) y = rsi_result.tolist() # plot_rsi(timestamps, rsi_result) # plot_overlay(timestamps, closes, timestamps, y) plot_overlay(closes, rsi_result, time)
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 main(): global specific_insts debug = False if not debug: pd.set_option('display.max_columns', 50) pd.set_option('display.width', 1000) user_input = input("Do You Want Select Instrument Manually:y or n") man_inst_names = None if user_input == "y": man_inst_names = input("Enter Instrument names Separated by Space:") man_inst_names = man_inst_names.split() instruments = INSTRUMENTS # # instruments = ['AUD_CAD',] # # instruments = ['AUD_CHF',] # instruments = ['AUD_CHF', 'AUD_CAD'] # instruments = ['AUD_CAD',] #data = get_file_data() stock = get_oanda_api(instruments, granularity='D') # print (stock['AUD_CAD']) # stock = get_ig_api(instruments) # print (stock['AUD_CAD']) # instruments = data['Close'].columns.values # # Initialize all assign all instrument data to dataframes # stock = {} # for instrument in instruments: # values = {} # for key in COLUMNS: # values[key] = data.get(key, {}).get(instrument) # values['Date'] = data.get('Date').iloc[:len(values[key]), 0] # stock[instrument] = pd.DataFrame(values, columns=COLUMNS) # print(stock[SELECTED_INSTRUMENT]) # return # Calculate the MACD, RSI and Profit and Loss for all instrument paid # Also, Calculate the MACD, RSI and Profit and Loss percentile for all # instruments instruments_list = [] CCI_list = [] dic_for_all_cci = {} for instrument in instruments: nsize = len(stock[instrument]['Close']) # Calculate MACD stock[instrument] = stock[instrument].join( macd(stock[instrument]['Close'])) # Calculate RSI for n = 14 stock[instrument] = stock[instrument].join( rsi(stock[instrument]['Close'])) #changeInPrice stock[instrument] = stock[instrument].join( pd.Series(change_in_price(stock[instrument]['Close'].values), name="Change In Price")) # Calculate Profile and Loss stock[instrument] = stock[instrument].join( pnl(stock[instrument]['Close'])) # Calculate MACD Percentile stock[instrument] = stock[instrument].join( macd_percentile(stock[instrument]['MACD'])) # Calculate RSI Percentile stock[instrument] = stock[instrument].join( rsi_percentile(stock[instrument]['RSI'])) # Calculate Profile and Loss Percentile stock[instrument] = stock[instrument].join( pnl_percentile(stock[instrument]['Profit/Loss'])) #Calculate CCI high = stock[instrument]["High"].values close = stock[instrument]["Close"].values low = stock[instrument]["Low"].values #create instrument dataframe ccis = talib.CCI(high, low, close, timeperiod=14) #ccis=list(ccis) instruments_list.append(instrument) CCI_list.append(ccis[-1]) dic_for_all_cci[instrument] = ccis stock[instrument]["CCI"] = ccis # Calculate Divergence factor 1 and 2 stock[instrument] = stock[instrument].join( pd.Series((stock[instrument]['MACD Percentile'] + 0.1 - stock[instrument]['RSI Percentile']) / 2.0, name='Divergence Factor 1')) stock[instrument] = stock[instrument].join( pd.Series(stock[instrument]['Divergence Factor 1'] - stock[instrument]['PNL Percentile'], name='Divergence Factor 2')) # Calculate Divergence factor 3 n = 19 for i in range(nsize): stock[instrument].loc[i:nsize, 'Macd_20'] = ( stock[instrument]['MACD'].iloc[i] - stock[instrument]['MACD'].iloc[i - n]) stock[instrument].loc[i:nsize, 'Prc_20'] = ( (stock[instrument]['Close'].iloc[i] - stock[instrument]['Close'].iloc[i - n]) ) / stock[instrument]['Close'].iloc[i - n] stock[instrument].loc[i:nsize, 'Divergence Factor 3'] = ( stock[instrument]['Macd_20'].iloc[i] / stock[instrument]['Close'].iloc[i] ) - stock[instrument]['Prc_20'].iloc[i] stock[instrument] = stock[instrument].join( rsi(stock[instrument]['Close'], 20, name='RSI_20')) # Calculate the momentum factors stock[instrument] = stock[instrument].join( pnl_n(stock[instrument]['Close'], 10)) stock[instrument] = stock[instrument].join( pnl_n(stock[instrument]['Close'], 30)) stock[instrument]['Close_fwd'] = stock[instrument]['Close'].shift(-2) stock[instrument].loc[ -1:nsize, 'Close_fwd'] = stock[instrument]['Close'].iloc[-1] stock[instrument].loc[ -2:nsize, 'Close_fwd'] = stock[instrument]['Close'].iloc[-2] stock[instrument] = stock[instrument].join( macd(stock[instrument]['Close_fwd'], name='MACD_fwd')) n = 19 stock[instrument] = stock[instrument].join( pd.Series(stock[instrument]['MACD_fwd'].diff(n) - stock[instrument]['MACD'], name='M_MACD_CHANGE')) stock[instrument] = stock[instrument].join( rsi(stock[instrument]['Close_fwd'], n=20, name='RSI_20_fwd')) stock[instrument] = stock[instrument].join( pd.Series(stock[instrument]['RSI_20_fwd'] - stock[instrument]['RSI_20'], name='M_RSI_CHANGE')) # Calculate the ADX, PDI & MDI _adx, _pdi, _mdi = adx(stock[instrument]) stock[instrument] = stock[instrument].join(_adx) stock[instrument] = stock[instrument].join(_pdi) stock[instrument] = stock[instrument].join(_mdi) # Calculate the Moving Averages: 5, 10, 20, 50, 100 for period in [5, 10, 20, 50, 100]: stock[instrument] = stock[instrument].join( moving_average(stock[instrument]['Close'], period, name=f'{period}MA')) # Calculate the Williams PCTR stock[instrument] = stock[instrument].join(williams(stock[instrument])) # Calculate the Minmax Range n = 17 for i in range(nsize): maxval = stock[instrument]['High'].iloc[i - n:i].max() minval = stock[instrument]['Low'].iloc[i - n:i].min() rng = abs(maxval) - abs(minval) # where is the last price in the range of minumimn to maximum pnow = stock[instrument]['Close'].iloc[i - n:i] if len(pnow.iloc[-1:i].values) > 0: whereinrng = ( (pnow.iloc[-1:i].values[0] - abs(minval)) / rng) * 100.0 stock[instrument].loc[i:nsize, 'MinMaxPosition'] = whereinrng stock[instrument].loc[i:nsize, 'High_Price(14)'] = maxval stock[instrument].loc[i:nsize, 'Low_Price(14)'] = minval stock[instrument]['Divergence factor Avg'] = ( stock[instrument]['Divergence Factor 1'] + stock[instrument]['Divergence Factor 2'] + stock[instrument]['Divergence Factor 3']) / 3.0 stock[instrument]['Momentum Avg'] = ( stock[instrument]['M_MACD_CHANGE'] + stock[instrument]['M_RSI_CHANGE'] + stock[instrument]['Profit/Loss_10'] + stock[instrument]['Profit/Loss_30']) / 4.0 df_instrument = pd.DataFrame() df_instrument["Price"] = stock[instrument]['Close'] df_instrument["Change In Price"] = change_in_price( stock[instrument]['Close'].values) df_instrument["CCI"] = stock[instrument]['CCI'] df_instrument["PNL Percentile"] = stock[instrument]['PNL Percentile'] df_instrument["Divergence Factor 1"] = stock[instrument][ 'Divergence Factor 1'] df_instrument["Divergence Factor 2"] = stock[instrument][ 'Divergence Factor 2'] df_instrument["Divergence Factor 3"] = stock[instrument][ 'Divergence Factor 3'] df_instrument["RSI"] = stock[instrument]["RSI"] df_instrument["MACD"] = stock[instrument]["MACD"] df_instrument["WPCTR"] = stock[instrument]["Williams PCTR"] df_instrument["pdi"] = stock[instrument]["pdi"] df_instrument["mdi"] = stock[instrument]["mdi"] df_instrument["adx"] = stock[instrument]["adx"] #df_instrument= df_instrument[pd.notnull(df_instrument['CCI'])] df_instrument = df_instrument.dropna(how="any") df_instrument["CCI Percentile"] = cci_percentile(df_instrument["CCI"]) df_instrument["Divergence Factor 4"] = df_instrument[ "CCI Percentile"] - df_instrument["PNL Percentile"] df_instrument['Divergence Factor 1 Rank'] = rank_formulation( df_instrument['Divergence Factor 1'].values) df_instrument['Divergence Factor 2 Rank'] = rank_formulation( df_instrument['Divergence Factor 2'].values) df_instrument['Divergence Factor 3 Rank'] = rank_formulation( df_instrument['Divergence Factor 3'].values) df_instrument['Divergence Factor 4 Rank'] = rank_formulation( df_instrument['Divergence Factor 4'].values) df_instrument['DF Avg Rank'] = ( df_instrument['Divergence Factor 1 Rank'] + df_instrument['Divergence Factor 2 Rank'] + df_instrument['Divergence Factor 3 Rank'] + df_instrument['Divergence Factor 4 Rank']) / 4.0 df_instrument["% Rank of DF Avgs"] = rank_formulation( df_instrument['DF Avg Rank'].values) df_instrument = df_instrument[[ 'Price', 'Change In Price', 'Divergence Factor 1', 'Divergence Factor 2', 'Divergence Factor 3', 'Divergence Factor 4', 'Divergence Factor 1 Rank', 'Divergence Factor 2 Rank', 'Divergence Factor 3 Rank', 'Divergence Factor 4 Rank', 'DF Avg Rank', '% Rank of DF Avgs', 'RSI', 'MACD', 'WPCTR', 'CCI', 'CCI Percentile', 'PNL Percentile', 'pdi', 'mdi', 'adx', ]] df_instrument.to_csv("all_inst" + "\\" + instrument + ".csv") ccis_df = pd.DataFrame(dic_for_all_cci) cci_percentile_list = [] dic = {"Instrument": instruments_list, "CCI": CCI_list} new_df = pd.DataFrame(dic) cci_percentile_list = cci_percentile(new_df["CCI"]).to_list() #sys.exit() # calculate the aggregrate for each oeruod # calculate the Divergence_Macd_Prc_Rank for nrow in range(nsize): row = [ stock[instrument]['Divergence Factor 3'].iloc[nrow] for instrument in instruments ] series = pd.Series(row).rank() / len(row) for i, instrument in enumerate(instruments): stock[instrument].loc[nrow:nsize, 'Divergence_Macd_Prc_Rank'] = series.iloc[i] # calculate the Divergence and Momentum average rank indices = [instrument for instrument in instruments] columns = [ 'Price', "Change In Price", 'Divergence Factor 1', 'Divergence Factor 2', 'Divergence Factor 3', 'Divergence Factor 1 Rank', 'Divergence Factor 2 Rank', 'Divergence Factor 3 Rank', 'M_MACD_CHANGE', 'M_RSI_CHANGE', 'Profit/Loss_10', 'Profit/Loss_30', 'M_MACD_CHANGE Rank', 'M_RSI_CHANGE Rank', 'Profit/Loss_10 Rank', 'Profit/Loss_30 Rank', 'Momentum Average Rank', 'Momentum Averages Ranks', 'MinMaxPosition', 'RSI', 'WPCTR', 'pdi', 'mdi', 'adx', 'High_Price(14)', 'Low_Price(14)', '5MA', '10MA', '20MA', '50MA', '100MA', "MACD", 'PNL Percentile', "DF Avg Rank", "% Rank of DF Avgs", ] periods = [] for i in range(nsize): period = [] for instrument in instruments: period.append([ stock[instrument]['Close'].iloc[i], stock[instrument]["Change In Price"].iloc[i], stock[instrument]['Divergence Factor 1'].iloc[i], stock[instrument]['Divergence Factor 2'].iloc[i], stock[instrument]['Divergence Factor 3'].iloc[i], None, None, None, stock[instrument]['M_MACD_CHANGE'].iloc[i], stock[instrument]['M_RSI_CHANGE'].iloc[i], stock[instrument]['Profit/Loss_10'].iloc[i], stock[instrument]['Profit/Loss_30'].iloc[i], None, None, None, None, None, None, stock[instrument]['MinMaxPosition'].iloc[i], stock[instrument]['RSI'].iloc[i], stock[instrument]['Williams PCTR'].iloc[i], stock[instrument]['pdi'].iloc[i], stock[instrument]['mdi'].iloc[i], stock[instrument]['adx'].iloc[i], stock[instrument]['High_Price(14)'].iloc[i], stock[instrument]['Low_Price(14)'].iloc[i], stock[instrument]['5MA'].iloc[i], stock[instrument]['10MA'].iloc[i], stock[instrument]['20MA'].iloc[i], stock[instrument]['50MA'].iloc[i], stock[instrument]['100MA'].iloc[i], stock[instrument]["MACD"].iloc[i], stock[instrument]['PNL Percentile'].iloc[i], None, None, ]) df = pd.DataFrame(data=period, index=indices, columns=columns) df['Divergence Factor 1 Rank'] = rank_formulation( df["Divergence Factor 1"].values) df['Divergence Factor 2 Rank'] = rank_formulation( df["Divergence Factor 2"].values) df['Divergence Factor 3 Rank'] = rank_formulation( df["Divergence Factor 3"].values) df['M_MACD_CHANGE Rank'] = rank_formulation(df['M_MACD_CHANGE'].values) df['M_RSI_CHANGE Rank'] = rank_formulation(df['M_RSI_CHANGE'].values) df['Profit/Loss_10 Rank'] = rank_formulation( df['Profit/Loss_10'].values) df['Profit/Loss_30 Rank'] = rank_formulation( df['Profit/Loss_30'].values) df['Momentum Average Rank'] = ( df['M_MACD_CHANGE Rank'] + df['M_RSI_CHANGE Rank'] + df['Profit/Loss_10 Rank'] + df['Profit/Loss_30 Rank']) / 4.0 df['Momentum Averages Ranks'] = rank_formulation( df['Momentum Average Rank'].values) #df.to_excel("target_data.xlsx") periods.append(df) pnl_percentile_nparaay = np.array(df["PNL Percentile"].values) cci_percentile_nparray = cci_percentile_list divergent_factor_4 = cci_percentile_nparray - pnl_percentile_nparaay df["CCI"] = CCI_list df["CCI Percentile"] = cci_percentile_list df["Divergence Factor 4"] = divergent_factor_4 df['Divergence Factor 4 Rank'] = rank_formulation( df['Divergence Factor 1'].values) df['DF Avg Rank'] = ( df['Divergence Factor 1 Rank'] + df['Divergence Factor 2 Rank'] + df['Divergence Factor 3 Rank'] + df['Divergence Factor 4 Rank']) / 4.0 df["% Rank of DF Avgs"] = rank_formulation(df['DF Avg Rank'].values) df = df[[ 'Price', 'Change In Price', 'Divergence Factor 1', 'Divergence Factor 2', 'Divergence Factor 3', 'Divergence Factor 4', 'Divergence Factor 1 Rank', 'Divergence Factor 2 Rank', 'Divergence Factor 3 Rank', 'Divergence Factor 4 Rank', 'DF Avg Rank', '% Rank of DF Avgs', 'M_MACD_CHANGE', 'M_RSI_CHANGE', 'Profit/Loss_10', 'Profit/Loss_30', 'M_MACD_CHANGE Rank', 'M_RSI_CHANGE Rank', 'Profit/Loss_10 Rank', 'Profit/Loss_30 Rank', 'Momentum Average Rank', 'Momentum Averages Ranks', 'MinMaxPosition', 'RSI', 'MACD', 'WPCTR', 'CCI', 'CCI Percentile', 'PNL Percentile', 'pdi', 'mdi', 'adx', 'High_Price(14)', 'Low_Price(14)', '5MA', '10MA', '20MA', '50MA', '100MA' ]] df.to_excel("target_data.xlsx") df.sort_values(by="% Rank of DF Avgs", inplace=True) top5, last5 = instrument_selection_rules(df) specific_insts = top5 + last5 print(specific_insts) Graph_Plots_For_Individual_Instrument(specific_insts, False) if man_inst_names is not None: Graph_Plots_For_Individual_Instrument(man_inst_names, True) df.to_excel("ordered_target_data.xlsx") '''
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)