Пример #1
0
def add_volatility_ta(df: pd.DataFrame,
                      high: str,
                      low: str,
                      close: str,
                      fillna: bool = False,
                      colprefix: str = ""):
    """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_bbh'] = indicator_bb.bollinger_hband()
    df[f'{colprefix}volatility_bbl'] = indicator_bb.bollinger_lband()
    df[f'{colprefix}volatility_bbm'] = indicator_bb.bollinger_mavg()
    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
Пример #2
0
def run(ticker):

    signal_is_sent = check_signal_is_sent(ticker)

    if (not signal_is_sent):

        tf_1hour = get_candles(ticker)
        rsi_1hour = RSIIndicator(close=tf_1hour.close).rsi()
        bolinger_1hour = BollingerBands(close=tf_1hour.close)

        condition_short = rsi_1min[-1] >= 80 and rsi_5min[-1] >= 80
        condition_long = rsi_1min[-1] <= 20 and rsi_5min[-1] <= 20

        # Trade size depends on STOP_LOSS_THRESH. MT5 limitations.
        STOP_LOSS_THRESH = (
            open_close_hour_dif_mean[ticker]
        )
        trade_size = calculate_trade_size(
            STOP_LOSS_THRESH, tf_1min.close[-1]
        ) / ticker_info[ticker]['min_lot']
        trade_size = round(trade_size)

        cur_time = str(datetime.now().time())
        if condition_short:
            sl = round(
                tf_1min.close[-1] + STOP_LOSS_THRESH * tf_1min.close[-1],
                ticker_info[ticker]['price_digits']
            )
            tp = round(
                tf_1min.close[-1] - STOP_LOSS_THRESH * tf_1min.close[-1],
                ticker_info[ticker]['price_digits']
            )
            print('\n', cur_time, ticker, ': SHORT', str(trade_size), tf_1min.close[-1], sl, tp, '\n')
            messsage = ' '.join(
                [cur_time, ticker, 'SHORT', str(trade_size), str(sl), str(tp)]
            )
            send_message(messsage)
            set_signal_is_sent_flag(ticker)
        elif condition_long:
            sl = round(
                tf_1min.close[-1] - STOP_LOSS_THRESH * tf_1min.close[-1],
                ticker_info[ticker]['price_digits']
            )
            tp = round(
                tf_1min.close[-1] + STOP_LOSS_THRESH * tf_1min.close[-1],
                ticker_info[ticker]['price_digits']
            )
            print('\n', cur_time, ticker, ': LONG', str(trade_size), tf_1min.close[-1], sl, tp, '\n')
            messsage = ' '.join(
                [cur_time, ticker, 'LONG', str(trade_size), str(sl), str(tp)]
            )
            send_message(messsage)
            set_signal_is_sent_flag(ticker)
Пример #3
0
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
Пример #4
0
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)
Пример #5
0
    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
Пример #6
0
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
Пример #7
0
    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
Пример #8
0
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
Пример #9
0
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
Пример #10
0
 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()
Пример #11
0
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from ta.volatility import BollingerBands
from ta.trend import MACD
from ta.momentum import RSIIndicator
from keras.models import Sequential
from keras.layers import Conv1D, MaxPool1D, Bidirectional, LSTM, Dropout, TimeDistributed
from keras.layers import Dense, GlobalAveragePooling2D
from ta.trend import IchimokuIndicator
from sklearn.linear_model import LinearRegression
from ta import add_all_ta_features
from ta.utils import dropna
import matplotlib.pyplot as plt
filename = 'AAPL'
stock = pd.read_csv('Data/' + filename + '.csv')
indicator_bb = BollingerBands(close=stock["Close"], n=20, ndev=2)
macd = MACD(close=stock["Close"])
rsi = RSIIndicator(close=stock["Close"])
ichi = IchimokuIndicator(high=stock["High"], low=stock["Low"])
stock['macd'] = macd.macd()
stock['rsi'] = rsi.rsi()
stock['bb_bbm'] = indicator_bb.bollinger_mavg()
stock['bb_bbh'] = indicator_bb.bollinger_hband()
stock['bb_bbl'] = indicator_bb.bollinger_lband()
stock['ichi_a'] = ichi.ichimoku_a()
stock['ichi_b'] = ichi.ichimoku_b()
stock['ichi_base'] = ichi.ichimoku_base_line()
stock['ichi_conv'] = ichi.ichimoku_conversion_line()
stock = stock.fillna(0)
print(stock)
scaler = preprocessing.MinMaxScaler()
Пример #12
0
 def setUpClass(cls):
     cls._df = pd.read_csv(cls._filename, sep=',')
     cls._params = dict(close=cls._df['Close'], n=20, ndev=2, fillna=False)
     cls._indicator = BollingerBands(**cls._params)
Пример #13
0
    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')
Пример #14
0
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.')

##############
# 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')
Пример #15
0
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
Пример #16
0
    # Calac data
    last_entry_df = dao.get_all_stocks_prices_max_entry_date(exchange)
    last_entry_dict = dict(zip(last_entry_df['equity_id'].tolist(), last_entry_df['last_entry'].tolist()))

    for idx1, row1 in equity_ref_df.iterrows():
        equity_id = row1['equity_id']
        ticker = row1['local_code']
        try:
            insert_list = list()
            # get all the prices for equity
            ticker_eod_df = eod_df[eod_df['equity_id'] == equity_id]
            ticker_eod_df = ticker_eod_df.sort_values(by=['trading_date'])
            df = dropna(ticker_eod_df)

            # Initialize Bollinger Bands Indicator
            indicator_bb = BollingerBands(close=df["adj_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()

            # EMA Indicator
            indicator_ema_200 = EMAIndicator(close=df["adj_close"], window=200)
            df['ema_200'] = indicator_ema_200.ema_indicator()
            indicator_ema_100 = EMAIndicator(close=df["adj_close"], window=100)
            df['ema_100'] = indicator_ema_100.ema_indicator()
            indicator_ema_50 = EMAIndicator(close=df["adj_close"], window=50)
            df['ema_50'] = indicator_ema_50.ema_indicator()

            # SMA Indicator
            indicator_sma_200 = SMAIndicator(close=df["adj_close"], window=200)
Пример #17
0
    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}")
Пример #18
0
    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
Пример #19
0
def features_df(stocks,
                rsi_vals=False,
                macd_vals=False,
                ppo=False,
                awesome_oscillator_val=False,
                daily_log_return=False,
                _return=False,
                change=False,
                volatility=False,
                min5=False,
                min10=False,
                min30=False,
                hband_indicator=False,
                lband_indicator=False,
                corr=False):
    """
    Calculates the momentum, RSI, moving average convergence/divergence (MACD), Percentage Price Oscillator,
    awesome oscillator indicator, daily log return column, return, change, volatility, 5-10 and 30 mins moving average,
    high band indicator, lower band indicator, correlation of the given stock dataframe.
    :param stocks: dataframe of stocks
    :param rsi_vals: Default value False. If you want the RSI column, set True
    :param macd_vals: Default value False. If you want the MACD column, set True
    :param ppo: Default value False. If you want the Percentage Price Oscillator column, set True
    :param awesome_oscillator_val: Default value False. If you want the awesome oscillator indicator column, set True
    :param daily_log_return: Default value False. If you want the daily log return column, set True
    :param _return: Default value False. If you want the return column, set True
    :param change: Default value False. If you want the change column, set True
    :param volatility: Default value False. If you want the volatility column, set True
    :param min5: Default value False. If you want the min5 column, set True
    :param min10: Default value False. If you want the min10 column, set True
    :param min30: Default value False. If you want the min30 column, set True
    :param hband_indicator: Default value False. If you want the high band indicator column, set True
    :param lband_indicator: Default value False. If you want the lower band indicator column, set True
    :param corr: Default value False. If you want the correlation column, set True
    :return: a dataframe with the different features of said stock Default value False.
                If you want the RSI column, set True
    """

    if rsi_vals is True:
        stocks['rsi_vals'] = RSIIndicator(close=stocks.Close, window=10).rsi()
    if macd_vals is True:
        stocks['macd_vals'] = macd(stocks.Close,
                                   window_slow=26,
                                   window_fast=12)
    if ppo is True:
        stocks['Ppo'] = np.array(
            PercentagePriceOscillator(stocks.Close,
                                      window_slow=26,
                                      window_fast=12).ppo())
    if awesome_oscillator_val is True:
        stocks['awesome_oscillator'] = awesome_oscillator(stocks.High,
                                                          stocks.Low,
                                                          window1=5,
                                                          window2=29)
    if daily_log_return is True:
        stocks['daily_log_return'] = daily_return(close=stocks.Close)
    if _return is True:
        stocks['Return'] = round(stocks['Close'] / stocks['Open'] - 1, 3)
    if change is True:
        stocks['Change'] = (stocks.Close - stocks.Close.shift(1)).fillna(0)
    if volatility is True:
        stocks['Volatility'] = stocks.Close.ewm(21).std()
    if min5 is True:
        stocks['min5'] = stocks.Close.rolling(5).mean()
    if min10 is True:
        stocks['min10'] = stocks.Close.rolling(10).mean()
    if min30 is True:
        stocks['min30'] = stocks.Close.rolling(30).mean()
    if hband_indicator is True:
        stocks['hband_indicator'] = BollingerBands(
            close=stocks.Close).bollinger_hband_indicator()
    if lband_indicator is True:
        stocks['lband_indicator'] = BollingerBands(
            close=stocks.Close).bollinger_lband_indicator()
    if corr is True:
        stocks['Corr'] = stocks.Close.rolling(window=10).corr(stocks['min10'])

    return stocks.iloc[-1, :]
Пример #20
0
from ta.momentum import RSIIndicator
# from ta.volume import put_call_ratio
from ta.trend import EMAIndicator
from ta.trend import SMAIndicator
from ta.trend import cci
from ta.volume import OnBalanceVolumeIndicator

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)
Пример #21
0
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
Пример #22
0
 def setUp(self):
     self._df = pd.read_csv(self._filename, sep=',')
     self._indicator = BollingerBands(close=self._df['Close'],
                                      n=20,
                                      ndev=2,
                                      fillna=False)
Пример #23
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)
Пример #24
0
                    ])

                df_bars = dropna(df_bars)
                df_bars['Open'] = pd.to_numeric(df_bars['Open'],
                                                errors='coerce')
                df_bars['Close'] = pd.to_numeric(df_bars['Close'],
                                                 errors='coerce')
                df_bars['High'] = pd.to_numeric(df_bars['High'],
                                                errors='coerce')
                df_bars['Low'] = pd.to_numeric(df_bars['Low'], errors='coerce')
                df_bars['Quote asset volume'] = pd.to_numeric(
                    df_bars['Quote asset volume'], errors='coerce')

                # Initialize Bollinger Bands Indicator
                indicator_bb = BollingerBands(close=df_bars["Close"],
                                              window=20,
                                              window_dev=2)

                # Add Bollinger Bands features
                # df_bars['bb_bbm'] = indicator_bb.bollinger_mavg()
                # df_bars['bb_bbh'] = indicator_bb.bollinger_hband()
                #df_bars['bb_bbl'] = indicator_bb.bollinger_lband()

                # Add Bollinger Band high indicator
                # df_bars['bb_bbhi'] = indicator_bb.bollinger_hband_indicator()

                # Add Bollinger Band low indicator
                # df_bars['bb_bbli'] = indicator_bb.bollinger_lband_indicator()

                # Add Width Size Bollinger Bands
                df_bars['bb_bbw_' + tf] = indicator_bb.bollinger_wband()
Пример #25
0
                                 end="2020-06-01")['Adj Close']
stock_data_biotech = stock_data_biotech.dropna(axis='columns')

# Initalise the plot and row/column variables
figure, axis = plt.subplots(4, 3)
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
Пример #26
0
bot = os.environ["telegram_token_bot"]

df = pd.read_csv('datasets/ETHUSDT-1m-sma-15.csv')

print(df)

df["EMA12"] = ta.ema(high=df.high, low=df.low, close=df.close, length=12)
df["RSI2"] = ta.rsi(high=df.high, low=df.low, close=df.close, length=14)
df['ATR2'] = df.ta.atr()
df['Momentum'] = df.ta.mom()
df['adx'] = ta.adx(high=df.high, low=df.low, close=df.close, length=14)['ADX_14']

print('---------------------')
df['pvt'] = ta.pvt(close=df.close, volume=df.volume)

indicator_bb = BollingerBands(close=df.close, window=14, window_dev=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()

macd = ta.macd(close=df.close, fast=12, slow=26, signal_indicators=True, signal=9)

df['macd_osc'] = macd['MACD_12_26_9']
df['macd_h'] = macd['MACDh_12_26_9']
df['macd_s'] = macd['MACDs_12_26_9']
df['macd_xa'] = macd['MACDh_12_26_9_XA_0']
df['macd_xb'] = macd['MACDh_12_26_9_XB_0']
df['macd_a'] = macd['MACD_12_26_9_A_0']
Пример #27
0
BUFFER_SIZE = 10000
EPOCHS = 10
CLASSIFICATION = True

step = 1
history_size = 21
target_distance = 2

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:]
Пример #28
0
    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
Пример #29
0
    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
    df['month'] = df.index.month

    df.dropna(inplace=True)
    df = df.drop(df.columns[[0, 1, 2, 4, 5]], axis=1)

    X_columns = ['price', 'kama', 'ppo', 'roc', 'macd', 'rsi', 'aroon', 'boll_mavg', 
                    'day_of_month', 'day_of_week', 'month']
]
features_considered = [
    'Close', 'Volume', 'Wilders_EMA', 'bb_bbm', 'bb_bbh', 'bb_bbl', 'bb_bbhi',
    'bb_bbli', 'trend_adx', 'momentum_stoch_signal', 'trend_trix',
    'trend_ichimoku_a', 'momentum_kama', 'momentum_tsi', 'volatility_kcli'
]
features_considered = ['close', 'MA_long', 'MA_short']
# features_considered = ['Close', 'MA_short', 'MA_long', 'Wilders_EMA']
# Initialize Bollinger Bands Indicator
e = EquityData('data/SPY.csv', 'SPY')
data = pyfinancialdata.get_multi_year(provider='histdata',
                                      instrument='SPXUSD',
                                      years=[2016, 2017, 2018],
                                      time_group='10min')
e.data = data
indicator_bb = BollingerBands(close=e.data['close'], n=20, ndev=2)
# e.data = add_all_ta_features(e.data, open="open", high="high", low="low", close="close")

e.data['MA_long'] = e.data['close'].rolling(window=52).mean()
e.data['MA_short'] = e.data['close'].rolling(window=7).mean()
# e.data['MA_short'] = 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()