def add_volume_indicators(data: pd.DataFrame) -> pd.DataFrame: """Adds the volume indicators. Parameters ---------- data : pd.DataFrame A dataframe with daily stock values. Must include: open, high, low, close and volume. It should also be sorted in a descending manner. Returns ------- pd.DataFrame The input dataframe with the indicators added. """ chaikin = ChaikinMoneyFlowIndicator(data['high'], data['low'], data['close'], data['volume']) mfi = MFIIndicator(data['high'], data['low'], data['close'], data['volume']) obv = OnBalanceVolumeIndicator(data['close'], data['volume']) data.loc[:, 'chaikin'] = chaikin.chaikin_money_flow() data.loc[:, 'mfi'] = mfi.money_flow_index() data.loc[:, 'obv'] = obv.on_balance_volume() return data
def OBV(self, df): ''' data range(0,inf) ''' df_OBV = df.copy() obv = OnBalanceVolumeIndicator(df['Close'], df['Volume']) df['OBV'] = obv.on_balance_volume() return df
def test_obv2(self): target = 'OBV' result = OnBalanceVolumeIndicator(close=self._df['Close'], volume=self._df['Volume'], fillna=False).on_balance_volume() pd.testing.assert_series_equal(self._df[target].tail(), result.tail(), check_names=False)
def get_indicators(df): """ Add set of technical indicators to the dataframe, return original data frame with new features """ feature_df = df.copy() feature_df['RSI'] = RSIIndicator(close=df[CLOSE]).rsi() feature_df['Stochastic'] = StochasticOscillator(high=df[HIGH], low=df[LOW], close=df[CLOSE]).stoch() feature_df['Stochastic_signal'] = StochasticOscillator( high=df[HIGH], low=df[LOW], close=df[CLOSE]).stoch_signal() feature_df['ADI'] = AccDistIndexIndicator( high=df[HIGH], low=df[LOW], close=df[CLOSE], volume=df[VOLUME]).acc_dist_index() feature_df['OBV'] = OnBalanceVolumeIndicator( close=df[CLOSE], volume=df[VOLUME]).on_balance_volume() feature_df['ATR'] = AverageTrueRange(high=df[HIGH], low=df[LOW], close=df[CLOSE]).average_true_range() feature_df['ADX'] = ADXIndicator(high=df[HIGH], low=df[LOW], close=df[CLOSE]).adx() feature_df['ADX_pos'] = ADXIndicator(high=df[HIGH], low=df[LOW], close=df[CLOSE]).adx_pos() feature_df['ADX_neg'] = ADXIndicator(high=df[HIGH], low=df[LOW], close=df[CLOSE]).adx_neg() feature_df['MACD'] = MACD(close=df[CLOSE]).macd() feature_df['MACD_diff'] = MACD(close=df[CLOSE]).macd_diff() feature_df['MACD_signal'] = MACD(close=df[CLOSE]).macd_signal() return feature_df
def add_volume_ta(df: pd.DataFrame, high: str, low: str, close: str, volume: str, fillna: bool = False, colprefix: str = "") -> pd.DataFrame: """Add volume technical analysis features to dataframe. Args: df (pandas.core.frame.DataFrame): Dataframe base. high (str): Name of 'high' column. low (str): Name of 'low' column. close (str): Name of 'close' column. volume (str): Name of 'volume' column. fillna(bool): if True, fill nan values. colprefix(str): Prefix column names inserted Returns: pandas.core.frame.DataFrame: Dataframe with new features. """ # Accumulation Distribution Index df[f'{colprefix}volume_adi'] = AccDistIndexIndicator( high=df[high], low=df[low], close=df[close], volume=df[volume], fillna=fillna).acc_dist_index() # On Balance Volume df[f'{colprefix}volume_obv'] = OnBalanceVolumeIndicator( close=df[close], volume=df[volume], fillna=fillna).on_balance_volume() # Chaikin Money Flow df[f'{colprefix}volume_cmf'] = ChaikinMoneyFlowIndicator( high=df[high], low=df[low], close=df[close], volume=df[volume], fillna=fillna).chaikin_money_flow() # Force Index df[f'{colprefix}volume_fi'] = ForceIndexIndicator( close=df[close], volume=df[volume], n=13, fillna=fillna).force_index() # Money Flow Indicator df[f'{colprefix}volume_mfi'] = MFIIndicator( high=df[high], low=df[low], close=df[close], volume=df[volume], n=14, fillna=fillna).money_flow_index() # Ease of Movement indicator = EaseOfMovementIndicator(high=df[high], low=df[low], volume=df[volume], n=14, fillna=fillna) df[f'{colprefix}volume_em'] = indicator.ease_of_movement() df[f'{colprefix}volume_sma_em'] = indicator.sma_ease_of_movement() # Volume Price Trend df[f'{colprefix}volume_vpt'] = VolumePriceTrendIndicator( close=df[close], volume=df[volume], fillna=fillna).volume_price_trend() # Negative Volume Index df[f'{colprefix}volume_nvi'] = NegativeVolumeIndexIndicator( close=df[close], volume=df[volume], fillna=fillna).negative_volume_index() # Volume Weighted Average Price df[f'{colprefix}volume_vwap'] = VolumeWeightedAveragePrice( high=df[high], low=df[low], close=df[close], volume=df[volume], n=14, fillna=fillna ).volume_weighted_average_price() return df
def __init__(self, symbols): # data = json.loads(symbols) # df_stock = pd.json_normalize(symbols) # df_stock = pd.read_csv(fn,names = ['sym']).drop_duplicates() df_stock = pd.DataFrame(symbols) ls_stock = df_stock['sym'].to_list() df_stock = df_stock.reset_index() df_stock.columns = ['sort', 'sym'] df_stock.head() # In[3]: start = dt.date.today() + relativedelta(days=-150) end = dt.date.today() + relativedelta(days=-0) ls_tickers = ls_stock ls_df = [] for ticker in ls_tickers: try: df = web.DataReader(ticker, 'yahoo', start, end) except Exception as e: print(str(e)) continue df['sym'] = ticker ls_df.append(df.copy()) df_price = pd.concat(ls_df).reset_index() df_price.columns = [ 'dte', 'hgh', 'low', 'opn', 'cls', 'vol', 'cls_adj', 'sym' ] df_price.sort_values(['sym', 'dte'], inplace=True) df_price = df_price[['dte', 'sym', 'hgh', 'low', 'cls', 'vol']].copy() df_price['curr'] = end df_price['curr'] = pd.to_datetime(df_price['curr']) df_price['dte'] = pd.to_datetime(df_price['dte']) df_price['ndays'] = (df_price['curr'] - df_price['dte']).dt.days df_price['ndays'] = df_price.groupby(['sym'])['ndays'].rank() df_price[df_price['sym'] == 'SPY'].head() # In[4]: ls_df = [] ls_tickers = ls_stock for ticker in ls_tickers: #df = dropna(df_price[df_price['sym']==ticker]) df = df_price[df_price['sym'] == ticker].copy() indicator_bb = BollingerBands(close=df['cls'], window=20, window_dev=2) indicator_macd = MACD(close=df['cls'], window_fast=12, window_slow=26, window_sign=9) indicator_rsi14 = RSIIndicator(close=df['cls'], window=14) indicator_cci20 = cci(high=df['hgh'], low=df['low'], close=df['cls'], window=20, constant=0.015) indicator_obv = OnBalanceVolumeIndicator(close=df['cls'], volume=df['vol'], fillna=True) indicator_vol_sma20 = SMAIndicator(close=df['vol'], window=20) indicator_ema03 = EMAIndicator(close=df['cls'], window=3) indicator_ema05 = EMAIndicator(close=df['cls'], window=5) indicator_ema08 = EMAIndicator(close=df['cls'], window=8) indicator_ema10 = EMAIndicator(close=df['cls'], window=10) indicator_ema12 = EMAIndicator(close=df['cls'], window=12) indicator_ema15 = EMAIndicator(close=df['cls'], window=15) indicator_ema30 = EMAIndicator(close=df['cls'], window=30) indicator_ema35 = EMAIndicator(close=df['cls'], window=35) indicator_ema40 = EMAIndicator(close=df['cls'], window=40) indicator_ema45 = EMAIndicator(close=df['cls'], window=45) indicator_ema50 = EMAIndicator(close=df['cls'], window=50) indicator_ema60 = EMAIndicator(close=df['cls'], window=60) # Add Bollinger Band high indicator df['bb_bbhi'] = indicator_bb.bollinger_hband_indicator() # Add Bollinger Band low indicator df['bb_bbli'] = indicator_bb.bollinger_lband_indicator() #df['macd'] = indicator_macd.macd() df['macd'] = indicator_macd.macd_diff() #df['macd_signal'] = indicator_macd.macd_signal() df['obv'] = indicator_obv.on_balance_volume() df['vol_sma20'] = indicator_vol_sma20.sma_indicator() df['ema03'] = indicator_ema03.ema_indicator() df['ema05'] = indicator_ema05.ema_indicator() df['ema08'] = indicator_ema08.ema_indicator() df['ema10'] = indicator_ema10.ema_indicator() df['ema12'] = indicator_ema12.ema_indicator() df['ema15'] = indicator_ema15.ema_indicator() df['ema30'] = indicator_ema30.ema_indicator() df['ema35'] = indicator_ema35.ema_indicator() df['ema40'] = indicator_ema40.ema_indicator() df['ema45'] = indicator_ema45.ema_indicator() df['ema50'] = indicator_ema50.ema_indicator() df['ema60'] = indicator_ema60.ema_indicator() df['rsi14'] = indicator_rsi14.rsi() df['cci20'] = indicator_cci20 ls_df.append(df.copy()) df = pd.concat(ls_df) df['score_vol_sma20'] = df[['vol', 'vol_sma20']].apply(lambda x: x[0] / x[1], axis=1) df['emash_min'] = df[[ 'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15' ]].min(axis=1) df['emash_max'] = df[[ 'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15' ]].max(axis=1) df['emash_avg'] = df[[ 'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15' ]].mean(axis=1) #df['score_short'] = df[['cls','emash_min','emash_max','emash_min']].apply(lambda x: 100 * (x[0]-x[1])/(x[2]-x[3]),axis=1) df['emalg_min'] = df[[ 'ema30', 'ema35', 'ema40', 'ema45', 'ema50', 'ema60' ]].min(axis=1) df['emalg_max'] = df[[ 'ema30', 'ema35', 'ema40', 'ema45', 'ema50', 'ema60' ]].max(axis=1) df['emalg_avg'] = df[[ 'ema30', 'ema35', 'ema40', 'ema45', 'ema50', 'ema60' ]].mean(axis=1) #df['score_long'] = df[['cls','emalg_min','emalg_max','emalg_min']].apply(lambda x: 100 * (x[0]-x[1])/(x[2]-x[3]),axis=1) df['ema_min'] = df[[ 'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15', 'ema30', 'ema35', 'ema40', 'ema45', 'ema50', 'ema60' ]].min(axis=1) df['ema_max'] = df[[ 'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15', 'ema30', 'ema35', 'ema40', 'ema45', 'ema50', 'ema60' ]].max(axis=1) df['score_ovlp_ema'] = df[[ 'emash_min', 'emalg_max', 'ema_max', 'ema_min' ]].apply(lambda x: 100 * (x[0] - x[1]) / (x[2] - x[3]), axis=1) df = pd.merge(df_stock, df, on=['sym'], how='inner').sort_values(['sort', 'ndays']) decimals = pd.Series([1, 0, 0, 2, 0, 0, 2, 0, 0, 0, 0], index=[ 'cls', 'ndays', 'vol', 'score_vol_sma20', 'bb_bbhi', 'bb_bbli', 'macd', 'obv', 'rsi14', 'cci20', 'score_ovlp_ema' ]) cols = [ 'ndays', 'dte', 'sort', 'sym', 'cls', 'vol', 'score_vol_sma20', 'bb_bbhi', 'bb_bbli', 'macd', 'obv', 'rsi14', 'cci20', 'score_ovlp_ema' ] df = df[df['ndays'] <= 10][cols].round(decimals).copy() print(df['score_ovlp_ema'].min(), df['score_ovlp_ema'].max()) df[df['sym'] == 'QQQ'].head(50) self.df = df
def setUpClass(cls): cls._df = pd.read_csv(cls._filename, sep=",") cls._params = dict(close=cls._df["Close"], volume=cls._df["Volume"], fillna=False) cls._indicator = OnBalanceVolumeIndicator(**cls._params)
#df = dropna(df_price[df_price['sym']==ticker]) df = df_price[df_price['sym'] == ticker].copy() indicator_bb = BollingerBands(close=df['cls'], window=20, window_dev=2) indicator_macd = MACD(close=df['cls'], window_fast=12, window_slow=26, window_sign=9) indicator_rsi14 = RSIIndicator(close=df['cls'], window=14) indicator_cci20 = cci(high=df['hgh'], low=df['low'], close=df['cls'], window=20, constant=0.015) indicator_obv = OnBalanceVolumeIndicator(close=df['cls'], volume=df['vol'], fillna=True) indicator_vol_sma20 = SMAIndicator(close=df['vol'], window=20) indicator_ema03 = EMAIndicator(close=df['cls'], window=3) indicator_ema05 = EMAIndicator(close=df['cls'], window=5) indicator_ema08 = EMAIndicator(close=df['cls'], window=8) indicator_ema10 = EMAIndicator(close=df['cls'], window=10) indicator_ema12 = EMAIndicator(close=df['cls'], window=12) indicator_ema15 = EMAIndicator(close=df['cls'], window=15) indicator_ema30 = EMAIndicator(close=df['cls'], window=30) indicator_ema35 = EMAIndicator(close=df['cls'], window=35) indicator_ema40 = EMAIndicator(close=df['cls'], window=40) indicator_ema45 = EMAIndicator(close=df['cls'], window=45) indicator_ema50 = EMAIndicator(close=df['cls'], window=50)