def init(self, base_data): base_data = base_data.sort_values("date") macd = MACD(close=base_data["close"], n_slow=26, n_fast=12, n_sign=9) base_data["macd_diff"] = macd.macd_diff() base_data["macd_signal"] = macd.macd_signal() base_data["fs_dif"] = base_data["macd_diff"] - base_data["macd_signal"] base_data["bool_signal"] = base_data["fs_dif"].map( lambda x: 1 if x > 0 else -1 ) base_data["bool_signal_shift1"] = base_data["bool_signal"].shift(1) base_data["signal"] = 0 base_data.loc[ ( (base_data["bool_signal"] > 0) & (base_data["bool_signal_shift1"] < 0) ), "signal", ] = 1 base_data.loc[ ( (base_data["bool_signal"] < 0) & (base_data["bool_signal_shift1"] > 0) ), "signal", ] = -1 base_data.index = range(len(base_data)) return base_data
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 __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 test_macd2(self): target = 'MACD_line' result = MACD(close=self._df['Close'], n_slow=12, n_fast=26, n_sign=9, fillna=False).macd() pd.testing.assert_series_equal(self._df[target].tail(), result.tail(), check_names=False)
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 add_indicators(self,data): warnings.filterwarnings("ignore",category=RuntimeWarning) # SMA n =20 data['ma'] = SMAIndicator(data['Close'],20).sma_indicator() data['rsi'] = RSIIndicator(data['Close'],14).rsi() data['macd'] = MACD(data['Close'],26,12,9).macd() data['macd_signal'] = MACD(data['Close'],26,12,9).macd_signal() data['macd_hist'] = MACD(data['Close'],26,12,9).macd_diff() data['adx'] = ADXIndicator(data['High'],data['Low'],data['Close'],14).adx() data['adx_neg'] = ADXIndicator(data['High'],data['Low'],data['Close'],14).adx_neg() data['adx_pos'] = ADXIndicator(data['High'],data['Low'],data['Close'],14).adx_pos() return data
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 setUpClass(cls): cls._df = pd.read_csv(cls._filename, sep=',') cls._params = dict(close=cls._df['Close'], n_slow=26, n_fast=12, n_sign=9, fillna=False) cls._indicator = MACD(**cls._params)
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 create_trade_sign(self, stock_price: pd.DataFrame) -> pd.DataFrame: stock_price = stock_price.sort_values("date") macd = MACD(close=stock_price["close"], n_slow=26, n_fast=12, n_sign=9) stock_price["macd_diff"] = macd.macd_diff() stock_price["macd_signal"] = macd.macd_signal() stock_price["fs_dif"] = (stock_price["macd_diff"] - stock_price["macd_signal"]) stock_price["bool_signal"] = stock_price["fs_dif"].map( lambda x: 1 if x > 0 else -1) stock_price["bool_signal_shift1"] = stock_price["bool_signal"].shift(1) stock_price["signal"] = 0 stock_price.loc[((stock_price["bool_signal"] > 0) & (stock_price["bool_signal_shift1"] < 0)), "signal", ] = 1 stock_price.loc[((stock_price["bool_signal"] < 0) & (stock_price["bool_signal_shift1"] > 0)), "signal", ] = -1 stock_price.index = range(len(stock_price)) return stock_price
def create_trade_sign(self, stock_price: pd.DataFrame) -> pd.DataFrame: stock_price = stock_price.sort_values("date") macd = MACD(close=stock_price["close"], n_slow=26, n_fast=12, n_sign=9) stock_price["DIF"] = macd.macd_diff() stock_price["MACD"] = macd.macd_signal() stock_price["OSC"] = stock_price["DIF"] - stock_price["MACD"] stock_price["OSC_signal"] = stock_price["OSC"].map(lambda x: 1 if x > 0 else -1) stock_price["OSC_signal_yesterday"] = stock_price["OSC_signal"].shift( 1) stock_price["signal"] = 0 stock_price.loc[((stock_price["OSC_signal"] > 0) & (stock_price["OSC_signal_yesterday"] < 0)), "signal", ] = 1 # 下而上穿過 stock_price.loc[((stock_price["OSC_signal"] < 0) & (stock_price["OSC_signal_yesterday"] > 0)), "signal", ] = -1 # 上而下穿過 stock_price.index = range(len(stock_price)) return stock_price
def setUpClass(cls): cls._df = pd.read_csv(cls._filename, sep=",") cls._params = dict( close=cls._df["Close"], window_slow=26, window_fast=12, window_sign=9, fillna=False, ) cls._indicator = MACD(**cls._params)
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 handler(event, context): # DynamoDb dynamodb = boto3.resource('dynamodb') tableName = os.environ['DATABASE'] table = dynamodb.Table(tableName) # Get stock data stock = yf.Ticker(event['symbol']) if (event['date']): endDate = datetime.strptime(event['date'], "%Y-%m-%d") else: endDate = datetime.utcnow() startDate = endDate - timedelta(weeks=260) stock_data = stock.history(end=endDate, start=startDate, interval="5d") # Calculate impulse system macd_hist = MACD(stock_data["Close"], fillna=True).macd_diff() ema = EMAIndicator(stock_data["Close"], n=13, fillna=True).ema_indicator() shouldBeGreen = ema.iloc[-1] > ema.iloc[-2] and macd_hist.iloc[ -1] > macd_hist.iloc[-2] shouldBeRed = ema.iloc[-1] < ema.iloc[-2] and macd_hist.iloc[ -1] < macd_hist.iloc[-2] color = 'green' if shouldBeGreen else 'red' if shouldBeRed else 'blue' dateString = endDate.strftime("%Y-%m-%d") id = str(uuid.uuid4()) entry = { 'symbol': event['symbol'], 'security': event['security'], 'sector': event['sector'], 'id': id, 'date': dateString, 'weekly': { 'type': 'impulse_system', 'result': color, } } table.put_item(Item=entry) return entry
def acceptCandle(self, candle): ''' accepts a candle and updates current state of strategy to determine buy/sell ''' self.addCandle(candle) macd = MACD(self.candleDf['C']) # print(macd.macd().iloc[-1], macd.macd_signal().iloc[-1], macd.macd_diff().iloc[-1], macd.macd().iloc[-1] - macd.macd_signal().iloc()[-1]) if macd.macd_diff().iloc[-1] >= 0 and macd.macd_diff().iloc[-2] < 0: self.buy(0.05 * self.capital) elif macd.macd_diff().iloc[-1] <= 0 and macd.macd_diff().iloc[-2] > 0: self.sell()
def acceptCandle(self, candle): ''' accepts a candle and updates current state of strategy to determine buy/sell ''' self.addCandle(candle) macd = MACD(self.candleDf['C'], 20, 6, 5) rsi = RSIIndicator(self.candleDf['C'], 8) prevRsi = rsi.rsi().iloc[-2] currentRsi = rsi.rsi().iloc[-1] # print(macd.macd().iloc[-1], macd.macd_signal().iloc[-1], macd.macd_diff().iloc[-1], macd.macd().iloc[-1] - macd.macd_signal().iloc()[-1]) if macd.macd_diff().iloc[-1] >= 0 and macd.macd_diff().iloc[-2] < 0\ and currentRsi >= self.oversold and prevRsi < self.oversold: self.buy(0.05 * self.capital) elif macd.macd_diff().iloc[-1] <= 0 and macd.macd_diff().iloc[-2] > 0\ and currentRsi <= self.overbought and prevRsi > self.overbought: self.sell()
end = datetime.today() 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
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 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
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()
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()
# SMA Indicator 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']
def test_macd_diff2(self): target = 'MACD_diff' result = MACD(**self._params).macd_diff() pd.testing.assert_series_equal(self._df[target].tail(), result.tail(), check_names=False)
############## # Stock data # ############## # https://technical-analysis-library-in-python.readthedocs.io/en/latest/ta.html#momentum-indicators df = yf.download(option, start=start_date, end=end_date, progress=False) indicator_bb = BollingerBands(df['Close']) bb = df bb['bb_h'] = indicator_bb.bollinger_hband() bb['bb_l'] = indicator_bb.bollinger_lband() bb = bb[['Close', 'bb_h', 'bb_l']] macd = MACD(df['Close']).macd() rsi = RSIIndicator(df['Close']).rsi() ################### # Set up main app # ################### st.write('Stock Bollinger Bands') st.line_chart(bb) progress_bar = st.progress(0) # https://share.streamlit.io/daniellewisdl/streamlit-cheat-sheet/app.py
def handler(event, context): # DynamoDb dynamodb = boto3.resource('dynamodb') tableName = os.environ['DATABASE'] table = dynamodb.Table(tableName) # Get stock data stock = yf.Ticker('^GSPC') stock_data_weekly = stock.history(period="5y", interval="5d") stock_data_daily = stock.history(period="2y", interval="1d") # Calculate impulse system weekly macd_hist = MACD(stock_data_weekly["Close"], fillna=True).macd_diff() ema = EMAIndicator( stock_data_weekly["Close"], n=13, fillna=True).ema_indicator() shouldBeGreen = ema.iloc[-1] > ema.iloc[-2] and macd_hist.iloc[-1] > macd_hist.iloc[-2] shouldBeRed = ema.iloc[-1] < ema.iloc[-2] and macd_hist.iloc[-1] < macd_hist.iloc[-2] colorWeekly = 'green' if shouldBeGreen else 'red' if shouldBeRed else 'blue' # Calculate impulse system daily macd_hist = MACD(stock_data_daily["Close"], fillna=True).macd_diff() ema = EMAIndicator( stock_data_daily["Close"], n=13, fillna=True).ema_indicator() shouldBeGreen = ema.iloc[-1] > ema.iloc[-2] and macd_hist.iloc[-1] > macd_hist.iloc[-2] shouldBeRed = ema.iloc[-1] < ema.iloc[-2] and macd_hist.iloc[-1] < macd_hist.iloc[-2] colorDaily = 'green' if shouldBeGreen else 'red' if shouldBeRed else 'blue' # Caculate ForceIndex 13 days indicator_fi = ForceIndexIndicator( stock_data_daily["Close"], stock_data_daily["Volume"], 13, fillna=True).force_index() lastForceIndexValue = indicator_fi.iloc[-1] lastFIDecimal = Decimal(lastForceIndexValue) lastFI = round(lastFIDecimal, 0) lastCloseData = stock_data_daily.iloc[-1]["Close"] lastCloseDecimal = Decimal(lastCloseData) lastClose = round(lastCloseDecimal, 2) # daily timestamp date = datetime.utcnow() future = date + timedelta(days=14) expiryDate = round(future.timestamp() * 1000) dateString = date.strftime("%Y-%m-%d") id = str(uuid.uuid4()) entry = { 'symbol': '^GSPC', 'id': id, 'date': dateString, 'ttl': expiryDate, 'weeklyImpulse': colorWeekly, 'dailyImpulse': colorDaily, 'forceIndex13': lastFI, 'lastClose': lastClose, } table.put_item(Item=entry) return entry
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