def bb_strategy(data): bbBuy = [] bbSell = [] position = False bb = ta.bbands(data['Adj Close'], length=20, std=2) data = pd.concat([data, bb], axis=1).reindex(data.index) for i in range(len(data)): if data['Adj Close'][i] < data['BBL_20_2.0'][i]: if position == False: bbBuy.append(data['Adj Close'][i]) bbSell.append(np.nan) position = True else: bbBuy.append(np.nan) bbSell.append(np.nan) elif data['Adj Close'][i] > data['BBU_20_2.0'][i]: if position == True: bbBuy.append(np.nan) bbSell.append(data['Adj Close'][i]) position = False #To indicate that I actually went there else: bbBuy.append(np.nan) bbSell.append(np.nan) else: bbBuy.append(np.nan) bbSell.append(np.nan) data['bb_Buy_Signal_price'] = bbBuy data['bb_Sell_Signal_price'] = bbSell return data
def bbands(close_values: pd.Series, length: int = 15, n_std: float = 2, mamode: str = "ema") -> pd.DataFrame: """Calculate Bollinger Bands Parameters ---------- close_values : pd.DataFrame DataFrame of sclose prices length : int Length of window to calculate BB n_std : float Number of standard deviations to show mamode : str Method of calculating average Returns ------- df_ta: pd.DataFrame Dataframe of bollinger band data """ return pd.DataFrame( ta.bbands( close=close_values, length=length, std=n_std, mamode=mamode, )).dropna()
def bbands(s_interval: str, df_stock: pd.DataFrame, length: int, n_std: float, mamode: str) -> pd.DataFrame: """Calculate Bollinger Bands Parameters ---------- s_interval : str Interval of stock data df_stock : pd.DataFrame DataFrame of stock data length : int Length of window to calculate BB n_std : float Number of standard deviations to show mamode : str Method of calculating average Returns ------- df_ta: pd.DataFrame Dataframe of bollinger band data """ # Daily if s_interval == "1440min": df_ta = ta.bbands( close=df_stock["Adj Close"], length=length, std=n_std, mamode=mamode, ).dropna() # Intraday else: df_ta = ta.bbands( close=df_stock["Close"], length=length, std=n_std, mamode=mamode, ).dropna() return df_ta
def bol_band(bs): b = ta.bbands(bs['close'], length=None, std=None, mamode=None, offset=None) bs['close'].plot() b = pd.concat([bs['close'], b['BBL_20'], b['BBM_20'], b['BBU_20']], axis=1, sort=False) b.plot()
def get_bbands_values(inputs): bbands_values = ta.bbands(inputs['close']) #print(bbands_values) ret_dict = {} ret_dict['lower'] = bbands_values['BBL_5_2.0'].values.tolist()[-items_ret:] ret_dict['mid'] = bbands_values['BBM_5_2.0'].values.tolist()[-items_ret:] ret_dict['upper'] = bbands_values['BBU_5_2.0'].values.tolist()[-items_ret:] ret_dict['price'] = inputs['close'].values.tolist()[-items_ret:] #print(ret_dict) return ret_dict
def get_bbands_values(inputs): bbands_values = ta.bbands(inputs['close'], length=20, std=2, mamode='SMA', offset=0) ret_dict = {} ret_dict['lower'] = bbands_values['BBL_20_2.0'].dropna().round( 2).values.tolist() ret_dict['mid'] = bbands_values['BBM_20_2.0'].dropna().round( 2).values.tolist() ret_dict['upper'] = bbands_values['BBU_20_2.0'].dropna().round( 2).values.tolist() return ret_dict
def get_bbands_values(inputs): bbands_values = ta.bbands(inputs['close'], length=20, std=2, mamode='SMA', offset=0) """ array dict name name array values """ resp_array = [] upper_dict = {} upper_dict['name'] = "upper" upper_dict['data'] = bbands_values['BBU_20_2.0'].dropna().round(2).values.tolist() resp_array.append(upper_dict) mid_dict = {} mid_dict['name'] = "mid" mid_dict['data'] = bbands_values['BBM_20_2.0'].dropna().round(2).values.tolist() resp_array.append(mid_dict) lower_dict = {} lower_dict['name'] = "lower" lower_dict['data'] = bbands_values['BBL_20_2.0'].dropna().round(2).values.tolist() resp_array.append(lower_dict) ret_dict = {} ret_dict['name'] = "price" ret_dict['data'] = inputs['close'].values.tolist() resp_array.append(ret_dict) return resp_array
def preprocess( self ): print('\n PREPROCESSING \n') ticker_details = pd.read_excel('Ticker List.xlsx') ticker = ticker_details['Ticker'].to_list() names = ticker_details['Description'].to_list() #Extracting Data from Yahoo Finance and Adding them to Values table using date as key end_date= "2020-06-19" start_date = "2000-01-01" date_range = pd.bdate_range(start=start_date,end=end_date) values = pd.DataFrame({ 'Date': date_range}) values['Date']= pd.to_datetime(values['Date']) #Extracting Data from Yahoo Finance and Adding them to Values table using date as key for i in ticker: raw_data = YahooFinancials(i) raw_data = raw_data.get_historical_price_data(start_date, end_date, "daily") df = pd.DataFrame(raw_data[i]['prices'])[['formatted_date','adjclose']] df.columns = ['Date1',i] df['Date1']= pd.to_datetime(df['Date1']) values = values.merge(df,how='left',left_on='Date',right_on='Date1') values = values.drop(labels='Date1',axis=1) self.VV = values #Renaming columns to represent instrument names rather than their ticker codes for ease of readability names.insert(0,'Date') values.columns = names values.tail() #Front filling the NaN values in the data set values = values.fillna(method="ffill",axis=0) values = values.fillna(method="bfill",axis=0) values.isna().sum() #Return values['SPX-RSI'] = ta.rsi( values['SPX'] ) BBANDS = ta.bbands( values['SPX'] ) keys = BBANDS.keys().to_list() Upper = BBANDS[ 'BBU_5' ] Lower = BBANDS[ 'BBL_5' ] Upper_perc = Upper / values['SPX'] Lower_perc = Lower / values['SPX'] values[ 'BBU-Distance' ] = Upper_perc values[ 'BBL-Distance' ] = Lower_perc values['MACD-Histogram'] = ta.macd( values[ 'SPX' ] )[ 'MACDH_12_26_9' ] # Co-ercing numeric type to all columns except Date cols=values.columns.drop('Date') values[cols] = values[cols].apply(pd.to_numeric,errors='coerce').round(decimals=4) #print(values.tail()) imp = ['Gold','USD Index', 'Oil', 'SPX','VIX', 'High Yield Fund' , 'Nikkei', 'Dax', '10Yr', '2Yr' , 'EEM' ,'XLE', 'XLF', 'XLI', 'AUDJPY'] # Calculating Short term -Historical Returns change_days = [1,3,5,14,21] data = pd.DataFrame(data=values['Date']) for i in change_days: x= values[cols].pct_change(periods=i).add_suffix("-T-"+str(i)) data=pd.concat(objs=(data,x),axis=1) x=[] # Calculating Long term Historical Returns change_days = [60,90,180,250] for i in change_days: x= values[imp].pct_change(periods=i).add_suffix("-T-"+str(i)) data=pd.concat(objs=(data,x),axis=1) x=[] #Calculating Moving averages for SPX moving_avg = pd.DataFrame(values['Date'],columns=['Date']) moving_avg['Date']=pd.to_datetime(moving_avg['Date'],format='%Y-%b-%d') moving_avg['SPX/15SMA'] = (values['SPX']/(values['SPX'].rolling(window=15).mean()))-1 moving_avg['SPX/30SMA'] = (values['SPX']/(values['SPX'].rolling(window=30).mean()))-1 moving_avg['SPX/60SMA'] = (values['SPX']/(values['SPX'].rolling(window=60).mean()))-1 moving_avg['SPX/90SMA'] = (values['SPX']/(values['SPX'].rolling(window=90).mean()))-1 moving_avg['SPX/180SMA'] = (values['SPX']/(values['SPX'].rolling(window=180).mean()))-1 moving_avg['SPX/90EMA'] = (values['SPX']/(values['SPX'].ewm(span=90,adjust=True,ignore_na=True).mean()))-1 moving_avg['SPX/180EMA'] = (values['SPX']/(values['SPX'].ewm(span=180,adjust=True,ignore_na=True).mean()))-1 moving_avg = moving_avg.dropna(axis=0) #Merging Moving Average values to the feature space data['Date']=pd.to_datetime(data['Date'],format='%Y-%b-%d') self.RAW_data = pd.merge(left=data,right=moving_avg,how='left',on='Date') self.RAW_y = pd.DataFrame(data=values['Date']) self.RAW_values = values
def integrate_with_indicators_forecasting(input_path, output_path, start_date, test_set, end_date_for_clustering): folder_creator(PATH_INTEGRATED_FOLDER, 1) for crypto in os.listdir(input_path): for date_to_predict in test_set: #end_date=pd.to_datetime(date_to_predict) - timedelta(days=1) end_date = date_to_predict df = cut_dataset_by_range(input_path, crypto.replace(".csv", ""), start_date, end_date, features_to_use=None) df["Date"] = pd.to_datetime(df["Date"]) day_to_predict = df.loc[len(df.Date) - 1] df = df[:-1] #remove the day to predict #df = df.sort_values('Date', ascending=True) data_series_of_target_feature = df[TARGET_FEATURE] for lookback_value in LOOKBACK_TEST: df['VWAP'] = panda.vwap(df['High'], df['Low'], df['Close'], df['Volume'], lookback_value=lookback_value) for lookback_value in LOOKBACK_TEST: df[str('SMA_' + str(lookback_value))] = get_SMA( data_series_of_target_feature, lookback_value) for lookback_value in LOOKBACK_TEST: df[str('EMA_' + str(lookback_value))] = get_EMA( data_series_of_target_feature, lookback_value) for lookback_value in LOOKBACK_TEST: df[str('RSI_' + str(lookback_value))] = get_RSI( data_series_of_target_feature, lookback_value) df_macd = get_MACD(data_series_of_target_feature) df['MACD_12_26_9'] = df_macd['MACD_12_26_9'] df['MACDH_12_26_9'] = df_macd['MACDH_12_26_9'] df['MACDS_12_26_9'] = df_macd['MACDS_12_26_9'] df_bbs = panda.bbands(data_series_of_target_feature) df['BBL_20'] = df_bbs['BBL_20'] df['BBM_20'] = df_bbs['BBM_20'] df['BBU_20'] = df_bbs['BBU_20'] df['MOM'] = panda.mom(data_series_of_target_feature) df_stoch = panda.stoch(df['High'], df['Low'], df['Close']) df['STOCHF_14'] = df_stoch['STOCHF_14'] df['STOCHF_3'] = df_stoch['STOCHF_3'] df['STOCH_5'] = df_stoch['STOCH_5'] df['STOCH_3'] = df_stoch['STOCH_3'] df['CMO'] = panda.cmo(data_series_of_target_feature) df['DPO'] = panda.dpo(data_series_of_target_feature) df['UO'] = panda.uo(df['High'], df['Low'], df['Close']) df['lag_1'] = df['Close'].shift(1) """df['lag_7'] = df['Close'].shift(7) df = df.iloc[7:]""" df = df.append(day_to_predict, ignore_index=True) df.fillna(value=0, inplace=True) df.to_csv(os.path.join( output_path, crypto.replace(".csv", "") + str("_" + date_to_predict) + ".csv"), sep=",", index=False)
Gabriele """ import pandas as pd import pandas_ta as ta df = pd.read_csv( 'Downloads/bitcoin-historical-data/bitstampUSD_1-min_data_2012-01-01_to_2019-08-12.csv', sep=',', header=0) # Clean NaN values df = df.dropna(axis=0) # Initialize Bollinger Bands Indicator df2 = ta.bbands(close=df["Close"], lenght=20, std=2) # Add Bollinger Bands features df['bbL'] = df2.iloc[:, 0] df['bbM'] = df2.iloc[:, 1] df['bbU'] = df2.iloc[:, 2] # Add Awesome Oscillator df["ao"] = ta.ao(high=df["High"], low=df["Low"]) # Add more stuff df["apo"] = ta.apo(close=df["Close"]) df["bop"] = ta.bop(open_=df["Open"], high=df["High"], low=df["Low"], close=df["Close"])
def bbands(l_args, s_ticker, s_interval, df_stock): parser = argparse.ArgumentParser( prog='bbands', description= """ Bollinger Bands consist of three lines. The middle band is a simple moving average (generally 20 periods) of the typical price (TP). The upper and lower bands are F standard deviations (generally 2) above and below the middle band. The bands widen and narrow when the volatility of the price is higher or lower, respectively. \n \nBollinger Bands do not, in themselves, generate buy or sell signals; they are an indicator of overbought or oversold conditions. When the price is near the upper or lower band it indicates that a reversal may be imminent. The middle band becomes a support or resistance level. The upper and lower bands can also be interpreted as price targets. When the price bounces off of the lower band and crosses the middle band, then the upper band becomes the price target. """) parser.add_argument('-l', "--length", action="store", dest="n_length", type=check_positive, default=5, help='length') parser.add_argument('-s', "--std", action="store", dest="n_std", type=check_positive, default=2, help='std') parser.add_argument('-m', "--mamode", action="store", dest="s_mamode", default="sma", help='mamode') parser.add_argument('-o', "--offset", action="store", dest="n_offset", type=check_positive, default=0, help='offset') (ns_parser, l_unknown_args) = parser.parse_known_args(l_args) if l_unknown_args: print( f"The following args couldn't be interpreted: {l_unknown_args}\n") return # Daily if s_interval == "1440min": df_ta = ta.bbands(close=df_stock['5. adjusted close'], length=ns_parser.n_length, std=ns_parser.n_std, mamode=ns_parser.s_mamode, offset=ns_parser.n_offset).dropna() #plot_stock_ta(df_stock['5. adjusted close'], s_ticker, df_ta, "BBANDS") plt.plot(df_stock.index, df_stock['5. adjusted close'].values, color='k', lw=3) plt.plot(df_ta.index, df_ta.iloc[:, 0].values, 'r', lw=2) plt.plot(df_ta.index, df_ta.iloc[:, 1].values, 'b', lw=1.5, ls='--') plt.plot(df_ta.index, df_ta.iloc[:, 2].values, 'g', lw=2) plt.title(f"Bollinger Band (BBands) on {s_ticker}") plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.xlabel('Time') plt.ylabel('Share Price ($)') plt.legend( [s_ticker, df_ta.columns[0], df_ta.columns[1], df_ta.columns[2]]) plt.gca().fill_between(df_ta.index, df_ta.iloc[:, 0].values, df_ta.iloc[:, 2].values, alpha=.1, color='b') plt.grid(b=True, which='major', color='#666666', linestyle='-') plt.minorticks_on() plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2) plt.show() # Intraday else: df_ta = ta.bbands(close=df_stock['4. close'], length=ns_parser.n_length, std=ns_parser.n_std, mamode=ns_parser.s_mamode, offset=ns_parser.n_offset).dropna() #plot_stock_ta(df_stock['4. close'], s_ticker, df_ta, "BBANDS") plt.plot(df_stock.index, df_stock['4. close'].values, color='k', lw=3) plt.plot(df_ta.index, df_ta.iloc[:, 0].values, 'r', lw=2) plt.plot(df_ta.index, df_ta.iloc[:, 1].values, 'b', lw=1.5, ls='--') plt.plot(df_ta.index, df_ta.iloc[:, 2].values, 'g', lw=2) plt.title(f"Bollinger Band (BBands) on {s_ticker}") plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.xlabel('Time') plt.ylabel('Share Price ($)') plt.legend( [s_ticker, df_ta.columns[0], df_ta.columns[1], df_ta.columns[2]]) plt.gca().fill_between(df_ta.index, df_ta.iloc[:, 0].values, df_ta.iloc[:, 2].values, alpha=.1, color='b') plt.grid(b=True, which='major', color='#666666', linestyle='-') plt.minorticks_on() plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2) plt.show() print("")
def bbands(l_args, s_ticker, s_interval, df_stock): parser = argparse.ArgumentParser( prog="bbands", description=""" Bollinger Bands consist of three lines. The middle band is a simple moving average (generally 20 periods) of the typical price (TP). The upper and lower bands are F standard deviations (generally 2) above and below the middle band. The bands widen and narrow when the volatility of the price is higher or lower, respectively. \n \nBollinger Bands do not, in themselves, generate buy or sell signals; they are an indicator of overbought or oversold conditions. When the price is near the upper or lower band it indicates that a reversal may be imminent. The middle band becomes a support or resistance level. The upper and lower bands can also be interpreted as price targets. When the price bounces off of the lower band and crosses the middle band, then the upper band becomes the price target. """, ) parser.add_argument( "-l", "--length", action="store", dest="n_length", type=check_positive, default=5, help="length", ) parser.add_argument( "-s", "--std", action="store", dest="n_std", type=check_positive, default=2, help="std", ) parser.add_argument("-m", "--mamode", action="store", dest="s_mamode", default="sma", help="mamode") parser.add_argument( "-o", "--offset", action="store", dest="n_offset", type=check_positive, default=0, help="offset", ) try: ns_parser = parse_known_args_and_warn(parser, l_args) # Daily if s_interval == "1440min": df_ta = ta.bbands( close=df_stock["5. adjusted close"], length=ns_parser.n_length, std=ns_parser.n_std, mamode=ns_parser.s_mamode, offset=ns_parser.n_offset, ).dropna() # Intraday else: df_ta = ta.bbands( close=df_stock["4. close"], length=ns_parser.n_length, std=ns_parser.n_std, mamode=ns_parser.s_mamode, offset=ns_parser.n_offset, ).dropna() plt.figure() if s_ticker == "1440min": plt.plot(df_stock.index, df_stock["5. adjusted close"].values, color="k", lw=3) else: plt.plot(df_stock.index, df_stock["4. close"].values, color="k", lw=3) plt.plot(df_ta.index, df_ta.iloc[:, 0].values, "r", lw=2) plt.plot(df_ta.index, df_ta.iloc[:, 1].values, "b", lw=1.5, ls="--") plt.plot(df_ta.index, df_ta.iloc[:, 2].values, "g", lw=2) plt.title(f"Bollinger Band (BBands) on {s_ticker}") plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.xlabel("Time") plt.ylabel("Share Price ($)") plt.legend( [s_ticker, df_ta.columns[0], df_ta.columns[1], df_ta.columns[2]]) plt.gca().fill_between( df_ta.index, df_ta.iloc[:, 0].values, df_ta.iloc[:, 2].values, alpha=0.1, color="b", ) plt.grid(b=True, which="major", color="#666666", linestyle="-") plt.minorticks_on() plt.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2) plt.ion() plt.show() print("") except Exception as e: print(e) print("")
def on_message(ws, message): global initial global i global indicators global buy_price try: i += 1 checked = False new_dict = {} indic_dict = {} info_dict = json.loads(message) info_dict = info_dict['data'] close_price = 0.0 for key, value in info_dict.items(): if key == 'o': new_dict['open'] = float(value) indic_dict['open'] = float(value) elif key == 'h': new_dict['high'] = float(value) indic_dict['high'] = float(value) elif key == 'l': new_dict['low'] = float(value) indic_dict['low'] = float(value) elif key == 'c': new_dict['close'] = float(value) indic_dict['close'] = float(value) checked = True close_price = float(value) elif key == 'vw': new_dict['vwap'] = float(value) indic_dict['vwap'] = float(value) if checked: initial = initial.append(new_dict, ignore_index=True) print(initial.tail()) if i > 55: bbands = ta.bbands(initial['close'], length=50, std=2) #calculating indicators ema_50 = np.array(ta.ema(initial['close'], length=5))[-1] ema_200 = np.array(ta.ema(initial['close'], length=20))[-1] ema_500 = np.array(ta.ema(initial['close'], length=50))[-1] #macd = ta.macd(initial['close'], 5, 35, 5) indic_dict['bband1'] = bbands['BBL_50'].iloc[-1] indic_dict['useless'] = bbands['BBM_50'].iloc[-1] indic_dict['bband2'] = bbands['BBU_50'].iloc[-1] indic_dict['ema1'] = ema_50 indic_dict['ema2'] = ema_200 indic_dict['ema3'] = ema_500 # indic_dict['macd'] = macd['MACD_5_35_5'].iloc[-1] # indic_dict['macdh'] = macd['MACDH_5_35_5'].iloc[-1] # indic_dict['macds'] = macd['MACDS_5_35_5'].iloc[-1] if checked: indicators = indicators.append(indic_dict, ignore_index=True) pred = rfc.predict([indicators.iloc[-1]]) #PREDICT print(indicators.tail()) if (pred[0] > indicators['close'].iloc[-1] and i > 5): #buy if b.buy(5, close_price, 5): create_order('MSFT', 5, 'buy', 'market', 'gtc') buy_price = close_price elif (pred[0] < indicators['close'].iloc[-1] and i > 5): #sell if b.sell(5, close_price, 5): create_order('MSFT', 5, 'sell', 'market', 'day') elif (buy_price - close_price >= 0.5 and i > 5): #sell if b.sell(5, close_price, 5): create_order('MSFT', 5, 'sell', 'market', 'day') predictions.append(pred) except Exception as e: print(e)
'AverageScore', 'Signal' ]) # loop through tickers to compute and store ta indicators values/scores for ticker in tickers: # retrieve security data df = pdr.DataReader(ticker, data_source='yahoo', start=start_date, end=end_date) # create ta indicators df[rsi] = ta.rsi(df['Adj Close'], length=rsi_length) # rsi df[[lower_bband, mean, upper_bband]] = ta.bbands(df['Adj Close'], length=bband_length, std=bband_std) # bollinger bands df[[stochk, stochd]] = ta.stoch(df.High, df.Low, df['Adj Close'], k=stoch_k, d=stoch_d, smooth_k=stoch_smoothk) df[[macd, macdh, macds]] = ta.macd(df['Adj Close'], fast=macd_fast, slow=macd_slow, signal=macd_signal) # push data to screener screener.loc[ticker] = df.drop( ['High', 'Low', 'Open', 'Close', 'Volume'],
def add_plots(df: pd.DataFrame, additional_charts: Dict[str, bool]): """Add additional plots to the candle chart. Parameters ---------- df : pd.DataFrame The source data additional_charts : Dict[str, bool] A dictionary of flags to include additional charts Returns ------- Tuple Tuple of lists containing the plots, legends and subplot legends """ panel_number = 2 plots_to_add = [] legends = [] subplot_legends = [] if additional_charts["ad"]: ad = ta.ad(df["High"], df["Low"], df["Close"], df["Volume"]) ad_plot = mpf.make_addplot(ad, panel=panel_number) plots_to_add.append(ad_plot) subplot_legends.extend([panel_number * 2, ["AD"]]) panel_number += 1 if additional_charts["bbands"]: bbands = ta.bbands(df["Close"]) bbands = bbands.drop("BBB_5_2.0", axis=1) bbands_plot = mpf.make_addplot(bbands, panel=0) plots_to_add.append(bbands_plot) legends.extend(["Lower BBand", "Middle BBand", "Upper BBand"]) if additional_charts["cci"]: cci = ta.cci(df["High"], df["Low"], df["Close"]) cci_plot = mpf.make_addplot(cci, panel=panel_number) plots_to_add.append(cci_plot) subplot_legends.extend([panel_number * 2, ["CCI"]]) panel_number += 1 if additional_charts["ema"]: ema = ta.ema(df["Close"]) ema_plot = mpf.make_addplot(ema, panel=0) plots_to_add.append(ema_plot) legends.append("10 EMA") if additional_charts["rsi"]: rsi = ta.rsi(df["Close"]) rsi_plot = mpf.make_addplot(rsi, panel=panel_number) plots_to_add.append(rsi_plot) subplot_legends.extend([panel_number * 2, ["RSI"]]) panel_number += 1 if additional_charts["obv"]: obv = ta.obv(df["Close"], df["Volume"]) obv_plot = mpf.make_addplot(obv, panel=panel_number) plots_to_add.append(obv_plot) subplot_legends.extend([panel_number * 2, ["OBV"]]) panel_number += 1 if additional_charts["sma"]: sma_length = [20, 50] for length in sma_length: sma = ta.sma(df["Close"], length=length) sma_plot = mpf.make_addplot(sma, panel=0) plots_to_add.append(sma_plot) legends.append(f"{length} SMA") if additional_charts["vwap"]: vwap = ta.vwap(df["High"], df["Low"], df["Close"], df["Volume"]) vwap_plot = mpf.make_addplot(vwap, panel=0) plots_to_add.append(vwap_plot) legends.append("vwap") return plots_to_add, legends, subplot_legends
def getBollingerBands(data): bband = ta.bbands(data["close"]) return bband
def setUp(self, df): df['rsi'] = ta.rsi(df['close'], self.rsi_len) df['lbb'], df['mbb'], df['ubb'], df['bb_width'] = ta.bbands( df['close'], self.bb_len) self.dataframe = df
for i in range(10000): now = datetime.now() # dd/mm/YY H:M:S new_dict = {} indic_dict = {} open1, high, low, close = get_close() new_dict['open'] = float(open1) new_dict['high'] = float(high) new_dict['low'] = float(low) new_dict['close'] = float(close) X_test = X_test.append(new_dict, ignore_index=True) if i < 51: print(X_test.tail()) if i >= 51: bbands_close = ta.bbands(X_test['close'], length=50, std=2) #calculating indicators macd_close = ta.macd(X_test['close'], 5, 35, 5) rsi_close = np.array(ta.rsi(X_test['close'], 14))[-1] ema_5_close = np.array(ta.ema(X_test['close'], 5))[-1] ema_20_close = np.array(ta.ema(X_test['close'], 20))[-1] ema_50_close = np.array(ta.ema(X_test['close'], 50))[-1] indic_dict['open'] = float(open1) indic_dict['high'] = float(high) indic_dict['low'] = float(low) indic_dict['close'] = float(close) indic_dict['useless'] = bbands_close['BBM_50'].iloc[-1] indic_dict['bband1'] = bbands_close['BBL_50'].iloc[-1] indic_dict['bband2'] = bbands_close['BBU_50'].iloc[-1] #BUYS BUYS BUYS indic_dict['macd'] = macd_close['MACD_5_35_5'].iloc[-1] indic_dict['macdh'] = macd_close['MACDH_5_35_5'].iloc[-1] indic_dict['macds'] = macd_close['MACDS_5_35_5'].iloc[-1]
import pandas_ta as ta import backtester, math import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix import pickle sns.set() initial = pd.read_csv( 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&interval=1min&symbol=msft&apikey=OUMVBY0VK0HS8I9E&datatype=csv&outputsize=full' ) initial = initial[::-1].reset_index(drop=True) volume = initial['volume'] initial.drop(['volume', 'timestamp'], axis=1, inplace=True) bbands = ta.bbands(initial['close'], length=50, std=2) #calculating indicators rsi = ta.rsi(initial['close'], length=20) ema_50 = ta.ema(initial['close'], length=5) ema_200 = ta.ema(initial['close'], length=20) ema_500 = ta.ema(initial['close'], length=50) #macd = ta.macd(initial['close'], 5, 35, 5) vwap = ta.vwap(initial['high'], initial['low'], initial['close'], volume) initial = pd.concat([initial, bbands, ema_50, ema_200, ema_500, vwap], axis=1) initial.columns = [ 'open', 'high', 'low', 'close', 'bband1', 'useless', 'bband2', 'ema1', 'ema2', 'ema3', 'vwap' ] initialInvestment = 1000 b = backtester.Backtester(initialInvestment) initial = initial.dropna()
import torch from torch import nn from sklearn.preprocessing import MinMaxScaler # importing training data sets from torch.autograd import Variable data_cleaned = pd.read_csv('data_cleaned.csv') data_cleaned = data_cleaned.assign(slow_vwma_value=(vwma(data_cleaned.close, data_cleaned.volume, length=2, offset=0)), fast_vwma_value=(vwma(data_cleaned.close, data_cleaned.volume, length=5, offset=0)), slow_sma_value=(sma(data_cleaned.close, 15)), fast_sma_value=(sma(data_cleaned.close, 5)), rsi_data_value=(rsi(data_cleaned.close, 10)), ) bbands_train = pd.DataFrame(bbands(data_cleaned.close, length=30, std=1.7)) data_cleaned = pd.concat([data_cleaned, bbands_train], axis=1) # data_cleaned['timestamp'] = pd.to_datetime(data_cleaned['timestamp'], format='%Y-%m-%d %H') data_cleaned = data_cleaned.set_index('timestamp') data_cleaned = data_cleaned.dropna() # print(data_cleaned) # print(len(data_cleaned)) # importing test data sets data_cleaned_test = pd.read_csv("data_cleaned_test.csv") data_cleaned_test = data_cleaned_test.assign( slow_vwma_value=(vwma(data_cleaned_test.close, data_cleaned_test.volume, length=15, offset=0)), fast_vwma_value=(vwma(data_cleaned_test.close, data_cleaned_test.volume, length=5, offset=0)), slow_sma_value=(sma(data_cleaned_test.close, 15)), fast_sma_value=(sma(data_cleaned_test.close, 5)), rsi_data_value=(rsi(data_cleaned_test.close, 10)),
def add_plots(df, ns_parser): panel_number = 2 plots_to_add = [] legends = [] subplot_legends = [] if ns_parser.ad: ad = ta.ad(df["High"], df["Low"], df["Close"], df["Volume"]) ad_plot = mpf.make_addplot(ad, panel=panel_number) plots_to_add.append(ad_plot) subplot_legends.extend([panel_number * 2, ["AD"]]) panel_number += 1 if ns_parser.bbands: bbands = ta.bbands(df["Close"]) bbands = bbands.drop("BBB_5_2.0", axis=1) bbands_plot = mpf.make_addplot(bbands, panel=0) plots_to_add.append(bbands_plot) legends.extend(["Lower BBand", "Middle BBand", "Upper BBand"]) if ns_parser.cci: cci = ta.cci(df["High"], df["Low"], df["Close"]) cci_plot = mpf.make_addplot(cci, panel=panel_number) plots_to_add.append(cci_plot) subplot_legends.extend([panel_number * 2, ["CCI"]]) panel_number += 1 if ns_parser.ema: ema = ta.ema(df["Close"]) ema_plot = mpf.make_addplot(ema, panel=0) plots_to_add.append(ema_plot) legends.append("10 EMA") if ns_parser.rsi: rsi = ta.rsi(df["Close"]) rsi_plot = mpf.make_addplot(rsi, panel=panel_number) plots_to_add.append(rsi_plot) subplot_legends.extend([panel_number * 2, ["RSI"]]) panel_number += 1 if ns_parser.obv: obv = ta.obv(df["Close"], df["Volume"]) obv_plot = mpf.make_addplot(obv, panel=panel_number) plots_to_add.append(obv_plot) subplot_legends.extend([panel_number * 2, ["OBV"]]) panel_number += 1 if ns_parser.sma: sma_length = [20, 50] for length in sma_length: sma = ta.sma(df["Close"], length=length) sma_plot = mpf.make_addplot(sma, panel=0) plots_to_add.append(sma_plot) legends.append(f"{length} SMA") if ns_parser.vwap: vwap = ta.vwap(df["High"], df["Low"], df["Close"], df["Volume"]) vwap_plot = mpf.make_addplot(vwap, panel=0) plots_to_add.append(vwap_plot) legends.append("vwap") return plots_to_add, legends, subplot_legends
# ## SMA and EMA #Simple Moving Average data['SMA'] = ta1.sma(data['Adj Close'], timeperiod=20) # Exponential Moving Average data['EMA'] = ta1.ema(data['Adj Close'], timeperiod=20) # Plot st.header( f"Simple Moving Average vs. Exponential Moving Average\n {company_name}") st.line_chart(data[['Adj Close', 'SMA', 'EMA']]) # Bollinger Bands data[['lower_band', 'middle_band', 'upper_band']] = ta1.bbands(data['Adj Close'], timeperiod=20).iloc[:, 0:3] # Plot st.header(f"Bollinger Bands\n {company_name}") st.line_chart(data[['Adj Close', 'upper_band', 'middle_band', 'lower_band']]) # ## MACD (Moving Average Convergence Divergence) # MACD data[['macd', 'macdhist', 'macdsignal']] = ta1.macd(data['Adj Close'], fastperiod=12, slowperiod=26, signalperiod=9).iloc[:, 0:3] # Plot st.header(f"Moving Average Convergence Divergence\n {company_name}")
#print(values.isna().sum()) values.tail() #Front filling the NaN values in the data set values = values.fillna(method="ffill",axis=0) values = values.fillna(method="bfill",axis=0) values.isna().sum() # Co-ercing numeric type to all columns except Date cols=values.columns.drop('Date') values[cols] = values[cols].apply(pd.to_numeric,errors='coerce').round(decimals=4) #print(values.tail()) values['SPX-RSI'] = ta.rsi( values['SPX'] ) BBANDS = ta.bbands( values['SPX'] ) keys = BBANDS.keys().to_list() Upper = BBANDS[ 'BBU_5' ] Lower = BBANDS[ 'BBL_5' ] Upper_perc = Upper / values['SPX'] Lower_perc = Lower / values['SPX'] values[ 'BBU-Distance' ] = Upper_perc values[ 'BBL-Distance' ] = Lower_perc values['MACD-Histogram'] = ta.macd( values[ 'SPX' ] )[ 'MACDH_12_26_9' ] imp = ['Gold','USD Index', 'Oil', 'SPX','VIX', 'High Yield Fund' , 'Nikkei', 'Dax', '10Yr', '2Yr' , 'EEM' ,'XLE', 'XLF', 'XLI', 'AUDJPY'] # Calculating Short term -Historical Returns change_days = [1,3,5,14,21]