def BBands(close, window, deviation_1, deviation_2): # Getting values of Bollinger Bands and SMA from the `ta` module BBD1 = BollingerBands(close=close, window=int(window), window_dev=deviation_1, fillna=False) BBD2 = BollingerBands(close=close, window=int(window), window_dev=deviation_2, fillna=False) SMA = sma_indicator(close=close, window=int(window), fillna=False) BB_Upper_1 = BBD1.bollinger_hband().dropna() BB_Lower_1 = BBD1.bollinger_lband().dropna() BB_Upper_2 = BBD2.bollinger_hband().dropna() BB_Lower_2 = BBD2.bollinger_lband().dropna() # Creating DataFrame df = pd.DataFrame() # Adding all the required columns to the DataFrame df['Close'] = close.dropna() df['Upper_2'] = BB_Upper_2 df['Upper_1'] = BB_Upper_1 df['SMA'] = SMA df['Lower_1'] = BB_Lower_1 df['Lower_2'] = BB_Lower_2 df['Positions'] = get_signal(df) return df['Close'], df['Positions']
def analyze(self): bollinger_bands = BollingerBands(self.df.close, ) self.df["bb_h2"] = bollinger_bands.bollinger_hband() self.df["bb_l2"] = bollinger_bands.bollinger_lband() bollinger_bands2 = BollingerBands(self.df.close, ndev=1) self.df["bb_h1"] = bollinger_bands2.bollinger_hband() self.df["bb_l1"] = bollinger_bands2.bollinger_lband() self.df[f"buy_signal"] = (is_crossover(self.df.close, self.df.bb_h1)) self.df[f"sell_signal"] = (is_crossover(self.df.bb_l1, self.df.close))
def AddIndicators(df): # Add Simple Moving Average (SMA) indicators df["sma7"] = SMAIndicator(close=df["Close"], window=7, fillna=True).sma_indicator() df["sma25"] = SMAIndicator(close=df["Close"], window=25, fillna=True).sma_indicator() df["sma99"] = SMAIndicator(close=df["Close"], window=99, fillna=True).sma_indicator() # Add Bollinger Bands indicator indicator_bb = BollingerBands(close=df["Close"], window=20, window_dev=2) df['bb_bbm'] = indicator_bb.bollinger_mavg() df['bb_bbh'] = indicator_bb.bollinger_hband() df['bb_bbl'] = indicator_bb.bollinger_lband() # Add Parabolic Stop and Reverse (Parabolic SAR) indicator indicator_psar = PSARIndicator(high=df["High"], low=df["Low"], close=df["Close"], step=0.02, max_step=2, fillna=True) df['psar'] = indicator_psar.psar() # Add Moving Average Convergence Divergence (MACD) indicator df["MACD"] = macd(close=df["Close"], window_slow=26, window_fast=12, fillna=True) # mazas # Add Relative Strength Index (RSI) indicator df["RSI"] = rsi(close=df["Close"], window=14, fillna=True) # mazas return df
def add_volatility_indicators(data: pd.DataFrame) -> pd.DataFrame: """Adds the volatility 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. """ bb = BollingerBands(data['close']) data.loc[:, 'bollinger_hband'] = bb.bollinger_hband() data.loc[:, 'bollinger_hband_indicator'] = bb.bollinger_hband_indicator() data.loc[:, 'bollinger_lband'] = bb.bollinger_lband() data.loc[:, 'bollinger_lband_indicator'] = bb.bollinger_lband_indicator() data.loc[:, 'bollinger_mavg'] = bb.bollinger_mavg() data.loc[:, 'bollinger_pband'] = bb.bollinger_pband() data.loc[:, 'bollinger_wband'] = bb.bollinger_wband() return data
def get_signal(self, input_df, ticker, run_id): df = input_df.copy() indicator_bb = BollingerBands( close=df["Close"], window=self.indicator["window"], window_dev=self.indicator["window_dev"], fillna=self.indicator["fillna"], ) # Add Bollinger Bands features df["bb_bbm"] = indicator_bb.bollinger_mavg() df["bb_bbh"] = indicator_bb.bollinger_hband() df["bb_bbl"] = indicator_bb.bollinger_lband() df["bb_bbhi"] = indicator_bb.bollinger_hband_indicator() df["bb_bbli"] = indicator_bb.bollinger_lband_indicator() df["bb_bbp"] = indicator_bb.bollinger_pband() row = df.iloc[-1] if row.bb_bbhi.item(): sell_signal = { "ticker": ticker, "datetime": row.Date, "indicator": self.name, "param": self.param, "reason": "High BollingerBand percentage - currently at {}%".format( int(row.bb_bbp.item() * 100.0)), "image": self.draw_image(df, ticker, run_id), } else: sell_signal = None if row.bb_bbli.item(): buy_signal = { "ticker": ticker, "datetime": row.Date, "indicator": self.name, "param": self.param, "reason": "Low BollingerBand percentage - currently at {}%".format( int(row.bb_bbp.item() * 100.0)), "image": self.draw_image(df, ticker, run_id), } else: buy_signal = None return buy_signal, sell_signal
def add_volatility_ta(df: pd.DataFrame, high: str, low: str, close: str, fillna: bool = False, colprefix: str = "") -> pd.DataFrame: """Add volatility 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. """ # Average True Range df[f'{colprefix}volatility_atr'] = AverageTrueRange( close=df[close], high=df[high], low=df[low], n=10, fillna=fillna).average_true_range() # Bollinger Bands indicator_bb = BollingerBands(close=df[close], n=20, ndev=2, fillna=fillna) df[f'{colprefix}volatility_bbm'] = indicator_bb.bollinger_mavg() df[f'{colprefix}volatility_bbh'] = indicator_bb.bollinger_hband() df[f'{colprefix}volatility_bbl'] = indicator_bb.bollinger_lband() df[f'{colprefix}volatility_bbw'] = indicator_bb.bollinger_wband() df[f'{colprefix}volatility_bbhi'] = indicator_bb.bollinger_hband_indicator( ) df[f'{colprefix}volatility_bbli'] = indicator_bb.bollinger_lband_indicator( ) # Keltner Channel indicator_kc = KeltnerChannel(close=df[close], high=df[high], low=df[low], n=10, fillna=fillna) df[f'{colprefix}volatility_kcc'] = indicator_kc.keltner_channel_central() df[f'{colprefix}volatility_kch'] = indicator_kc.keltner_channel_hband() df[f'{colprefix}volatility_kcl'] = indicator_kc.keltner_channel_lband() df[f'{colprefix}volatility_kchi'] = indicator_kc.keltner_channel_hband_indicator( ) df[f'{colprefix}volatility_kcli'] = indicator_kc.keltner_channel_lband_indicator( ) # Donchian Channel indicator_dc = DonchianChannel(close=df[close], n=20, fillna=fillna) df[f'{colprefix}volatility_dcl'] = indicator_dc.donchian_channel_lband() df[f'{colprefix}volatility_dch'] = indicator_dc.donchian_channel_hband() df[f'{colprefix}volatility_dchi'] = indicator_dc.donchian_channel_hband_indicator( ) df[f'{colprefix}volatility_dcli'] = indicator_dc.donchian_channel_lband_indicator( ) return df
def _run(self): # Bollinger Bands bb_indicator = BollingerBands(close=self._close, n=self._chan_period, ndev=self._bol_band_std_dev, fillna=self._fillna) self._bb_hband = bb_indicator.bollinger_hband() self._bb_lband = bb_indicator.bollinger_lband() # Keltner Channel kb_indicator = KeltnerChannel(high=self._high, low=self._low, close=self._close, n=self._chan_period, n_atr=self._kelt_std_dev, fillna=self._fillna, ov=False) self._kb_hband = kb_indicator.keltner_channel_hband() self._kb_lband = kb_indicator.keltner_channel_lband() # Momentum Oscillator smo_indicator = SMOIndicator(high=self._high, low=self._low, close=self._close, n=self._mom_period, fillna=self._fillna) self._oscillator = smo_indicator.smo() # Bar and Signal Colors self._squeeze = bb_indicator.bollinger_wband( ) - kb_indicator.keltner_channel_wband() self._squeeze = self._squeeze.ge(0).astype(int)
def AddIndicators(df): # Add Bollinger Bands indicator indicator_bb = BollingerBands(close=df["Close"], window=20, window_dev=2) df['bb_bbm'] = indicator_bb.bollinger_mavg() df['bb_bbh'] = indicator_bb.bollinger_hband() df['bb_bbl'] = indicator_bb.bollinger_lband() return df
class TestBollingerBands(unittest.TestCase): """ https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_bands """ _filename = 'ta/tests/data/cs-bbands.csv' def setUp(self): self._df = pd.read_csv(self._filename, sep=',') self._indicator = BollingerBands(close=self._df['Close'], n=20, ndev=2, fillna=False) def tearDown(self): del (self._df) def test_mavg(self): target = 'MiddleBand' result = self._indicator.bollinger_mavg() pd.testing.assert_series_equal(self._df[target].tail(), result.tail(), check_names=False) def test_hband(self): target = 'HighBand' result = self._indicator.bollinger_hband() pd.testing.assert_series_equal(self._df[target].tail(), result.tail(), check_names=False) def test_lband(self): target = 'LowBand' result = self._indicator.bollinger_lband() pd.testing.assert_series_equal(self._df[target].tail(), result.tail(), check_names=False) def test_wband(self): target = 'WidthBand' result = self._indicator.bollinger_wband() pd.testing.assert_series_equal(self._df[target].tail(), result.tail(), check_names=False) def test_hband_indicator(self): target = 'CrossUp' result = self._indicator.bollinger_hband_indicator() pd.testing.assert_series_equal(self._df[target].tail(), result.tail(), check_names=False) def test_lband_indicator(self): target = 'CrossDown' result = self._indicator.bollinger_lband_indicator() pd.testing.assert_series_equal(self._df[target].tail(), result.tail(), check_names=False)
def bollinger_bands(df): indicator_bb = BollingerBands(close=df["Close"]) df['bb_bbh'] = indicator_bb.bollinger_hband() df['bb_bbl'] = indicator_bb.bollinger_lband() df['bb_avg'] = indicator_bb.bollinger_mavg() df['bb_bbh_ind'] = indicator_bb.bollinger_hband_indicator() df['bb_bbl_ind'] = indicator_bb.bollinger_lband_indicator() df['bb_pband'] = indicator_bb.bollinger_pband() df['bb_wband'] = indicator_bb.bollinger_wband()
def techIndicator(df1): #OFtrader # Initialize Bollinger Bands Indicator from ta.volatility import BollingerBands indicator_bb = BollingerBands(close=df1["Close"], window=10, window_dev=2) # Add Bollinger Bands features df1['bb_bbh'] = indicator_bb.bollinger_hband() df1['bb_bbl'] = indicator_bb.bollinger_lband() # Initialize Bollinger Bands Indicator from ta.trend import PSARIndicator indicator_SAR = PSARIndicator(high=df1["high"], low=df1["low"], close=df1["Close"]) # Add Bollinger Bands features df1['sar_high'] = indicator_SAR.psar_up() df1['sar_low'] = indicator_SAR.psar_down() from ta.trend import EMAIndicator indicator_EMA = EMAIndicator(close=df1["Close"], window=7) df1['Media7'] = indicator_EMA.ema_indicator() df1['sar_low'] = df1['sar_low'].fillna(0) df1['sar_high'] = df1['sar_high'].fillna(0) df1['Distancia_M7'] = df1['Close'] / df1['Media7'] df1['Distancia_BBH'] = df1['Close'] / df1['bb_bbh'] df1['Distancia_BBL'] = df1['Close'] / df1['bb_bbl'] df1['Distancia_SAR'] = np.where(df1['sar_high'] > 0, df1['Close'] / df1['sar_high'], df1['sar_low'] / df1['Close']) df1['posicao_sar'] = np.where(df1['sar_high'] > 0, '1', '0') corte = 3 df1["Distancia_M7"] = pd.qcut(df1["Distancia_M7"], corte, labels=False) df1["Distancia_BBH"] = pd.qcut(df1["Distancia_BBH"], corte, labels=False) df1["Distancia_BBL"] = pd.qcut(df1["Distancia_BBL"], 15, labels=False) df1["Distancia_SAR"] = pd.qcut(df1["Distancia_SAR"], 15, labels=False) # # Padrão Bom com M7: 3 - BBH: 3 - BBL: 15 - DSAR: 15 df1 = df1.drop(["sar_high", "sar_low", "bb_bbh", "bb_bbl", "Media7"], axis=1) #df1.tail(50) return df1
def bollinger_bands(data, days=20, std=2, price="Close"): df = data # Initialize Bollinger Bands Indicator indicator_bb = BollingerBands(close=df[price], window=days, window_dev=std) # Add Bollinger Bands features df["bb_ma"] = indicator_bb.bollinger_mavg() df["bb_high"] = indicator_bb.bollinger_hband() df["bb_low"] = indicator_bb.bollinger_lband() # 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() return df
def analysis(df, ma_f, ma_s, period): df["ema_f"] = ta.ema(high=df.high, low=df.low, close=df.close, length=ma_f) df["ema_s"] = ta.ema(high=df.high, low=df.low, close=df.close, length=ma_s) df.fillna(0, inplace=True) df['s'] = (df['ema_s'] - df['ema_s'].shift(1)) >= 0 df['f'] = (df['ema_f'] - df['ema_f'].shift(1)) >= 0 df['buy_ema'] = df['ema_f'] > df['ema_s'] df['sell_ema'] = df['ema_f'] <= df['ema_s'] df['buy_change'] = (df['buy_ema'] != df['buy_ema'].shift(1)) & df['buy_ema'] df['sell_change'] = (df['sell_ema'] != df['sell_ema'].shift(1)) & df['sell_ema'] # df["RSI"] = ta.rsi(high=df.high, low=df.low, close=df.close, length=period) # df['RSIs'] = (df['RSI'] - df['RSI'].shift(1)) >= 0 # df['RSI_ups'] = df.groupby( # (df['RSIs'] != df['RSIs'].shift(1)).cumsum()).cumcount() + 1 # df['adx'] = ta.adx(high=df.high, low=df.low, close=df.close, length=period)['ADX_%s' % period] # df['adx_s'] = (df['adx'] - df['adx'].shift(1)) >= 0 # df['adx_ups'] = df.groupby( # (df['adx_s'] != df['adx_s'].shift(1)).cumsum()).cumcount() + 1 # df['ATR'] = df.ta.atr() indicator_bb = BollingerBands(close=df.close, window=10, window_dev=1.8) df['bb_bbm'] = indicator_bb.bollinger_mavg() df['b_m'] = (df['bb_bbm'] - df['bb_bbm'].shift(1)) >= 0 df['bb_bbh'] = indicator_bb.bollinger_hband() df['bb_bbl'] = indicator_bb.bollinger_lband() df['bb_bbhi'] = indicator_bb.bollinger_hband_indicator() df['bb_bbli'] = indicator_bb.bollinger_lband_indicator() df['pvt'] = ta.pvt(close=df.close, volume=df.volume) df['pvt_t'] = (df['pvt'] - df['pvt'].shift(1)) >= 0 df['close_variation'] = df['close'] - df['close'].shift(1) # # df = ema(df, ma_f, ma_s) df = rsi(df, period) df = momentum(df) df['trend'] = df['momentum_s'] & df['RSIs'] return df
def get_bollinger_bands(config, crypto): close_prices = crypto.prices dataframe = crypto.technical_indicators window = 20 indicator_bb = BollingerBands(close=close_prices, window=window, window_dev=2) dataframe['Bollinger_Bands_Middle'] = indicator_bb.bollinger_mavg() dataframe['Bollinger_Bands_Upper'] = indicator_bb.bollinger_hband() dataframe['Bollinger_Bands_Lower'] = indicator_bb.bollinger_lband() generate_buy_sell_signals( lambda x, signal: signal['Close'].values[x] < signal[ 'Bollinger_Bands_Lower'].values[x], lambda x, signal: signal[ 'Close'].values[x] > signal['Bollinger_Bands_Upper'].values[x], dataframe, 'Bollinger_Bands') return dataframe
def transform_one(self, entity_id, df: pd.DataFrame) -> pd.DataFrame: indicator_bb = BollingerBands(close=df["close"], window=20, window_dev=2) # Add Bollinger Bands features df["bb_bbm"] = indicator_bb.bollinger_mavg() df["bb_bbh"] = indicator_bb.bollinger_hband() df["bb_bbl"] = indicator_bb.bollinger_lband() # 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() # Add Width Size Bollinger Bands df["bb_bbw"] = indicator_bb.bollinger_wband() # Add Percentage Bollinger Bands df["bb_bbp"] = indicator_bb.bollinger_pband() return df
def get_signal(self, stock, minute_price): bb_bars = self.wb.get_bars(stock, interval=self.time_period, extendTrading=0, count=20) bb = BollingerBands(close=bb_bars['close'], fillna=True) # set series objects to indicators calculations bb_upper = bb.bollinger_hband() bb_lower = bb.bollinger_lband() # get value for latest interval current_bb_upper = bb_upper[19] current_bb_lower = bb_lower[19] difference = current_bb_upper - current_bb_lower threshold_price = difference * self.threshold lower_threshold = current_bb_lower + threshold_price upper_threshold = current_bb_upper - threshold_price if minute_price <= lower_threshold: return 1 elif minute_price >= upper_threshold: return -1 else: return 0
def analyze(self): bollinger_bands = BollingerBands(self.df.close, ) self.df["bb_h2"] = bollinger_bands.bollinger_hband() self.df["bb_l2"] = bollinger_bands.bollinger_lband() self.df[f"buy_signal"] = (self.df.bb_h2 - self.df.bb_l2 <= 200)
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() scaled_values = y_scaler.fit_transform( np.array(stock.iloc[:, 4]).reshape(-1, 1)) stock.iloc[:, 4] = scaled_values
def _bollinger_bands(self, df, close): bb = BollingerBands(close=close) df['bb_bbm'] = bb.bollinger_mavg() df['bb_bbh'] = bb.bollinger_hband() df['bb_bbl'] = bb.bollinger_lband()
def GetPriceDataFromExchangeFinnHub(event, context): retVal = {} retVal["data"] = [] # For debugging the input, write the EVENT to CloudWatch logs print(json.dumps(event)) # Data is sent to Lambda via a HTTPS POST call. We want to get to the payload send by Snowflake event_body = event["body"] payload = json.loads(event_body) for row in payload["data"]: sflkRowRef = row[ 0] # This is how Snowflake keeps track of data as it gets returned symbol = row[ 1] # The data passed in from Snowflake that the input row contains. fromDate = row[2] toDate = row[3] # Will return URL without token to Snowflake for tracking URL = f'https://finnhub.io/api/v1/stock/candle?symbol={symbol}&resolution=D&from={fromDate}&to={toDate}' # Add our FinnHubAPI Key to the end of the URL. # This is in a new variable which will not be returned to Snowflake URLWithToken = f'{URL}&token={FinnHubAPI.TOKEN}' # GET data from the API httpData = requests.get(url=URLWithToken).json() # Convert to Pandas DataFrame df = pd.DataFrame(httpData) # Add the column names print("Adding column names") df.columns = [ "Close", "High", "Low", "Open", "Status", "OpenTime", "Volume" ] # Set DateTime columns to correct type df['OpenTime'] = pd.to_datetime(df['OpenTime'], unit='ms') df['Open'] = df['Open'].astype(float) df['High'] = df['High'].astype(float) df['Low'] = df['Low'].astype(float) df['Close'] = df['Close'].astype(float) df['Volume'] = df['Volume'].astype(float) # Clean NaN values print("Cleaning NA values") df = dropna(df) # Calculate the Bollinger Bands indicator indicator_bb = BollingerBands(close=df["Close"], n=20, ndev=2) df['bb_bbm'] = indicator_bb.bollinger_mavg() df['bb_bbh'] = indicator_bb.bollinger_hband() df['bb_bbl'] = indicator_bb.bollinger_lband() df['bb_bbhi'] = indicator_bb.bollinger_hband_indicator() df['bb_bbli'] = indicator_bb.bollinger_lband_indicator() df['bb_bbw'] = indicator_bb.bollinger_wband() df['bb_bbp'] = indicator_bb.bollinger_pband() print("converting OHLC pandas to JSON. This does it as a string") buffer = df.to_json(orient="records") print("Interpret the JSON string into a dictionary for output") jsonResponse = json.loads(buffer) # Prepare the output response response = {} response["url"] = URL response["response"] = jsonResponse retVal["data"].append([sflkRowRef, response]) # For debugging the output, write the RETurn VALue to CloudWatch logs # print(json.dumps(retVal)) return retVal
def PlotBB(stock_ticker, close, window, deviation_1, deviation_2): def GetSignal(data): buy_signal = [] # buy list sell_signal = [] # sell list for i in range(len(data['Close'])): # If the closing price is above Upper_2 band. [SELL] if data['Close'][i] > data['Upper_2'][i]: buy_signal.append(np.nan) sell_signal.append(data['Close'][i]) # If closing price is below lower_2 band. [BUY] elif data['Close'][i] < data['Lower_2'][i]: sell_signal.append(np.nan) buy_signal.append(data['Close'][i]) # The first few values for Bollinger Bands will be NaN as the SMA hasn't been calculated for the given time period. else: buy_signal.append(np.nan) sell_signal.append(np.nan) return buy_signal, sell_signal # Getting values of Bollinger Bands and SMA from the `ta` module BBD1 = BollingerBands(close=close, window=int(window), window_dev=deviation_1, fillna=False) BBD2 = BollingerBands(close=close, window=int(window), window_dev=deviation_2, fillna=False) SMA = sma_indicator(close=close, window=int(window), fillna=False) BB_Upper_1 = BBD1.bollinger_hband().dropna() BB_Lower_1 = BBD1.bollinger_lband().dropna() BB_Upper_2 = BBD2.bollinger_hband().dropna() BB_Lower_2 = BBD2.bollinger_lband().dropna() # Creating DataFrame df = pd.DataFrame() # Adding all the required columns to the DataFrame df['Close'] = close.dropna() df['Upper_2'] = BB_Upper_2 df['Upper_1'] = BB_Upper_1 df['SMA'] = SMA df['Lower_1'] = BB_Lower_1 df['Lower_2'] = BB_Lower_2 df['Buy'], df['Sell'] = GetSignal(df) # Initialising matplotlib fig = plt.figure(figsize=(7, 6)) ax = fig.add_subplot(1, 1, 1) x_axis = df.index # Plotting Bollinger Bands, Closing price and SMA ax.fill_between(x_axis, df['Upper_2'], df['Lower_2'], color='#ffe59e') ax.plot(x_axis, df['Close'], color='#a8ff26', lw=3, label='Close Price') ax.plot(x_axis, df['SMA'], color='#f7b21b', lw=3, label=f'SMA: {window} periods') len_list = df[df['Sell'].notna()].index.tolist() # Getting SELL data points for k, j in zip(range(0, len(len_list)), df['Sell'].dropna().tolist()): date = df[df['Sell'].notna()].index[k] date = date.to_pydatetime() x_axis = date y_axis = j # Annotating the chart at sell points ax.annotate(text='S', xy=(x_axis, y_axis), arrowprops=dict(facecolor='red', shrink=0.05)) # Getting BUY data points for k, j in zip(range(0, len(len_list)), df['Buy'].dropna().tolist()): date = df[df['Buy'].notna()].index[k] date = date.to_pydatetime() x_axis = date y_axis = j # Annotating the chart at buy points ax.annotate(text='B', xy=(x_axis, y_axis), arrowprops=dict(facecolor='green', shrink=0.05)) plt.ylabel('Price', fontsize=15) plt.xlabel('Date', fontsize=15) plt.title(f'Bollinger Bands {stock_ticker}', fontsize=20) plt.legend() plt.grid() try: plt.savefig(f'image/{stock_ticker}/BB_{stock_ticker}.png', bbox_inches='tight') except: directory = f'image/{stock_ticker}' for f in os.listdir(stock_ticker): os.remove(os.path.join(directory, f)) plt.savefig(f'image/{stock_ticker}/BB_{stock_ticker}.png', bbox_inches='tight')
def add_volatility_ta( df: pd.DataFrame, high: str, low: str, close: str, fillna: bool = False, colprefix: str = "", vectorized: bool = False, ) -> pd.DataFrame: """Add volatility 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. """ # Bollinger Bands indicator_bb = BollingerBands(close=df[close], window=20, window_dev=2, fillna=fillna) df[f"{colprefix}volatility_bbm"] = indicator_bb.bollinger_mavg() df[f"{colprefix}volatility_bbh"] = indicator_bb.bollinger_hband() df[f"{colprefix}volatility_bbl"] = indicator_bb.bollinger_lband() df[f"{colprefix}volatility_bbw"] = indicator_bb.bollinger_wband() df[f"{colprefix}volatility_bbp"] = indicator_bb.bollinger_pband() df[f"{colprefix}volatility_bbhi"] = indicator_bb.bollinger_hband_indicator( ) df[f"{colprefix}volatility_bbli"] = indicator_bb.bollinger_lband_indicator( ) # Keltner Channel indicator_kc = KeltnerChannel(close=df[close], high=df[high], low=df[low], window=10, fillna=fillna) df[f"{colprefix}volatility_kcc"] = indicator_kc.keltner_channel_mband() df[f"{colprefix}volatility_kch"] = indicator_kc.keltner_channel_hband() df[f"{colprefix}volatility_kcl"] = indicator_kc.keltner_channel_lband() df[f"{colprefix}volatility_kcw"] = indicator_kc.keltner_channel_wband() df[f"{colprefix}volatility_kcp"] = indicator_kc.keltner_channel_pband() df[f"{colprefix}volatility_kchi"] = indicator_kc.keltner_channel_hband_indicator( ) df[f"{colprefix}volatility_kcli"] = indicator_kc.keltner_channel_lband_indicator( ) # Donchian Channel indicator_dc = DonchianChannel(high=df[high], low=df[low], close=df[close], window=20, offset=0, fillna=fillna) df[f"{colprefix}volatility_dcl"] = indicator_dc.donchian_channel_lband() df[f"{colprefix}volatility_dch"] = indicator_dc.donchian_channel_hband() df[f"{colprefix}volatility_dcm"] = indicator_dc.donchian_channel_mband() df[f"{colprefix}volatility_dcw"] = indicator_dc.donchian_channel_wband() df[f"{colprefix}volatility_dcp"] = indicator_dc.donchian_channel_pband() if not vectorized: # Average True Range df[f"{colprefix}volatility_atr"] = AverageTrueRange( close=df[close], high=df[high], low=df[low], window=10, fillna=fillna).average_true_range() # Ulcer Index df[f"{colprefix}volatility_ui"] = UlcerIndex( close=df[close], window=14, fillna=fillna).ulcer_index() return df
(start_date, end_date)) else: st.sidebar.error('Error: End date must fall after start date.') ############## # 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)
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
row = 0 column = 0 # Loop over the tickers for ticker in stock_data_biotech.columns: # Initalise the DataFrame data_plot = pd.DataFrame(stock_data_biotech[ticker]) # Initialize Bollinger Bands Indicator indicator_bb = BollingerBands(close=stock_data_biotech[ticker], window=20, window_dev=2) # Add Bollinger Bands features data_plot['bb_bbm'] = indicator_bb.bollinger_mavg() data_plot['bb_bbh'] = indicator_bb.bollinger_hband() data_plot['bb_bbl'] = indicator_bb.bollinger_lband() # Create the plot axis[row, column].plot(data_plot) axis[row, column].set_title(health_etfs_in_biotech[ticker]['long_name'], fontsize=6) axis[row, column].set_xticks([]) axis[row, column].set_yticks([]) # Count a column further column += 1 # If the column reaches the max, add another row if column == 3: row += 1
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}")
features_considered = [ 'Close', 'Volume', 'MA_short', 'MA_long', 'Wilders_EMA', 'bb_bbm', 'bb_bbh', 'bb_bbl', 'bb_bbhi', 'bb_bbli' ] # features_considered = ['Close', 'MA_short', 'MA_long', 'Wilders_EMA'] # Initialize Bollinger Bands Indicator e = EquityData('data/SPY.csv', 'SPY') indicator_bb = BollingerBands(close=e.close(), n=20, ndev=2) e.data['MA_short'] = moving_average(e, window=history_size) e.data['MA_long'] = moving_average(e, window=5) e.data['Wilders_EMA'] = e.close().ewm(alpha=1 / history_size, adjust=False).mean() # Add Bollinger Bands features e.data['bb_bbm'] = indicator_bb.bollinger_mavg() e.data['bb_bbh'] = indicator_bb.bollinger_hband() e.data['bb_bbl'] = indicator_bb.bollinger_lband() # Add Bollinger Band high indicator e.data['bb_bbhi'] = indicator_bb.bollinger_hband_indicator() # Add Bollinger Band low indicator e.data['bb_bbli'] = indicator_bb.bollinger_lband_indicator() e.data = e.data[21:] EVALUATION_INTERVAL = int(e.data.shape[0] / BATCH_SIZE) * 2 features = e.data[features_considered] assert (list(features)[0] == 'Close') features.index = e.date() # features.plot(subplots=True) # plt.show()
def app(): ticker_list = pd.read_csv( 'https://raw.githubusercontent.com/kennethmina24/stockapp/master/List%20of%20Names%20(Stocks)' ) #Heading Info tickerSymbol = st.sidebar.selectbox('Stock ticker', ticker_list) # Select ticker symbol tickerData = yf.Ticker(tickerSymbol) # Get ticker data #Ticker information string_logo = '<img src=%s>' % tickerData.info['logo_url'] st.markdown(string_logo, unsafe_allow_html=True) string_name = tickerData.info['longName'] st.header('**%s**' % string_name) string_summary = tickerData.info['longBusinessSummary'] st.info(string_summary) # Function to display values and their name ######################### #def display_summary(tickerSymbol): # info = get_info(tickerSymbol) #info_names = ["Name: ", "Close Price: ", "Open Price: ", "52-Week Range: ", "Dividend Rate & Yield: ", \ #"Market Cap: ", "PE Ratio: ", "EPS: "] # print out info in sidebar #for name,infoValue in zip(info_names, info): # row = \ # f"""<div> # <span style='float: left;'><b>{name}</b></span> # <span style='float: right;'> {infoValue}</span> # </div> ########### # sidebar # ########### import datetime today = datetime.date.today() before = today - datetime.timedelta(days=1825) start_date = st.sidebar.date_input('Start date', before) end_date = st.sidebar.date_input('End date', today) if start_date < end_date: st.sidebar.success('Start date: `%s`\n\nEnd date:`%s`' % (start_date, end_date)) else: st.sidebar.error('Error: End date must fall after start date.') ############### #Download Data# ############### df = yf.download(tickerSymbol, start=start_date, end=end_date, progress=False) #Indicators# # Bollinger Bands# indicator_bb = BollingerBands(df['Low']) bb = df bb['bb_h'] = indicator_bb.bollinger_hband() bb['bb_l'] = indicator_bb.bollinger_lband() bb = bb[['Low', 'bb_h', 'bb_l']] bb = bb.tail(5) # Resistence Strength Indicator rsi = RSIIndicator(df['Low']).rsi() # Plot RSI st.header('Stock RSI ') st.write( "Overbought(Selling Pressure) above 70 /// Oversold(Buying Pressure) below 30" ) st.dataframe(rsi.tail(3)) ################### # Set up main app # ################### # Data of recent days # Plot the prices and the bolinger bands st.write('Recent Data') st.dataframe(bb) progress_bar = st.progress(0)