def obv(s_interval: str, df_stock: pd.DataFrame) -> pd.DataFrame: """On Balance Volume Parameters ---------- s_interval: str Stock data interval df_stock: pd.DataFrame Dataframe of stock prices Returns ------- pd.DataFrame Dataframe with technical indicator """ # Daily if s_interval == "1440min": df_ta = ta.obv(close=df_stock["Adj Close"], volume=df_stock["Volume"]).dropna() # Intraday else: df_ta = ta.obv(close=df_stock["Close"], volume=df_stock["Volume"]).dropna() return df_ta
def _compute_obs(self, index: int) -> list: sub_df = self._dataset.iloc[self._clock.current_index - self._clock.window_look_back:self._clock. current_index] # print('XX') # print(self._dataset) # print(sub_df) fwma = ta.fwma(sub_df['Close'], length=(self._clock.window_look_back - 1)).mean() obv = ta.obv(sub_df['Close'], sub_df['Close']).mean() ### obs = [fwma, obv] return obs
def obv(df_stock: pd.DataFrame) -> pd.DataFrame: """On Balance Volume Parameters ---------- df_stock: pd.DataFrame Dataframe of stock prices Returns ------- pd.DataFrame Dataframe with technical indicator """ return pd.DataFrame( ta.obv(close=df_stock["Adj Close"], volume=df_stock["Volume"]).dropna())
# Plot st.header(f"Moving Average Convergence Divergence\n {company_name}") st.line_chart(data[['macd', 'macdsignal']]) ## CCI (Commodity Channel Index) # CCI cci = ta.trend.cci(data['High'], data['Low'], data['Close'], window=31, constant=0.015) # Plot st.header(f"Commodity Channel Index\n {company_name}") st.line_chart(cci) # ## RSI (Relative Strength Index) # RSI data['RSI'] = ta1.rsi(data['Adj Close'], timeperiod=14) # Plot st.header(f"Relative Strength Index\n {company_name}") st.line_chart(data['RSI']) # ## OBV (On Balance Volume) # OBV data['OBV'] = ta1.obv(data['Adj Close'], data['Volume']) / 10**6 # Plot st.header(f"On Balance Volume\n {company_name}") st.line_chart(data['OBV'])
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 obv(l_args, s_ticker, s_interval, df_stock): parser = argparse.ArgumentParser( prog='obv', description= """ The On Balance Volume (OBV) is a cumulative total of the up and down volume. When the close is higher than the previous close, the volume is added to the running total, and when the close is lower than the previous close, the volume is subtracted from the running total. \n \n To interpret the OBV, look for the OBV to move with the price or precede price moves. If the price moves before the OBV, then it is a non-confirmed move. A series of rising peaks, or falling troughs, in the OBV indicates a strong trend. If the OBV is flat, then the market is not trending. """ ) 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.obv(close=df_stock['5. adjusted close'], volume=df_stock['6. volume'], offset=ns_parser.n_offset).dropna() axPrice = plt.subplot(211) plt.plot(df_stock.index, df_stock['5. adjusted close'].values, 'k', lw=2) plt.title(f"On-Balance Volume (OBV) on {s_ticker}") plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.ylabel(f'Share Price ($)') plt.grid(b=True, which='major', color='#666666', linestyle='-') plt.minorticks_on() plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2) axVolume = axPrice.twinx() plt.bar(df_stock.index, df_stock['6. volume'].values, color='k', alpha=0.8, width=.3) plt.subplot(212) plt.plot(df_ta.index, df_ta.values, 'b', lw=1) plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.legend([f'OBV']) plt.xlabel('Time') 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.obv(close=df_stock['4. close'], volume=df_stock['5. volume'], offset=ns_parser.n_offset).dropna() axPrice = plt.subplot(211) plt.plot(df_stock.index, df_stock['5. adjusted close'].values, 'k', lw=2) plt.title(f"On-Balance Volume (OBV) on {s_ticker}") plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.ylabel(f'Share Price ($)') plt.grid(b=True, which='major', color='#666666', linestyle='-') plt.minorticks_on() plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2) axVolume = axPrice.twinx() plt.bar(df_stock.index, df_stock['5. volume'].values, color='k', alpha=0.8, width=.3) plt.subplot(212) plt.plot(df_ta.index, df_ta.values, 'b', lw=1) plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.legend([f'OBV']) plt.xlabel('Time') 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 obv(l_args, s_ticker, s_interval, df_stock): parser = argparse.ArgumentParser( prog="obv", description=""" The On Balance Volume (OBV) is a cumulative total of the up and down volume. When the close is higher than the previous close, the volume is added to the running total, and when the close is lower than the previous close, the volume is subtracted from the running total. \n \n To interpret the OBV, look for the OBV to move with the price or precede price moves. If the price moves before the OBV, then it is a non-confirmed move. A series of rising peaks, or falling troughs, in the OBV indicates a strong trend. If the OBV is flat, then the market is not trending. """, ) 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.obv( close=df_stock["5. adjusted close"], volume=df_stock["6. volume"], offset=ns_parser.n_offset, ).dropna() # Intraday else: df_ta = ta.obv( close=df_stock["4. close"], volume=df_stock["5. volume"], offset=ns_parser.n_offset, ).dropna() plt.figure() axPrice = plt.subplot(211) if s_interval == "1440min": plt.plot(df_stock.index, df_stock["5. adjusted close"].values, "k", lw=2) else: plt.plot(df_stock.index, df_stock["4. close"].values, "k", lw=2) plt.title(f"On-Balance Volume (OBV) on {s_ticker}") plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.ylabel("Share Price ($)") plt.grid(b=True, which="major", color="#666666", linestyle="-") plt.minorticks_on() plt.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2) _ = axPrice.twinx() if s_interval == "1440min": plt.bar( df_stock.index, df_stock["6. volume"].values, color="k", alpha=0.8, width=0.3, ) else: plt.bar( df_stock.index, df_stock["5. volume"].values, color="k", alpha=0.8, width=0.3, ) plt.subplot(212) plt.plot(df_ta.index, df_ta.values, "b", lw=1) plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.legend(["OBV"]) plt.xlabel("Time") 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 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