def add_trend_indicators(data: pd.DataFrame) -> pd.DataFrame: """Adds the trend 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. """ adx = ADXIndicator(data['high'], data['low'], data['close']) ema = EMAIndicator(data['close']) ema_200 = EMAIndicator(data['close'], n=200) ichimoku = IchimokuIndicator(data['high'], data['low']) macd = MACD(data['close']) sma = SMAIndicator(data['close'], n=14) sma_200 = SMAIndicator(data['close'], n=200) data.loc[:, 'adx'] = adx.adx() data.loc[:, 'adx_pos'] = adx.adx_pos() data.loc[:, 'adx_neg'] = adx.adx_neg() data.loc[:, 'ema'] = ema.ema_indicator() data.loc[:, 'ema_200'] = ema_200.ema_indicator() data.loc[:, 'ichimoku_a'] = ichimoku.ichimoku_a() data.loc[:, 'ichimoku_b'] = ichimoku.ichimoku_b() data.loc[:, 'ichimoku_base_line'] = ichimoku.ichimoku_base_line() data.loc[:, 'ichimoku_conversion_line'] = ( ichimoku.ichimoku_conversion_line()) data.loc[:, 'macd'] = macd.macd() data.loc[:, 'macd_diff'] = macd.macd_diff() data.loc[:, 'macd_signal'] = macd.macd_signal() data.loc[:, 'sma'] = sma.sma_indicator() data.loc[:, 'sma_200'] = sma_200.sma_indicator() return data
def add_trend_ta( df: pd.DataFrame, high: str, low: str, close: str, fillna: bool = False, colprefix: str = "", vectorized: bool = False, ) -> pd.DataFrame: """Add trend 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. fillna(bool): if True, fill nan values. colprefix(str): Prefix column names inserted vectorized(bool): if True, use only vectorized functions indicators Returns: pandas.core.frame.DataFrame: Dataframe with new features. """ # MACD indicator_macd = MACD(close=df[close], window_slow=26, window_fast=12, window_sign=9, fillna=fillna) df[f"{colprefix}trend_macd"] = indicator_macd.macd() df[f"{colprefix}trend_macd_signal"] = indicator_macd.macd_signal() df[f"{colprefix}trend_macd_diff"] = indicator_macd.macd_diff() # SMAs df[f"{colprefix}trend_sma_fast"] = SMAIndicator( close=df[close], window=12, fillna=fillna).sma_indicator() df[f"{colprefix}trend_sma_slow"] = SMAIndicator( close=df[close], window=26, fillna=fillna).sma_indicator() # EMAs df[f"{colprefix}trend_ema_fast"] = EMAIndicator( close=df[close], window=12, fillna=fillna).ema_indicator() df[f"{colprefix}trend_ema_slow"] = EMAIndicator( close=df[close], window=26, fillna=fillna).ema_indicator() # Vortex Indicator indicator_vortex = VortexIndicator(high=df[high], low=df[low], close=df[close], window=14, fillna=fillna) df[f"{colprefix}trend_vortex_ind_pos"] = indicator_vortex.vortex_indicator_pos( ) df[f"{colprefix}trend_vortex_ind_neg"] = indicator_vortex.vortex_indicator_neg( ) df[f"{colprefix}trend_vortex_ind_diff"] = indicator_vortex.vortex_indicator_diff( ) # TRIX Indicator df[f"{colprefix}trend_trix"] = TRIXIndicator(close=df[close], window=15, fillna=fillna).trix() # Mass Index df[f"{colprefix}trend_mass_index"] = MassIndex(high=df[high], low=df[low], window_fast=9, window_slow=25, fillna=fillna).mass_index() # DPO Indicator df[f"{colprefix}trend_dpo"] = DPOIndicator(close=df[close], window=20, fillna=fillna).dpo() # KST Indicator indicator_kst = KSTIndicator( close=df[close], roc1=10, roc2=15, roc3=20, roc4=30, window1=10, window2=10, window3=10, window4=15, nsig=9, fillna=fillna, ) df[f"{colprefix}trend_kst"] = indicator_kst.kst() df[f"{colprefix}trend_kst_sig"] = indicator_kst.kst_sig() df[f"{colprefix}trend_kst_diff"] = indicator_kst.kst_diff() # Ichimoku Indicator indicator_ichi = IchimokuIndicator( high=df[high], low=df[low], window1=9, window2=26, window3=52, visual=False, fillna=fillna, ) df[f"{colprefix}trend_ichimoku_conv"] = indicator_ichi.ichimoku_conversion_line( ) df[f"{colprefix}trend_ichimoku_base"] = indicator_ichi.ichimoku_base_line() df[f"{colprefix}trend_ichimoku_a"] = indicator_ichi.ichimoku_a() df[f"{colprefix}trend_ichimoku_b"] = indicator_ichi.ichimoku_b() # Schaff Trend Cycle (STC) df[f"{colprefix}trend_stc"] = STCIndicator( close=df[close], window_slow=50, window_fast=23, cycle=10, smooth1=3, smooth2=3, fillna=fillna, ).stc() if not vectorized: # Average Directional Movement Index (ADX) indicator_adx = ADXIndicator(high=df[high], low=df[low], close=df[close], window=14, fillna=fillna) df[f"{colprefix}trend_adx"] = indicator_adx.adx() df[f"{colprefix}trend_adx_pos"] = indicator_adx.adx_pos() df[f"{colprefix}trend_adx_neg"] = indicator_adx.adx_neg() # CCI Indicator df[f"{colprefix}trend_cci"] = CCIIndicator( high=df[high], low=df[low], close=df[close], window=20, constant=0.015, fillna=fillna, ).cci() # Ichimoku Visual Indicator indicator_ichi_visual = IchimokuIndicator( high=df[high], low=df[low], window1=9, window2=26, window3=52, visual=True, fillna=fillna, ) df[f"{colprefix}trend_visual_ichimoku_a"] = indicator_ichi_visual.ichimoku_a( ) df[f"{colprefix}trend_visual_ichimoku_b"] = indicator_ichi_visual.ichimoku_b( ) # Aroon Indicator indicator_aroon = AroonIndicator(close=df[close], window=25, fillna=fillna) df[f"{colprefix}trend_aroon_up"] = indicator_aroon.aroon_up() df[f"{colprefix}trend_aroon_down"] = indicator_aroon.aroon_down() df[f"{colprefix}trend_aroon_ind"] = indicator_aroon.aroon_indicator() # PSAR Indicator indicator_psar = PSARIndicator( high=df[high], low=df[low], close=df[close], step=0.02, max_step=0.20, fillna=fillna, ) # df[f'{colprefix}trend_psar'] = indicator.psar() df[f"{colprefix}trend_psar_up"] = indicator_psar.psar_up() df[f"{colprefix}trend_psar_down"] = indicator_psar.psar_down() df[f"{colprefix}trend_psar_up_indicator"] = indicator_psar.psar_up_indicator( ) df[f"{colprefix}trend_psar_down_indicator"] = indicator_psar.psar_down_indicator( ) return df
def add_trend_ta(df: pd.DataFrame, high: str, low: str, close: str, fillna: bool = False, colprefix: str = ""): """Add trend 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. fillna(bool): if True, fill nan values. colprefix(str): Prefix column names inserted Returns: pandas.core.frame.DataFrame: Dataframe with new features. """ # MACD indicator_macd = MACD(close=df[close], n_fast=12, n_slow=26, n_sign=9, fillna=fillna) df[f'{colprefix}trend_macd'] = indicator_macd.macd() df[f'{colprefix}trend_macd_signal'] = indicator_macd.macd_signal() df[f'{colprefix}trend_macd_diff'] = indicator_macd.macd_diff() # EMAs df[f'{colprefix}trend_ema_fast'] = EMAIndicator( close=df[close], n=12, fillna=fillna).ema_indicator() df[f'{colprefix}trend_ema_slow'] = EMAIndicator( close=df[close], n=26, fillna=fillna).ema_indicator() # Average Directional Movement Index (ADX) indicator = ADXIndicator(high=df[high], low=df[low], close=df[close], n=14, fillna=fillna) df[f'{colprefix}trend_adx'] = indicator.adx() df[f'{colprefix}trend_adx_pos'] = indicator.adx_pos() df[f'{colprefix}trend_adx_neg'] = indicator.adx_neg() # Vortex Indicator indicator = VortexIndicator(high=df[high], low=df[low], close=df[close], n=14, fillna=fillna) df[f'{colprefix}trend_vortex_ind_pos'] = indicator.vortex_indicator_pos() df[f'{colprefix}trend_vortex_ind_neg'] = indicator.vortex_indicator_neg() df[f'{colprefix}trend_vortex_ind_diff'] = indicator.vortex_indicator_diff() # TRIX Indicator indicator = TRIXIndicator(close=df[close], n=15, fillna=fillna) df[f'{colprefix}trend_trix'] = indicator.trix() # Mass Index indicator = MassIndex(high=df[high], low=df[low], n=9, n2=25, fillna=fillna) df[f'{colprefix}trend_mass_index'] = indicator.mass_index() # CCI Indicator indicator = CCIIndicator(high=df[high], low=df[low], close=df[close], n=20, c=0.015, fillna=fillna) df[f'{colprefix}trend_cci'] = indicator.cci() # DPO Indicator indicator = DPOIndicator(close=df[close], n=20, fillna=fillna) df[f'{colprefix}trend_dpo'] = indicator.dpo() # KST Indicator indicator = KSTIndicator(close=df[close], r1=10, r2=15, r3=20, r4=30, n1=10, n2=10, n3=10, n4=15, nsig=9, fillna=fillna) df[f'{colprefix}trend_kst'] = indicator.kst() df[f'{colprefix}trend_kst_sig'] = indicator.kst_sig() df[f'{colprefix}trend_kst_diff'] = indicator.kst_diff() # Ichimoku Indicator indicator = IchimokuIndicator(high=df[high], low=df[low], n1=9, n2=26, n3=52, visual=False, fillna=fillna) df[f'{colprefix}trend_ichimoku_a'] = indicator.ichimoku_a() df[f'{colprefix}trend_ichimoku_b'] = indicator.ichimoku_b() indicator = IchimokuIndicator(high=df[high], low=df[low], n1=9, n2=26, n3=52, visual=True, fillna=fillna) df[f'{colprefix}trend_visual_ichimoku_a'] = indicator.ichimoku_a() df[f'{colprefix}trend_visual_ichimoku_b'] = indicator.ichimoku_b() # Aroon Indicator indicator = AroonIndicator(close=df[close], n=25, fillna=fillna) df[f'{colprefix}trend_aroon_up'] = indicator.aroon_up() df[f'{colprefix}trend_aroon_down'] = indicator.aroon_down() df[f'{colprefix}trend_aroon_ind'] = indicator.aroon_indicator() # PSAR Indicator indicator = PSARIndicator(high=df[high], low=df[low], close=df[close], step=0.02, max_step=0.20, fillna=fillna) df[f'{colprefix}trend_psar'] = indicator.psar() df[f'{colprefix}trend_psar_up'] = indicator.psar_up() df[f'{colprefix}trend_psar_down'] = indicator.psar_down() df[f'{colprefix}trend_psar_up_indicator'] = indicator.psar_up_indicator() df[f'{colprefix}trend_psar_down_indicator'] = indicator.psar_down_indicator( ) return df
def handle(self, *args, **options): # import pdb # pdb.set_trace() if not options['update']: NSETechnical.objects.all().delete() symbols = Symbol.objects.all() for symbol in symbols: nse_history_data = NSEHistoricalData.objects.filter( symbol__symbol_name=symbol).order_by('timestamp') if not nse_history_data: continue nse_technical = pd.DataFrame( list( nse_history_data.values('timestamp', 'open', 'high', 'low', 'close', 'total_traded_quantity'))) ''' Moving average convergence divergence ''' indicator_macd = MACD(close=nse_technical['close'], window_slow=26, window_fast=12, window_sign=9, fillna=False) nse_technical["trend_macd"] = indicator_macd.macd() nse_technical["trend_macd_signal"] = indicator_macd.macd_signal() nse_technical["trend_macd_diff"] = indicator_macd.macd_diff() ''' Simple Moving Average ''' nse_technical["trend_sma_fast"] = SMAIndicator( close=nse_technical['close'], window=12, fillna=False).sma_indicator() nse_technical["trend_sma_slow"] = SMAIndicator( close=nse_technical['close'], window=26, fillna=False).sma_indicator() ''' Exponential Moving Average ''' nse_technical["trend_ema_fast"] = EMAIndicator( close=nse_technical['close'], window=12, fillna=False).ema_indicator() nse_technical["trend_ema_slow"] = EMAIndicator( close=nse_technical['close'], window=26, fillna=False).ema_indicator() ''' Ichimoku Indicator ''' indicator_ichi = IchimokuIndicator( high=nse_technical['high'], low=nse_technical['low'], window1=9, window2=26, window3=52, visual=False, fillna=False, ) nse_technical[ "trend_ichimoku_conv"] = indicator_ichi.ichimoku_conversion_line( ) nse_technical[ "trend_ichimoku_base"] = indicator_ichi.ichimoku_base_line() nse_technical["trend_ichimoku_a"] = indicator_ichi.ichimoku_a() nse_technical["trend_ichimoku_b"] = indicator_ichi.ichimoku_b() indicator_ichi_visual = IchimokuIndicator( high=nse_technical['high'], low=nse_technical['low'], window1=9, window2=26, window3=52, visual=True, fillna=False, ) nse_technical[ "trend_visual_ichimoku_a"] = indicator_ichi_visual.ichimoku_a( ) nse_technical[ "trend_visual_ichimoku_b"] = indicator_ichi_visual.ichimoku_b( ) ''' Bollinger Band ''' indicator_bb = BollingerBands(close=nse_technical['close'], window=20, window_dev=2, fillna=False) nse_technical["volatility_bbm"] = indicator_bb.bollinger_mavg() nse_technical["volatility_bbh"] = indicator_bb.bollinger_hband() nse_technical["volatility_bbl"] = indicator_bb.bollinger_lband() nse_technical["volatility_bbw"] = indicator_bb.bollinger_wband() nse_technical["volatility_bbp"] = indicator_bb.bollinger_pband() nse_technical[ "volatility_bbhi"] = indicator_bb.bollinger_hband_indicator() nse_technical[ "volatility_bbli"] = indicator_bb.bollinger_lband_indicator() ''' Accumulation Distribution Index ''' nse_technical["volume_adi"] = AccDistIndexIndicator( high=nse_technical['high'], low=nse_technical['low'], close=nse_technical['close'], volume=nse_technical['total_traded_quantity'], fillna=False).acc_dist_index() ''' Money Flow Index ''' nse_technical["volume_mfi"] = MFIIndicator( high=nse_technical['high'], low=nse_technical['low'], close=nse_technical['close'], volume=nse_technical['total_traded_quantity'], window=14, fillna=False, ).money_flow_index() ''' Relative Strength Index (RSI) ''' nse_technical["momentum_rsi"] = RSIIndicator( close=nse_technical['close'], window=14, fillna=False).rsi() ''' Stoch RSI (StochRSI) ''' indicator_srsi = StochRSIIndicator(close=nse_technical['close'], window=14, smooth1=3, smooth2=3, fillna=False) nse_technical["momentum_stoch_rsi"] = indicator_srsi.stochrsi() nse_technical["momentum_stoch_rsi_k"] = indicator_srsi.stochrsi_k() nse_technical["momentum_stoch_rsi_d"] = indicator_srsi.stochrsi_d() nse_technical.replace({np.nan: None}, inplace=True) nse_technical.replace([np.inf, -np.inf], None, inplace=True) list_to_create = [] list_to_update = [] for index in range(len(nse_history_data) - 1, -1, -1): data = nse_history_data[index] if data.technicals: break technical = NSETechnical( nse_historical_data=data, trend_macd=nse_technical['trend_macd'][index], trend_macd_signal=nse_technical['trend_macd_signal'] [index], trend_macd_diff=nse_technical['trend_macd_diff'][index], trend_sma_fast=nse_technical['trend_sma_fast'][index], trend_sma_slow=nse_technical['trend_sma_slow'][index], trend_ema_fast=nse_technical['trend_ema_fast'][index], trend_ema_slow=nse_technical['trend_ema_slow'][index], trend_ichimoku_conv=nse_technical['trend_ichimoku_conv'] [index], trend_ichimoku_base=nse_technical['trend_ichimoku_base'] [index], trend_ichimoku_a=nse_technical['trend_ichimoku_a'][index], trend_ichimoku_b=nse_technical['trend_ichimoku_b'][index], trend_visual_ichimoku_a=nse_technical[ 'trend_visual_ichimoku_a'][index], trend_visual_ichimoku_b=nse_technical[ 'trend_visual_ichimoku_b'][index], volatility_bbm=nse_technical['volatility_bbm'][index], volatility_bbh=nse_technical['volatility_bbh'][index], volatility_bbl=nse_technical['volatility_bbl'][index], volatility_bbw=nse_technical['volatility_bbw'][index], volatility_bbp=nse_technical['volatility_bbp'][index], volatility_bbhi=nse_technical['volatility_bbhi'][index], volatility_bbli=nse_technical['volatility_bbli'][index], volume_adi=nse_technical['volume_adi'][index], volume_mfi=nse_technical['volume_mfi'][index], momentum_rsi=nse_technical['momentum_rsi'][index], momentum_stoch_rsi=nse_technical['momentum_stoch_rsi'] [index], momentum_stoch_rsi_k=nse_technical['momentum_stoch_rsi_k'] [index], momentum_stoch_rsi_d=nse_technical['momentum_stoch_rsi_d'] [index]) data.technicals = True list_to_update.append(data) list_to_create.append(technical) NSETechnical.objects.bulk_create(list_to_create) NSEHistoricalData.objects.bulk_update(list_to_update, ['technicals']) print(f"Technicals updated for {symbol}")
from ta.trend import MACD from ta.momentum import RSIIndicator from keras.models import Sequential from keras.layers import Conv1D, MaxPool1D, Bidirectional, LSTM, Dropout, TimeDistributed from keras.layers import Dense, GlobalAveragePooling2D from ta.trend import IchimokuIndicator from sklearn.linear_model import LinearRegression from ta import add_all_ta_features from ta.utils import dropna import matplotlib.pyplot as plt filename = 'AAPL' stock = pd.read_csv('Data/' + filename + '.csv') indicator_bb = BollingerBands(close=stock["Close"], n=20, ndev=2) macd = MACD(close=stock["Close"]) rsi = RSIIndicator(close=stock["Close"]) ichi = IchimokuIndicator(high=stock["High"], low=stock["Low"]) stock['macd'] = macd.macd() stock['rsi'] = rsi.rsi() stock['bb_bbm'] = indicator_bb.bollinger_mavg() stock['bb_bbh'] = indicator_bb.bollinger_hband() stock['bb_bbl'] = indicator_bb.bollinger_lband() stock['ichi_a'] = ichi.ichimoku_a() stock['ichi_b'] = ichi.ichimoku_b() stock['ichi_base'] = ichi.ichimoku_base_line() stock['ichi_conv'] = ichi.ichimoku_conversion_line() stock = stock.fillna(0) print(stock) scaler = preprocessing.MinMaxScaler() scaled_values = scaler.fit_transform(stock.iloc[:, 1:4]) stock.iloc[:, 1:4] = scaled_values