def __init__(self): dfr['EMA_12'] = EMAIndicator(close=dfr['close'], n=9, fillna=True).ema_indicator() dfr['EMA_26'] = EMAIndicator(close=dfr['close'], n=26, fillna=True).ema_indicator() MACD = MACD(close=dfr['close']) dfr['MACD'] = dfr['EMA_12'] - dfr['EMA_26'] dfr['MACD2'] = MACD.macd() dfr['MACD_Signal'] = EMAIndicator(close=dfr['MACD'], n=9).ema_indicator() dfr['MACD_Signal2'] = MACD.macd_signal() dfr['MACD_HIST'] = dfr['MACD'] - dfr['MACD_Signal'] dfr['MACD_HIST2'] = MACD.macd_diff() new_col = 'MACD_HIST_TYPE' new_col2 = 'MACD_HIST_TYPE2' nr = dfr.shape[0] dfr[new_col] = np.empty(nr) for k in range(1, nr): i1 = dfr.index.values[k - 1] i = dfr.index.values[k] if dfr.loc[i, 'MACD_HIST'] > 0 and dfr.loc[i1, 'MACD_HIST'] < 0: dfr.loc[i, new_col] = 1 # Cross over dfr.loc[i, new_col2] = 1 # Cross over if i not in long_asset_list.keys(): tlist = [] tlist.append(table_name) long_asset_list[i] = tlist elif dfr.loc[i, 'MACD_HIST'] > 0 and dfr.loc[ i, 'MACD_HIST'] > dfr.loc[i1, 'MACD_HIST']: dfr.loc[i, new_col] = 2 # Col grow above dfr.loc[i, new_col2] = 2 # Cross over elif dfr.loc[i, 'MACD_HIST'] > 0 and dfr.loc[ i, 'MACD_HIST'] < dfr.loc[i1, 'MACD_HIST']: dfr.loc[i, new_col] = 3 # Col fall above dfr.loc[i, new_col2] = 3 # Cross over elif dfr.loc[i, 'MACD_HIST'] < 0 and dfr.loc[i1, 'MACD_HIST'] > 0: a = (i, table_name) dfr.loc[i, new_col] = -1 # Cross over dfr.loc[i, new_col2] = -1 # Cross over if i not in short_asset_list.keys(): tlist = [] tlist.append(table_name) short_asset_list[i] = tlist else: short_asset_list[i].append(table_name) elif dfr.loc[i, 'MACD_HIST'] < 0 and dfr.loc[ i, 'MACD_HIST'] < dfr.loc[i1, 'MACD_HIST']: dfr.loc[i, new_col] = -2 # Col fall above dfr.loc[i, new_col2] = -2 # Cross over elif dfr.loc[i, 'MACD_HIST'] < 0 and dfr.loc[ i, 'MACD_HIST'] > dfr.loc[i1, 'MACD_HIST']: dfr.loc[i, new_col] = -3 # Cross under dfr.loc[i, new_col2] = -3 # Cross over else: dfr.loc[i, new_col] = 0 dfr.loc[i, new_col2] = 0 # Cross over
def get_MACD_Indicator(self, col='Close', fillna=False): """ get MACD Indicator """ stock_MACD = MACD(self.df[col], fillna=fillna) self.df['MACD'] = stock_MACD.macd() self.df['MACD_signal'] = stock_MACD.macd_signal() self.df['MACD_diff'] = stock_MACD.macd_diff()
def analyze(self): macd = MACD(self.df.close, n_fast=12, n_slow=26, n_sign=9) self.df["macd"] = macd.macd() self.df["signal"] = macd.macd_signal() self.df["buy_signal_macd"] = (is_crossover(self.df['macd'], self.df['signal'])) self.df["sell_signal_macd"] = (is_crossover(self.df['signal'], self.df['macd'])) self.df["buy_signal"] = (self.df["buy_signal_macd"])
def ta_macd(df): """ Moving Average Convergence Divergence (MACD) calculation. :param df: pandas dataframe :return: pandas dataframe """ temp_df = df.copy() temp = MACD(close=temp_df["Close"], fillna=False) # temp = MACD(close=temp_df["Close"], window_slow=26, window_fast=12, window_sign=9, fillna=True) temp_df["macd"] = temp.macd() temp_df["macd_diff"] = temp.macd_diff() temp_df["macd_signal"] = temp.macd_signal() return temp_df
def action(self, indicator): # Derive the action based on past data # action: 1 means buy, -1 means sell, 0 means do nothing close = indicator['c'] macd = MACD(close=close, n_slow=self.parameters['ema26'], n_fast=self.parameters['ema12'], n_sign=self.parameters['ema9']) indicator['trend_macd'] = macd.macd() indicator['trend_macd_signal'] = macd.macd_signal() indicator['trend_macd_diff'] = macd.macd_diff() indicator['trend_macd_diff_prev'] = indicator['trend_macd_diff'].shift(1) indicator['action'] = (np.sign(indicator['trend_macd_diff']) \ - np.sign(indicator['trend_macd_diff_prev'])) / 2
def get_macd(config, company): close_prices = company.prices dataframe = company.technical_indicators window_slow = 26 signal = 9 window_fast = 12 macd = MACD(company.prices, window_slow, window_fast, signal) dataframe['MACD'] = macd.macd() dataframe['MACD_Histogram'] = macd.macd_diff() dataframe['MACD_Signal'] = macd.macd_signal() generate_buy_sell_signals( lambda x, dataframe: dataframe['MACD'].values[x] < dataframe[ 'MACD_Signal'].iloc[x], lambda x, dataframe: dataframe['MACD']. values[x] > dataframe['MACD_Signal'].iloc[x], dataframe, 'MACD') return dataframe
def action(self, indicator): # Derive the action based on past data # action: 1 means buy, -1 means sell, 0 means do nothing close = indicator["c"] macd = MACD( close=close, n_slow=self.parameters["ema26"], n_fast=self.parameters["ema12"], n_sign=self.parameters["ema9"], ) indicator["trend_macd"] = macd.macd() indicator["trend_macd_signal"] = macd.macd_signal() indicator["trend_macd_diff"] = macd.macd_diff() indicator["trend_macd_diff_prev"] = indicator["trend_macd_diff"].shift( 1) indicator["action"] = (np.sign(indicator["trend_macd_diff"]) - np.sign(indicator["trend_macd_diff_prev"])) / 2
def get_signal(self, input_df, ticker, run_id): df = input_df.copy() indicator_macd = MACD( close=df["Close"], window_slow=self.indicator["window_slow"], window_fast=self.indicator["window_fast"], window_sign=self.indicator["window_sign"], fillna=self.indicator["fillna"], ) # Add Bollinger Bands features df["macd"] = indicator_macd.macd() df["macd_signal"] = indicator_macd.macd_signal() df["macd_diff"] = indicator_macd.macd_diff() previous_row = df.iloc[-2] row = df.iloc[-1] if (row.macd_diff.item() < 0) and (previous_row.macd_diff.item() > 0): sell_signal = { "ticker": ticker, "datetime": row.Date, "indicator": self.name, "param": self.param, "reason": "MACD Downward Crossover", "image": self.draw_image(df, ticker, run_id), } else: sell_signal = None if (previous_row.macd_diff.item() < 0) and (row.macd_diff.item() > 0): buy_signal = { "ticker": ticker, "datetime": row.Date, "indicator": self.name, "param": self.param, "reason": "MACD Upward Crossover", "image": self.draw_image(df, ticker, run_id), } else: buy_signal = None return buy_signal, sell_signal
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 _macd(self, df, close): macd = MACD(close=close) df['macd'] = macd.macd() df['macd_signal'] = macd.macd_signal() df['macd_diff'] = macd.macd_diff()
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 y_scaler = preprocessing.MinMaxScaler()
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
indicator_sma_200 = SMAIndicator(close=df["adj_close"], window=200) df['sma_200'] = indicator_sma_200.sma_indicator() indicator_sma_100 = SMAIndicator(close=df["adj_close"], window=100) df['sma_100'] = indicator_sma_100.sma_indicator() indicator_sma_50 = SMAIndicator(close=df["adj_close"], window=50) df['sma_50'] = indicator_sma_50.sma_indicator() # RSI Indicator indicator_rsi_6 = RSIIndicator(close=df["adj_close"], window=6) df['rsi_6'] = indicator_rsi_6.rsi() indicator_rsi_14 = RSIIndicator(close=df["adj_close"], window=14) df['rsi_14'] = indicator_rsi_14.rsi() # MACD Indicator indicator_macd = MACD(close=df["adj_close"]) df['macd'] = indicator_macd.macd() # df = df.dropna(how='all) df.set_index('trading_date', inplace=True) # Filter the latest ones df = df[df.index > last_entry_dict[equity_id]] for idx, row in df.iterrows(): trade_date = row['trading_date'] bb_bbh = row['bb_bbh'] bb_bbl = row['bb_bbl'] ema_200 = row['ema_200'] ema_100 = row['ema_100'] ema_50 = row['ema_50'] rsi_14 = row['rsi_14'] rsi_6 = row['rsi_6']
def applyIndicator(self, full_company_price): self.data = full_company_price high = self.data['high'] low = self.data['low'] close = self.data['close'] volume = self.data['volume'] EMA12 = EMAIndicator(close, 12, fillna=False) EMA30 = EMAIndicator(close, 20, fillna=False) EMA60 = EMAIndicator(close, 60, fillna=False) MACD1226 = MACD(close, 26, 12, 9, fillna=False) MACD2452 = MACD(close, 52, 24, 18, fillna=False) ROC12 = ROCIndicator(close, 12, fillna=False) ROC30 = ROCIndicator(close, 30, fillna=False) ROC60 = ROCIndicator(close, 60, fillna=False) RSI14 = RSIIndicator(close, 14, fillna=False) RSI28 = RSIIndicator(close, 28, fillna=False) RSI60 = RSIIndicator(close, 60, fillna=False) AROON25 = AroonIndicator(close, 25, fillna=False) AROON50 = AroonIndicator(close, 50, fillna=False) AROON80 = AroonIndicator(close, 80, fillna=False) MFI14 = MFIIndicator(high, low, close, volume, 14, fillna=False) MFI28 = MFIIndicator(high, low, close, volume, 28, fillna=False) MFI80 = MFIIndicator(high, low, close, volume, 80, fillna=False) CCI20 = CCIIndicator(high, low, close, 20, 0.015, fillna=False) CCI40 = CCIIndicator(high, low, close, 40, 0.015, fillna=False) CCI100 = CCIIndicator(high, low, close, 100, 0.015, fillna=False) WILLR14 = WilliamsRIndicator(high, low, close, 14, fillna=False) WILLR28 = WilliamsRIndicator(high, low, close, 28, fillna=False) WILLR60 = WilliamsRIndicator(high, low, close, 60, fillna=False) BBANDS20 = BollingerBands(close, 20, 2, fillna=False) KC20 = KeltnerChannel(high, low, close, 20, 10, fillna=False) STOCH14 = StochasticOscillator(high, low, close, 14, 3, fillna=False) STOCH28 = StochasticOscillator(high, low, close, 28, 6, fillna=False) STOCH60 = StochasticOscillator(high, low, close, 60, 12, fillna=False) CMI20 = ChaikinMoneyFlowIndicator(high, low, close, volume, 20, fillna=False) CMI40 = ChaikinMoneyFlowIndicator(high, low, close, volume, 40, fillna=False) CMI100 = ChaikinMoneyFlowIndicator(high, low, close, volume, 100, fillna=False) self.data['ema12'] = (close - EMA12.ema_indicator()) / close self.data['ema30'] = (close - EMA30.ema_indicator()) / close self.data['ema60'] = (close - EMA60.ema_indicator()) / close self.data['macd1226'] = MACD1226.macd() - MACD1226.macd_signal() self.data['macd2452'] = MACD2452.macd() - MACD2452.macd_signal() self.data['roc12'] = ROC12.roc() self.data['roc30'] = ROC30.roc() self.data['roc60'] = ROC60.roc() self.data['rsi14'] = RSI14.rsi() self.data['rsi28'] = RSI28.rsi() self.data['rsi60'] = RSI60.rsi() self.data['aroon25'] = AROON25.aroon_indicator() self.data['aroon50'] = AROON50.aroon_indicator() self.data['aroon80'] = AROON80.aroon_indicator() self.data['mfi14'] = MFI14.money_flow_index() self.data['mfi28'] = MFI28.money_flow_index() self.data['mfi80'] = MFI80.money_flow_index() self.data['cci20'] = CCI20.cci() self.data['cci40'] = CCI40.cci() self.data['cci100'] = CCI100.cci() self.data['willr14'] = WILLR14.wr() self.data['willr28'] = WILLR28.wr() self.data['willr60'] = WILLR60.wr() self.data['bband20up'] = (BBANDS20.bollinger_hband() - close) / close self.data['bband20down'] = (close - BBANDS20.bollinger_lband()) / close self.data['stoch14'] = STOCH14.stoch() self.data['stoch28'] = STOCH28.stoch() self.data['stoch60'] = STOCH60.stoch() self.data['cmi20'] = CMI20.chaikin_money_flow() self.data['cmi40'] = CMI40.chaikin_money_flow() self.data['cmi100'] = CMI100.chaikin_money_flow() self.data['kc20up'] = (KC20.keltner_channel_hband() - close) / close self.data['kc20down'] = (close - KC20.keltner_channel_lband()) / close return self.data
import pandas as pd from ta.utils import dropna import matplotlib.pyplot as plt from ta.trend import MACD import numpy as np df = pd.read_csv('TSLA.csv', sep=',') # clean NaN df = dropna(df) macd = MACD(close=df["Close"]) def normalize(col): return (col - col.mean()) / col.std() df["macd"] = normalize(macd.macd()) df["macd_signal"] = normalize(macd.macd_signal()) df["macd_diff"] = normalize(macd.macd_diff()) plt.plot(df.macd, label="MACD") plt.plot(df.macd_signal, label="MACD signal") plt.plot(df.macd_diff, label="MACD diff") plt.title("TSLA MACD") plt.show() with open("TSLA_ta.csv", "w") as f: f.write(df.to_csv())
df['Centerline Crossover'] = np.where(df['macd'] < 0, -1, df['Centerline Crossover']) except TypeError as e: df['Signal Line Crossover'] = 111 df['Signal Line Crossover'] = 111 df['Buy Sell signal line'] = 111 df['Centerline Crossover'] =111 df['Centerline Crossover'] =111 """For MACD""" indicator = MACD(close=df["close_price"], n_slow=26, n_fast=12, n_sign=9, fillna=False) MACD_INDICATOR = "MACD_indicator" # print(indicator) df[MACD_INDICATOR] = indicator.macd() df["MACD_SIGNAL_indicator"] = indicator.macd_signal() df2 = df2.append(df) df2.to_csv('MACD_price_buy_sell.csv', mode='w', header=False) m=m+1 def pg_load_table(file_path, table_name1, dbname, host, port, user, pwd): ''' This function upload csv to a target table ''' try: conn = psycopg2.connect(dbname=dbname, host=host, port=port, user=user, password=pwd) print("Connecting to Database") cur = conn.cursor()
#pd.to_datetime(EURUSD_T_FX.index) print(EURUSD_T_FX.head()) #input() # Calculate the macd and macd_sig lines. # Start an instance of a MACD object EURUSD_T_FX_MACD = MACD(close = EURUSD_T_FX["Last"]) # Set up new columns in df to hold macd method outputs for macd line and the signal line EURUSD_T_FX['MACD'] = EURUSD_T_FX_MACD.macd() EURUSD_T_FX['MACD_sig'] = EURUSD_T_FX_MACD.macd_signal() # Run the macd line and signal line though the cross-over trigger function MACD_crossover_signal = MACD_crossover_trigger(EURUSD_T_FX.Last, EURUSD_T_FX['MACD'], EURUSD_T_FX['MACD_sig']) MACD_buy_sig = MACD_crossover_signal[0] MACD_sell_sig = MACD_crossover_signal[1] length = len(MACD_buy_sig) for i in range(0, length): if str(MACD_buy_sig[i]) == 'nan': MACD_buy_sig[i] = 0
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 macd(df): indicator_macd = MACD(close=df["Close"]) df['macd'] = indicator_macd.macd() df['macd_diff'] = indicator_macd.macd_diff() df['macd_signal'] = indicator_macd.macd_signal()
FX_data['Last'] = Last print(FX_data.head()) print("Data loaded") print("###########") # Calculate the macd and macd_sig lines. # Start an instance of a MACD object FX_data_MACD = MACD(close = FX_data["Last"]) # Set up new columns in df to hold macd method outputs for macd line and the signal line FX_data['MACD'] = FX_data_MACD.macd() FX_data['MACD_sig'] = FX_data_MACD.macd_signal() # Run the macd line and signal line though the cross-over trigger function MACD_crossover_signal = MACD_crossover_trigger(FX_data.Last, FX_data['MACD'], FX_data['MACD_sig']) MACD_buy_sig = MACD_crossover_signal[0] MACD_sell_sig = MACD_crossover_signal[1] length = len(MACD_buy_sig) for i in range(0, length): if str(MACD_buy_sig[i]) == 'nan': MACD_buy_sig[i] = 0
def AddFeatures(data, category): """Add feature to the data. Args: -- data : (DataFrame) The DataFrame of the stocks. category : (str) Composed of 5 arguments. "all" : Append all features. "trend": Append all trend-related features. "volatility": Append all volatile-related features. "volume": Append all volume-related features. "emaribbon": Append all ema + volume features. "oscillators": Append all oscillators + volume features. Returns: pandas.core.frame.DataFrame: Dataframe with new features. """ # Store list of tradable stocks if len(data["stock code"]) > 0: data.drop("stock code", 1, inplace=True) # drop stock code data = data.apply(pd.to_numeric) if category == "all" or category == "momentum": # Append all Momentum-related features print(f'data ${data}') data = ta.add_momentum_ta(data, high="High", low="Low", close="Close", volume="Volume") elif category == "all" or category == "trend": # Append all tren-related features data = ta.add_trend_ta(data, high="High", low="Low", close="Close") elif category == "all" or category == "volatility": # Append all volatility-related features data = ta.add_volatility_ta(data, high="High", low="Low", close="Close") elif category == "all" or category == "volume": # Append all volume-related features data = ta.add_volume_ta(data, high="High", low="Low", close="Close", volume="Volume") elif category == "emaribbon": # Append user-specified features data = indicators.ema(data, period=9) data = indicators.ema(data, period=20) data = indicators.ema(data, period=25) data = indicators.ema(data, period=30) data = indicators.ema(data, period=35) data = indicators.ema(data, period=40) data = indicators.ema(data, period=45) data = indicators.ema(data, period=50) data = indicators.ema(data, period=55) data = indicators.volume(data, period=20) elif category == 'bottom_fish': # BUY: # CCI > -100 # DCHL/DCHLI: Candle must touch the the lower indicators0 data = ta.add_all_ta_features(data, open='Open', high='High', low='Low', close='Close', volume='Volume') bottom_fish_list = ["Open","High","Low","Close", "Volume", \ "volatility_dcl", "volatility_dch", "volatility_dcli", "volatility_dchi", "trend_cci"] bottom_fish = data[bottom_fish_list] bottom_fish['volatility_dcl'] = data['volatility_dcl'] bottom_fish['volatility_dch'] = data['volatility_dch'] bottom_fish['volatility_dcli'] = data['volatility_dcl'] bottom_fish['volatility_dchi'] = data['volatility_dch'] bottom_fish['trend_cci'] = data['trend_cci'] bottom_fish = indicators.volume(bottom_fish, period=20) data = bottom_fish elif category == 'macdo': indicator_macd = MACD(close=data['Close'], n_slow=20, n_fast=5, n_sign=5) data['trend_macd'] = indicator_macd.macd() data = indicators.ma(data, period=200) data = indicators.ema(data, period=62) data = indicators.ema(data, period=38) data = indicators.volume(data, period=20) elif category == 'almarsi': alma_indicator = ALMAIndicator(close=data['Close']) data['alma9'] = alma_indicator.alma() # data['alma20'] = alma_indicator.alma_weights(window=20) # data['alma50'] = alma_indicator.alma_weights(window=50) data = indicators.rsi(data, period=9) data = indicators.rsi(data, period=25) data = indicators.rsi(data, period=12) # print (data) if category == "all": data.dropna(inplace=True, axis=1) else: data.dropna(inplace=True) # print (data) # Scale the value for col in data.columns[:]: data[col] = preprocessing.scale(data[col].values) # print (data) return data
def create_env(config): df = load_csv('btc_usdt_m5_history.csv') from ta.trend import ( MACD, ADXIndicator, AroonIndicator, CCIIndicator, DPOIndicator, EMAIndicator, IchimokuIndicator, KSTIndicator, MassIndex, PSARIndicator, SMAIndicator, STCIndicator, TRIXIndicator, VortexIndicator, ) colprefix = "" # MACD indicator_macd = MACD(close=df['close'], window_slow=26, window_fast=12, window_sign=9, fillna=True) 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() #df = ta.add_trend_ta(df,'high', 'low', 'close', fillna=True) #df = ta.add_volume_ta(df,'high', 'low', 'close', 'volume', fillna=True) #df = ta.add_volume_ta(df, 'high', 'low', 'close', 'volume', fillna=True) #df = ta.add_volatility_ta(df, 'high', 'low', 'close', fillna=True) price_history = df[['date', 'open', 'high', 'low', 'close', 'volume']] # chart data df.drop(columns=['date', 'open', 'high', 'low', 'close', 'volume'], inplace=True) print(df.head(5)) with NameSpace("bitfinex"): streams = [ Stream.source(df[c].tolist(), dtype="float").rename(c) for c in df.columns ] feed_ta_features = DataFeed(streams) price_list = price_history['close'].tolist() p = Stream.source(price_list, dtype="float").rename("USD-BTC") bitfinex = Exchange("bitfinex", service=execute_order)(p) cash = Wallet(bitfinex, 10000 * USD) asset = Wallet(bitfinex, 0 * BTC) portfolio = Portfolio(USD, [cash, asset]) reward_scheme = default.rewards.SimpleProfit(window_size=1) #action_scheme = default.actions.BSHEX( # cash=cash, # asset=asset #).attach(reward_scheme) action_scheme = default.actions.SimpleOrders(trade_sizes=3) renderer_feed_ptc = DataFeed([ Stream.source(list(price_history["date"])).rename("date"), Stream.source(list(price_history["open"]), dtype="float").rename("open"), Stream.source(list(price_history["high"]), dtype="float").rename("high"), Stream.source(list(price_history["low"]), dtype="float").rename("low"), Stream.source(list(price_history["close"]), dtype="float").rename("close"), Stream.source(list(price_history["volume"]), dtype="float").rename("volume") ]) env = default.create( feed=feed_ta_features, portfolio=portfolio, #renderer=PositionChangeChart(), renderer=default.renderers.PlotlyTradingChart(), action_scheme=action_scheme, reward_scheme=reward_scheme, renderer_feed=renderer_feed_ptc, window_size=config["window_size"], max_allowed_loss=0.1) return env
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}")
start = datetime(2000, 9, 1) ETH = pdr.DataReader(symbol,'yahoo',start,end) df = pd.DataFrame(data=ETH) kama_indicator = KAMAIndicator(close = df["Close"], window = 10, pow1 = 2, pow2 = 30, fillna = False) df['kama'] = kama_indicator.kama() ppo_indicator = PercentagePriceOscillator(close = df["Close"], window_slow = 20, window_fast = 10, window_sign = 9, fillna = False) df['ppo'] = ppo_indicator.ppo() roc_indicator = ROCIndicator(close = df["Close"], window = 12, fillna = False) df['roc'] = roc_indicator.roc() macd_indicator = MACD(close = df["Close"], window_slow = 20, window_fast = 12, window_sign = 9, fillna = False) df['macd'] = macd_indicator.macd() rsi_indicator = RSIIndicator(close = df["Close"], window = 14, fillna = False) df['rsi'] = rsi_indicator.rsi() aroon_indicator = AroonIndicator(close = df["Close"], window = 20, fillna = False) df['aroon'] = aroon_indicator.aroon_indicator() boll_indicator = BollingerBands(close = df["Close"], window = 20, window_dev = 2, fillna = False) df['boll_mavg'] = boll_indicator.bollinger_mavg() df.rename(columns = {"Close": "price"}, inplace=True) prices = df['price'].to_numpy() df['day_of_month'] = df.index.day df['day_of_week'] = df.index.dayofweek
#%%画K线主图 datacent = go.Datacent() if datacent.qihuo_connectSer(): qihuocount = list(range(len(cf.cfqihuo))) df = datacent.qihuoK(cflen) df = tdx_tools.SuperTrend( df, period=cf.st_period_fast, multiplier=cf.st_mult_fast, ) df = tdx_tools.StochRSI(df, m=14, p=7) dfmacd = MACD(df['close'], n_slow=10, n_fast=5, n_sign=89) df["macd"] = dfmacd.macd() df['diff'] = dfmacd.macd_diff() df['macd_signal'] = dfmacd.macd_signal() df = df.iloc[100:] weekday_quotes = [ tuple([i] + list(quote[1:])) for i, quote in enumerate(df.values, ) ] fig = plt.figure(figsize=(1000 / 72, 500 / 72), facecolor='#CCCCCC', edgecolor='#CCCCCC') df = df.reset_index() df = actionOrder(df)