Exemple #1
0
def rsi(candles, window):
    """Relative Strength Index"""

    closes = util.filtership(candles, "close")
    result = ta.rsi(closes, window)

    return result
Exemple #2
0
    def generate_images(data):

        # Reshape Pandas Dataframe
        #df = data['_2'].apply(pd.Series)
        #df.columns = column_names.value

        df = data.reset_index().rename(columns={'index': 'INDEX'})
        df['SMA50'] = df[target.value].rolling(50).mean()
        df['SMA200'] = df[target.value].rolling(200).mean()
        df['RSI14'] = ta.rsi(df[target.value], n=14)
        renderer = ImageRender(figsize=int(figsize.value), plot_volume=volume.value, dpi=int(dpi.value), plot_sma=sma.value, plot_rsi=rsi.value)

        window = window_size.value
        offset = window_offset.value
        l = [np.nan for i in range(0, window - 1)]
        for i in range(0, len(df) + 1 - window, offset):
            sample = df[i:i + window]
            l.append(renderer.render(sample))
            l = l + [ np.nan for j in range(0,offset-1)]
        l = l[:len(df)]

        df['IMAGE'] = l
        df = df.dropna()
        l = df['IMAGE'].values.tolist()
        #df_aux = pd.DataFrame(OrderedDict([('C' + str(i), [z[i] for z in l]) for i in range(0, len(l[0]))]))
        df_aux = pd.DataFrame( {'C' + str(i): [z[i] for z in l] for i in range(0, len(l[0]))} )
        df_aux = df_aux.reset_index(drop=True)
        df = df.drop(columns=['INDEX', 'IMAGE', 'SMA50', 'SMA200', 'RSI14'])
        df = df.reset_index(drop=True)
        #for c in df_aux.columns:
            #df[c] = df_aux[c]

        df = pd.concat([df.reset_index(drop=True), df_aux.reset_index(drop=True)], axis=1)
        return df
Exemple #3
0
def add_indicators(data: pd.DataFrame) -> pd.DataFrame:
    """
    This method creates technical indicators, based on the OHLC and volume bars
    :param data: pandas DataFrame, containing open, high, low and close and
                 optional volume columns
    :return: DataFrame with added technical indicators
    """
    assert 'open' in data.columns, "open column not present or with different name"
    assert 'high' in data.columns, "high column not present or with different name"
    assert 'low' in data.columns, "low column not present or with different name"
    assert 'close' in data.columns, "close column not present or with different name"

    try:
        data['RSI'] = ta.rsi(data["close"])
        data['TSI'] = ta.tsi(data["close"])
        data['UO'] = ta.uo(data["high"], data["low"], data["close"])
        data['AO'] = ta.ao(data["high"], data["low"])
        data['MACD_diff'] = ta.macd_diff(data["close"])
        data['Vortex_pos'] = ta.vortex_indicator_pos(data["high"], data["low"], data["close"])
        data['Vortex_neg'] = ta.vortex_indicator_neg(data["high"], data["low"], data["close"])
        data['Vortex_diff'] = abs(data['Vortex_pos'] - data['Vortex_neg'])
        data['Trix'] = ta.trix(data["close"])
        data['Mass_index'] = ta.mass_index(data["high"], data["low"])
        data['CCI'] = ta.cci(data["high"], data["low"], data["close"])
        data['DPO'] = ta.dpo(data["close"])
        data['KST'] = ta.kst(data["close"])
        data['KST_sig'] = ta.kst_sig(data["close"])
        data['KST_diff'] = (data['KST'] - data['KST_sig'])
        data['Aroon_up'] = ta.aroon_up(data["close"])
        data['Aroon_down'] = ta.aroon_down(data["close"])
        data['Aroon_ind'] = (data['Aroon_up'] - data['Aroon_down'])
        data['BBH'] = ta.bollinger_hband(data["close"])
        data['BBL'] = ta.bollinger_lband(data["close"])
        data['BBM'] = ta.bollinger_mavg(data["close"])
        data['BBHI'] = ta.bollinger_hband_indicator(data["close"])
        data['BBLI'] = ta.bollinger_lband_indicator(data["close"])
        data['KCHI'] = ta.keltner_channel_hband_indicator(data["high"], data["low"], data["close"])
        data['KCLI'] = ta.keltner_channel_lband_indicator(data["high"], data["low"], data["close"])
        data['DCHI'] = ta.donchian_channel_hband_indicator(data["close"])
        data['DCLI'] = ta.donchian_channel_lband_indicator(data["close"])
        data['DR'] = ta.daily_return(data["close"])
        data['DLR'] = ta.daily_log_return(data["close"])

        if 'volume' in data.columns:
            data['MFI'] = ta.money_flow_index(data["high"], data["low"], data["close"], data["volume"])
            data['ADI'] = ta.acc_dist_index(data["high"], data["low"], data["close"], data["volume"])
            data['OBV'] = ta.on_balance_volume(data["close"], data["volume"])
            data['CMF'] = ta.chaikin_money_flow(data["high"], data["low"], data["close"], data["volume"])
            data['FI'] = ta.force_index(data["close"], data["volume"])
            data['EM'] = ta.ease_of_movement(data["high"], data["low"], data["close"], data["volume"])
            data['VPT'] = ta.volume_price_trend(data["close"], data["volume"])
            data['NVI'] = ta.negative_volume_index(data["close"], data["volume"])

        data.fillna(method='bfill', inplace=True)

        return data

    except (AssertionError, Exception) as error:
        raise IndicatorsError(error)
        LOGGER.error(error)
Exemple #4
0
        def rsi_policy():
            """
            The RSI Divergence algorithm.

            Returns:
                Tuple[int, int]: The Action-Amount pair.

            """
            period = 5
            prices = self.env.full_data_df["Close"]
            cur_step = self.env.cur_step

            rsi = ta.rsi(prices)

            if cur_step >= period:
                rsi_sum = sum(rsi[cur_step - period:cur_step +
                                  1].diff().cumsum().fillna(0))
                price_sum = sum(prices[cur_step - period:cur_step +
                                       1].diff().cumsum().fillna(0))

                if rsi_sum < 0 <= price_sum:
                    return 0, 10
                elif rsi_sum > 0 >= price_sum:
                    return 2, 10

            return 1, 10
def add_indicators(df):
    df['RSI'] = ta.rsi(df["Close"])
    df['MFI'] = ta.money_flow_index(df["High"], df["Low"], df["Close"],
                                    df["Volume"])
    df['TSI'] = ta.tsi(df["Close"])
    df['UO'] = ta.uo(df["High"], df["Low"], df["Close"])
    df['AO'] = ta.ao(df["High"], df["Low"])

    df['MACD_diff'] = ta.macd_diff(df["Close"])
    df['Vortex_pos'] = ta.vortex_indicator_pos(df["High"], df["Low"],
                                               df["Close"])
    df['Vortex_neg'] = ta.vortex_indicator_neg(df["High"], df["Low"],
                                               df["Close"])
    df['Vortex_diff'] = abs(df['Vortex_pos'] - df['Vortex_neg'])
    df['Trix'] = ta.trix(df["Close"])
    df['Mass_index'] = ta.mass_index(df["High"], df["Low"])
    df['CCI'] = ta.cci(df["High"], df["Low"], df["Close"])
    df['DPO'] = ta.dpo(df["Close"])
    df['KST'] = ta.kst(df["Close"])
    df['KST_sig'] = ta.kst_sig(df["Close"])
    df['KST_diff'] = (df['KST'] - df['KST_sig'])
    df['Aroon_up'] = ta.aroon_up(df["Close"])
    df['Aroon_down'] = ta.aroon_down(df["Close"])
    df['Aroon_ind'] = (df['Aroon_up'] - df['Aroon_down'])

    df['BBH'] = ta.bollinger_hband(df["Close"])
    df['BBL'] = ta.bollinger_lband(df["Close"])
    df['BBM'] = ta.bollinger_mavg(df["Close"])
    df['BBHI'] = ta.bollinger_hband_indicator(df["Close"])
    df['BBLI'] = ta.bollinger_lband_indicator(df["Close"])
    df['KCHI'] = ta.keltner_channel_hband_indicator(df["High"], df["Low"],
                                                    df["Close"])
    df['KCLI'] = ta.keltner_channel_lband_indicator(df["High"], df["Low"],
                                                    df["Close"])
    df['DCHI'] = ta.donchian_channel_hband_indicator(df["Close"])
    df['DCLI'] = ta.donchian_channel_lband_indicator(df["Close"])

    df['ADI'] = ta.acc_dist_index(df["High"], df["Low"], df["Close"],
                                  df["Volume"])
    df['OBV'] = ta.on_balance_volume(df["Close"], df["Volume"])
    df['CMF'] = ta.chaikin_money_flow(df["High"], df["Low"], df["Close"],
                                      df["Volume"])
    df['FI'] = ta.force_index(df["Close"], df["Volume"])
    df['EM'] = ta.ease_of_movement(df["High"], df["Low"], df["Close"],
                                   df["Volume"])
    df['VPT'] = ta.volume_price_trend(df["Close"], df["Volume"])
    df['NVI'] = ta.negative_volume_index(df["Close"], df["Volume"])

    df['DR'] = ta.daily_return(df["Close"])
    df['DLR'] = ta.daily_log_return(df["Close"])

    df.fillna(method='bfill', inplace=True)

    return df
Exemple #6
0
 def rs():
     r = ta.rsi(close, n=14, fillna=False)
     rsi = (r[-1])
     if 15.1 <= rsi <= 30:
         status = "Buy"
     elif rsi <= 15:
         status = "Strong Buy"
     elif 84.9 <= rsi >= 70:
         status = "Sell"
     elif rsi >= 85:
         status = "Strong Sell"
     else:
         status = "Hold"
     return status
def add_candle_indicators(df, l, ck, hk, lk, vk):
    df[l + 'rsi'] = ta.rsi(df[ck])
    df[l + 'mfi'] = ta.money_flow_index(df[hk], df[lk], df[ck], df[vk])
    df[l + 'tsi'] = ta.tsi(df[ck])
    df[l + 'uo'] = ta.uo(df[hk], df[lk], df[ck])
    df[l + 'ao'] = ta.ao(df[hk], df[lk])
    df[l + 'macd_diff'] = ta.macd_diff(df[ck])
    df[l + 'vortex_pos'] = ta.vortex_indicator_pos(df[hk], df[lk], df[ck])
    df[l + 'vortex_neg'] = ta.vortex_indicator_neg(df[hk], df[lk], df[ck])
    df[l + 'vortex_diff'] = abs(df[l + 'vortex_pos'] - df[l + 'vortex_neg'])
    df[l + 'trix'] = ta.trix(df[ck])
    df[l + 'mass_index'] = ta.mass_index(df[hk], df[lk])
    df[l + 'cci'] = ta.cci(df[hk], df[lk], df[ck])
    df[l + 'dpo'] = ta.dpo(df[ck])
    df[l + 'kst'] = ta.kst(df[ck])
    df[l + 'kst_sig'] = ta.kst_sig(df[ck])
    df[l + 'kst_diff'] = (df[l + 'kst'] - df[l + 'kst_sig'])
    df[l + 'aroon_up'] = ta.aroon_up(df[ck])
    df[l + 'aroon_down'] = ta.aroon_down(df[ck])
    df[l + 'aroon_ind'] = (df[l + 'aroon_up'] - df[l + 'aroon_down'])
    df[l + 'bbh'] = ta.bollinger_hband(df[ck])
    df[l + 'bbl'] = ta.bollinger_lband(df[ck])
    df[l + 'bbm'] = ta.bollinger_mavg(df[ck])
    df[l + 'bbhi'] = ta.bollinger_hband_indicator(df[ck])
    df[l + 'bbli'] = ta.bollinger_lband_indicator(df[ck])
    df[l + 'kchi'] = ta.keltner_channel_hband_indicator(df[hk], df[lk], df[ck])
    df[l + 'kcli'] = ta.keltner_channel_lband_indicator(df[hk], df[lk], df[ck])
    df[l + 'dchi'] = ta.donchian_channel_hband_indicator(df[ck])
    df[l + 'dcli'] = ta.donchian_channel_lband_indicator(df[ck])
    df[l + 'adi'] = ta.acc_dist_index(df[hk], df[lk], df[ck], df[vk])
    df[l + 'obv'] = ta.on_balance_volume(df[ck], df[vk])
    df[l + 'cmf'] = ta.chaikin_money_flow(df[hk], df[lk], df[ck], df[vk])
    df[l + 'fi'] = ta.force_index(df[ck], df[vk])
    df[l + 'em'] = ta.ease_of_movement(df[hk], df[lk], df[ck], df[vk])
    df[l + 'vpt'] = ta.volume_price_trend(df[ck], df[vk])
    df[l + 'nvi'] = ta.negative_volume_index(df[ck], df[vk])
    df[l + 'dr'] = ta.daily_return(df[ck])
    df[l + 'dlr'] = ta.daily_log_return(df[ck])
    df[l + 'ma50'] = df[ck].rolling(window=50).mean()
    df[l + 'ma100'] = df[ck].rolling(window=100).mean()
    df[l + '26ema'] = df[[ck]].ewm(span=26).mean()
    df[l + '12ema'] = df[[ck]].ewm(span=12).mean()
    df[l + 'macd'] = (df[l + '12ema'] - df[l + '26ema'])
    df[l + '100sd'] = df[[ck]].rolling(100).std()
    df[l + 'upper_band'] = df[l + 'ma100'] + (df[l + '100sd'] * 2)
    df[l + 'lower_band'] = df[l + 'ma100'] - (df[l + '100sd'] * 2)
    df[l + 'ema'] = df[ck].ewm(com=0.5).mean()
    df[l + 'momentum'] = df[ck] - 1
    return df
Exemple #8
0
    def do_ta(self, data_series):

        open = Series(data_series['open'].astype('float64'))
        high = Series(data_series['high'].astype('float64'))
        low = Series(data_series['low'].astype('float64'))
        close = Series(data_series['close'].astype('float64'))

        #      Trend
        # ----------------
        ema30 = ta.ema(series=close, periods=30)
        ema50 = ta.ema(series=close, periods=50)
        ema100 = ta.ema(series=close, periods=100)
        ema200 = ta.ema(series=close, periods=200)
        macd_diff = ta.macd_diff(close=close, n_fast=12, n_slow=26, n_sign=9)
        macd_signal = ta.macd_signal(close=close,
                                     n_fast=12,
                                     n_slow=26,
                                     n_sign=9)

        data_series['ema30'] = ema30
        data_series['ema50'] = ema50
        data_series['ema100'] = ema100
        data_series['ema200'] = ema200
        data_series['macd_diff'] = macd_diff
        data_series['macd_signal'] = macd_signal

        #     Momentum
        # ----------------
        rsi = ta.rsi(close=close)
        stochastic = ta.stoch(high=high, low=low, close=close)

        data_series['rsi'] = rsi
        data_series['stochastic'] = stochastic

        #    Volatility
        # ----------------
        bollinger_h = ta.bollinger_hband(close=close)
        bollinger_l = ta.bollinger_lband(close=close)
        bollinger_h_indicator = ta.bollinger_hband_indicator(close=close)
        bollinger_l_indicator = ta.bollinger_lband_indicator(close=close)

        data_series['bollinger_h'] = bollinger_h
        data_series['bollinger_l'] = bollinger_l
        data_series['bollinger_h_indicator'] = bollinger_h_indicator
        data_series['bollinger_l_indicator'] = bollinger_l_indicator
        data_series['last_candle_change'] = self.lcc(close=close)

        return data_series
def rsi_divergence(prices, period=3):
    rsi = ta.rsi(prices)

    def signal_fn(i):
        rsiSum = sum(rsi[i - period:i + 1].diff().cumsum().fillna(0))
        priceSum = sum(prices[i - period:i + 1].diff().cumsum().fillna(0))

        if i >= period:
            if rsiSum < 0 and priceSum >= 0:
                return SIGNALS.BUY
            elif rsiSum > 0 and priceSum <= 0:
                return SIGNALS.SELL

        return SIGNALS.HOLD

    return signal_fn
Exemple #10
0
def rsi_divergence(prices, initial_balance, commision, period=3):
    rsi = ta.rsi(prices)

    def signal_fn(i):
        if i >= period:
            rsiSum = sum(rsi[i - period:i + 1].diff().cumsum().fillna(0))
            priceSum = sum(prices[i - period:i + 1].diff().cumsum().fillna(0))

            if rsiSum < 0 and priceSum >= 0:
                return SIGNAL.SELL
            elif rsiSum > 0 and priceSum <= 0:
                return SIGNAL.BUY

        return SIGNAL.HOLD

    return trade_strategy(prices, initial_balance, commision, signal_fn)
 def addTechnicalAnalysisIndicators(self, df):
   ''' #bollinger indicators (1 or 0)
   df['bb_high_indicator'] = ta.bollinger_hband_indicator(close)
   df['bb_low_indicator'] = ta.bollinger_lband_indicator(close)'''
   
   close, high, low = self.close, self.high, self.low
   # rsi with time period (for 5 min intervals, n=12 -> 1 hour)
   df['rsi'] = ta.rsi(close, n=14)
   df['upperboll'] = ta.bollinger_hband(close, ndev=2, fillna=False)
   df['lowerboll'] = ta.bollinger_lband(close, ndev=2, fillna=False)
   df['lowerkelt'] = ta.keltner_channel_lband(high, low, close, n=10, fillna=False)
   df['upperkelt'] = ta.keltner_channel_hband(high, low, close, n=10, fillna=False)
   df['sma14'] = ta.bollinger_mavg(close, n=14)
   df['sma30'] = ta.bollinger_mavg(close, n=30)
   df['sma50'] = ta.bollinger_mavg(close, n=50)
   df['sma200'] = ta.bollinger_mavg(close, n=200)
   return df
def process_data(data):
    data['BB_5'] = ta.bollinger_mavg(
        data['CLOSE'], 5)  #bollinger_moving average 5 trading periods
    data['BB_10'] = ta.bollinger_mavg(
        data['CLOSE'], 10)  #bollinger_moving average 10 trading periods
    data['BB_20'] = ta.bollinger_mavg(
        data['CLOSE'], 20)  # bollinger_moving average 20 periods
    data['ADX'] = ta.adx(data['HIGH'], data['LOW'], data['CLOSE'],
                         14)  #Average Directional Index
    data['ATR'] = ta.average_true_range(data['HIGH'], data['LOW'],
                                        data['CLOSE'], 14)  #Average True Range
    data['CCI'] = ta.cci(data['HIGH'], data['LOW'], data['CLOSE'],
                         14)  #Commodity Channel Index
    data['DCH'] = ta.donchian_channel_hband(
        data['CLOSE'])  #Donchian Channel High Band
    data['DCL'] = ta.donchian_channel_lband(
        data['CLOSE'])  #Donchian Channel Low Band
    data['DPO'] = ta.dpo(data['CLOSE'])  #Detrend Price Oscilator
    data['EMAf'] = ta.ema_fast(
        data['CLOSE'])  #Expornential Moving Average fast
    data['EMAs'] = ta.ema_slow(
        data['CLOSE'])  #Expornential Moving Average slow
    data['FI'] = ta.force_index(
        data['CLOSE'],
        data['VOLUME'])  # Force Index(reveals the value of a trend)
    data['ICHa'] = ta.ichimoku_a(data['HIGH'], data['LOW'])  #Ichimoku A
    data['ICHb'] = ta.ichimoku_b(data['HIGH'], data['LOW'])  #Ichimoku B
    data['KC'] = ta.keltner_channel_central(
        data['HIGH'], data['LOW'], data['CLOSE'])  #Keltner channel(KC) Central
    data['KST'] = ta.kst(
        data['CLOSE']
    )  #KST Oscillator (KST) identify major stock market cycle junctures
    data['MACD'] = ta.macd(
        data['CLOSE'])  # Moving Average convergence divergence
    data['OBV'] = ta.on_balance_volume_mean(
        data['CLOSE'], data['VOLUME'])  # on_balance_volume_mean
    data['RSI'] = ta.rsi(data['CLOSE'])  # Relative Strength Index (RSI)
    data['TRIX'] = ta.trix(
        data['CLOSE']
    )  #Shows the percent rate of change of a triple exponentially smoothed moving average
    data['TSI'] = ta.tsi(data['CLOSE'])  #True strength index (TSI)
    data['ROC1'] = (data['CLOSE'] - data['OPEN']) / data['OPEN']
    data['RET'] = data['CLOSE'].pct_change()
    data['y'] = np.where(data['OPEN'] <= data['CLOSE'], 1, -1)
    data = data.dropna()
    return data
Exemple #13
0
def add_indicators(df):
    df['RSI'] = ta.rsi(df["Close"])
    df['TSI'] = ta.tsi(df["Close"])
    df['UO'] = ta.uo(df["High"], df["Low"], df["Close"])
    df['AO'] = ta.ao(df["High"], df["Low"])

    df['MACD_diff'] = ta.macd_diff(df["Close"])
    df['Vortex_pos'] = ta.vortex_indicator_pos(df["High"], df["Low"],
                                               df["Close"])
    df['Vortex_neg'] = ta.vortex_indicator_neg(df["High"], df["Low"],
                                               df["Close"])
    df['Vortex_diff'] = abs(df['Vortex_pos'] - df['Vortex_neg'])
    df['Trix'] = ta.trix(df["Close"])
    df['Mass_index'] = ta.mass_index(df["High"], df["Low"])
    df['CCI'] = ta.cci(df["High"], df["Low"], df["Close"])
    df['DPO'] = ta.dpo(df["Close"])
    df['KST'] = ta.kst(df["Close"])
    df['KST_sig'] = ta.kst_sig(df["Close"])
    df['KST_diff'] = (df['KST'] - df['KST_sig'])
    df['Aroon_up'] = ta.aroon_up(df["Close"])
    df['Aroon_down'] = ta.aroon_down(df["Close"])
    df['Aroon_ind'] = (df['Aroon_up'] - df['Aroon_down'])

    df['BBH'] = ta.bollinger_hband(df["Close"])
    df['BBL'] = ta.bollinger_lband(df["Close"])
    df['BBM'] = ta.bollinger_mavg(df["Close"])
    df['BBHI'] = ta.bollinger_hband_indicator(df["Close"])
    df['BBLI'] = ta.bollinger_lband_indicator(df["Close"])
    df['KCHI'] = ta.keltner_channel_hband_indicator(df["High"], df["Low"],
                                                    df["Close"])
    df['KCLI'] = ta.keltner_channel_lband_indicator(df["High"], df["Low"],
                                                    df["Close"])
    df['DCHI'] = ta.donchian_channel_hband_indicator(df["Close"])
    df['DCLI'] = ta.donchian_channel_lband_indicator(df["Close"])

    df['DR'] = ta.daily_return(df["Close"])
    df['DLR'] = ta.daily_log_return(df["Close"])

    df.fillna(method='bfill', inplace=True)

    return df
Exemple #14
0
dd['target_1']=dd['Adj Close'].shift(-1)/dd['Adj Close']-1
dd['target_3']=dd['Adj Close'].shift(-3)/dd['Adj Close']-1
dd['target_7']=dd['Adj Close'].shift(-7)/dd['Adj Close']-1
dd['target_14']=dd['Adj Close'].shift(-14)/dd['Adj Close']-1
dd['target_30']=dd['Adj Close'].shift(-30)/dd['Adj Close']-1

dd['s00_return_1']=dd.Close/dd.Close.shift(1)-1
dd['s00_return_3']=dd.Close/dd.Close.shift(3)-1
dd['s03_return_1']=dd.s00_return_1.shift(3)
dd['s03_return_3']=dd.s00_return_3.shift(3)
dd['s05_return_1']=dd.s00_return_1.shift(5)
dd['s05_return_3']=dd.s00_return_3.shift(5)


dd['s00_rsi_14']=ta.rsi(dd.Close, 14)
dd['s00_rsi_7']=ta.rsi(dd.Close, 7)
dd['s00_willR_14']=ta.wr(dd.High,dd.Low,dd.Close,14)
dd['s00_willR_7']=ta.wr(dd.High,dd.Low,dd.Close,7)
dd['s00_stoch_sig_14_3']=ta.stoch_signal(dd.High,dd.Low,dd.Close,14,3)
dd['s00_stoch_sig_7_3']=ta.stoch_signal(dd.High,dd.Low,dd.Close,7,3)
dd['s00_cci_20_0015']=ta.cci(dd.High,dd.Low,dd.Close,20,0.015)
dd['s00_cci_20_005']=ta.cci(dd.High,dd.Low,dd.Close,20,0.05)
dd['s00_macd_12_26_9']=ta.macd_diff(dd.Close,12,26,9)
dd['s00_macd_7_14_9']=ta.macd_diff(dd.Close,7,14, 9)
dd['s00_kst_9']=ta.kst(dd.Close)-ta.kst_sig(dd.Close)

dd['s01_rsi_14']=dd.s00_rsi_14.shift(+1)
dd['s01_rsi_7']=dd.s00_rsi_7.shift(+1)
dd['s01_willR_14']=dd.s00_willR_14.shift(+1)
dd['s01_willR_7']=dd.s00_willR_7.shift(+1)
Exemple #15
0
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import ta

df = pd.read_csv('./data/coinbase_daily.csv')
df = df.dropna().reset_index().sort_values('Date')

ta_df = pd.DataFrame()

ta_df['RSI'] = ta.rsi(df["Close"])
ta_df['MFI'] = ta.money_flow_index(
    df["High"], df["Low"], df["Close"], df["Volume BTC"])
ta_df['TSI'] = ta.tsi(df["Close"])
ta_df['UO'] = ta.uo(df["High"], df["Low"], df["Close"])
ta_df['Stoch'] = ta.stoch(df["High"], df["Low"], df["Close"])
ta_df['Stoch_Signal'] = ta.stoch_signal(df["High"], df["Low"], df["Close"])
ta_df['WR'] = ta.wr(df["High"], df["Low"], df["Close"])
ta_df['AO'] = ta.ao(df["High"], df["Low"])

ta_df['MACD'] = ta.macd(df["Close"])
ta_df['MACD_signal'] = ta.macd_signal(df["Close"])
ta_df['MACD_diff'] = ta.macd_diff(df["Close"])
ta_df['EMA_fast'] = ta.ema_indicator(df["Close"])
ta_df['EMA_slow'] = ta.ema_indicator(df["Close"])
ta_df['Vortex_pos'] = ta.vortex_indicator_pos(
    df["High"], df["Low"], df["Close"])
ta_df['Vortex_neg'] = ta.vortex_indicator_neg(
    df["High"], df["Low"], df["Close"])
ta_df['Vortex_diff'] = abs(
    ta_df['Vortex_pos'] -
def get_data(context, data_, window):
    # Crear ventana de datos.

    h1 = data_.history(
        context.symbols,
        context.row_features,
        bar_count=window,
        frequency=str(context.bar_period) + "T",
    )

    h1 = h1.swapaxes(2, 0)

    norm_data = []
    close_prices = []

    for i, asset in enumerate(context.assets):
        data = h1.iloc[i]
        close = h1.iloc[i].close
        if context.include_ha:
            ha = heikenashi(data)
            data = pd.concat((data, ha), axis=1)

        for period in [3, 6, 8, 10, 15, 20]:
            data["rsi" + str(period)] = ta.rsi(data.close,
                                               n=period,
                                               fillna=True)
            data["stoch" + str(period)] = ta.stoch(data.high,
                                                   data.low,
                                                   data.close,
                                                   n=period,
                                                   fillna=True)
            data["stoch_signal" + str(period)] = ta.stoch_signal(
                high=data.high,
                low=data.low,
                close=data.close,
                n=period,
                d_n=3,
                fillna=True)

            data["dpo" + str(period)] = ta.dpo(close=data.close,
                                               n=period,
                                               fillna=True)
            data["atr" + str(period)] = ta.average_true_range(high=data.high,
                                                              low=data.low,
                                                              close=data.close,
                                                              n=period,
                                                              fillna=True)

        for period in [6, 7, 8, 9, 10]:
            data["williams" + str(period)] = ta.wr(high=data.high,
                                                   low=data.low,
                                                   close=data.close,
                                                   lbp=period,
                                                   fillna=True)
        for period in [12, 13, 14, 15]:
            data["proc" + str(period)] = ta.trix(close=data.close,
                                                 n=period,
                                                 fillna=True)

        data["macd_diff"] = ta.macd_diff(close=data.close,
                                         n_fast=15,
                                         n_slow=30,
                                         n_sign=9,
                                         fillna=True)

        data["macd_signal"] = ta.macd_signal(close=data.close,
                                             n_fast=15,
                                             n_slow=30,
                                             n_sign=9,
                                             fillna=True)

        data["bb_high_indicator"] = ta.bollinger_hband_indicator(
            close=data.close, n=15, ndev=2, fillna=True)

        data["bb_low_indicator"] = ta.bollinger_lband_indicator(
            close=data.close, n=15, ndev=2, fillna=True)

        data["dc_high_indicator"] = ta.donchian_channel_hband_indicator(
            close=data.close, n=20, fillna=True)

        data["dc_low_indicator"] = ta.donchian_channel_lband_indicator(
            close=data.close, n=20, fillna=True)

        data["ichimoku_a"] = ta.ichimoku_a(high=data.high,
                                           low=data.low,
                                           n1=9,
                                           n2=26,
                                           fillna=True)

        data.fillna(method="bfill")

        # Normalizar los valores
        for feature in data.columns:
            norm_feature = preprocessing.normalize(
                data[feature].values.reshape(-1, 1), axis=0)
            data[feature] = pd.DataFrame(data=norm_feature,
                                         index=data.index,
                                         columns=[feature])

        norm_data.append(data.values)
        close_prices.append(close)
        context.features = data.columns

    return np.array(norm_data), np.array(close_prices)
Exemple #17
0
                                price['Low'],
                                n1=9,
                                n2=26,
                                fillna=True)
X['ichimoku_b'] = ta.ichimoku_b(price['High'],
                                price['Low'],
                                n2=26,
                                n3=52,
                                fillna=True)
X['money_flow_index'] = ta.money_flow_index(price['High'],
                                            price['Low'],
                                            price['Adj. Close'],
                                            price['Volume'],
                                            n=14,
                                            fillna=True)
X['rsi'] = ta.rsi(price['Adj. Close'], n=14, fillna=True)
X['tsi'] = ta.tsi(price['Adj. Close'], r=25, s=13, fillna=True)
X['uo'] = ta.uo(price['High'],
                price['Low'],
                price['Adj. Close'],
                s=7,
                m=14,
                l=28,
                ws=4,
                wm=2,
                wl=1,
                fillna=True)
X['stoch_signal'] = ta.stoch_signal(price['High'],
                                    price['Low'],
                                    price['Adj. Close'],
                                    n=14,
if n_indicatori == 1:
    indicatore1 = indicatori_sep[0]
elif n_indicatori == 2:
    indicatore1 = indicatori_sep[0]
    indicatore2 = indicatori_sep[1]
elif n_indicatori == 3:
    indicatore1 = indicatori_sep[0]
    indicatore2 = indicatori_sep[1]
    indicatore3 = indicatori_sep[2]
else:
    print('Gli indicatori devono essere più di 0 e minori o uguali a 3')

if n_indicatori == 1:
    if indicatore1 == 'RSI':
        tabella['RSI'] = ta.rsi(tabella['Chiusura'], 3)
    if indicatore1 == 'MACD':
        tabella['MACD'] = ta.trend.macd(tabella['Chiusura'],
                                        n_fast=12,
                                        n_slow=26,
                                        fillna=False)
    if indicatore1 == 'ADX':
        tabella['ADX'] = ta.trend.macd(tabella['Chiusura'],
                                       n_fast=12,
                                       n_slow=26,
                                       fillna=False)
    tabella['MediaVolumi'] = ta.utils.ema(tabella['Volume(Asset)'], 20)

if n_indicatori == 2:
    if indicatore1 == 'RSI' or indicatore2 == 'RSI':
        tabella['RSI'] = ta.rsi(tabella['Chiusura'], n=3, fillna=False)
Exemple #19
0
def add_technical_indicators(df):
    """
    Args:
        df (pd.DataFrame): The processed dataframe returned by `process_data`.

    Returns:
        pd.DataFrame: The updated dataframe with the technical indicators inside.

    Acknowledgements:
        - Thanks for Adam King for this compilation of technical indicators!
          The original file and code can be found here:
          https://github.com/notadamking/RLTrader/blob/e5b83b1571f9fcfa6a67a2a810222f1f1751996c/util/indicators.py

    """

    # Add momentum indicators
    df["AO"] = ta.ao(df["High"], df["Low"])
    df["MFI"] = ta.money_flow_index(df["High"], df["Low"], df["Close"],
                                    df["Volume"])
    df["RSI"] = ta.rsi(df["Close"])
    df["TSI"] = ta.tsi(df["Close"])
    df["UO"] = ta.uo(df["High"], df["Low"], df["Close"])

    # Add trend indicators
    df["Aroon_up"] = ta.aroon_up(df["Close"])
    df["Aroon_down"] = ta.aroon_down(df["Close"])
    df["Aroon_ind"] = (df["Aroon_up"] - df["Aroon_down"])
    df["CCI"] = ta.cci(df["High"], df["Low"], df["Close"])
    df["DPO"] = ta.dpo(df["Close"])
    df["KST"] = ta.kst(df["Close"])
    df["KST_sig"] = ta.kst_sig(df["Close"])
    df["KST_diff"] = (df["KST"] - df["KST_sig"])
    df["MACD_diff"] = ta.macd_diff(df["Close"])
    df["Mass_index"] = ta.mass_index(df["High"], df["Low"])
    df["Trix"] = ta.trix(df["Close"])
    df["Vortex_pos"] = ta.vortex_indicator_pos(df["High"], df["Low"],
                                               df["Close"])
    df["Vortex_neg"] = ta.vortex_indicator_neg(df["High"], df["Low"],
                                               df["Close"])
    df["Vortex_diff"] = abs(df["Vortex_pos"] - df["Vortex_neg"])

    # Add volatility indicators
    df["BBH"] = ta.bollinger_hband(df["Close"])
    df["BBL"] = ta.bollinger_lband(df["Close"])
    df["BBM"] = ta.bollinger_mavg(df["Close"])
    df["BBHI"] = ta.bollinger_hband_indicator(df["Close"])
    df["BBLI"] = ta.bollinger_lband_indicator(df["Close"])
    df["KCHI"] = ta.keltner_channel_hband_indicator(df["High"], df["Low"],
                                                    df["Close"])
    df["KCLI"] = ta.keltner_channel_lband_indicator(df["High"], df["Low"],
                                                    df["Close"])
    df["DCHI"] = ta.donchian_channel_hband_indicator(df["Close"])
    df["DCLI"] = ta.donchian_channel_lband_indicator(df["Close"])

    # Volume indicators
    df["ADI"] = ta.acc_dist_index(df["High"], df["Low"], df["Close"],
                                  df["Volume"])
    df["CMF"] = ta.chaikin_money_flow(df["High"], df["Low"], df["Close"],
                                      df["Volume"])
    df["EM"] = ta.ease_of_movement(df["High"], df["Low"], df["Close"],
                                   df["Volume"])
    df["FI"] = ta.force_index(df["Close"], df["Volume"])
    df["NVI"] = ta.negative_volume_index(df["Close"], df["Volume"])
    df["OBV"] = ta.on_balance_volume(df["Close"], df["Volume"])
    df["VPT"] = ta.volume_price_trend(df["Close"], df["Volume"])

    # Add miscellaneous indicators
    df["DR"] = ta.daily_return(df["Close"])
    df["DLR"] = ta.daily_log_return(df["Close"])

    # Fill in NaN values
    df.fillna(method="bfill", inplace=True)  # First try `bfill`
    df.fillna(value=0,
              inplace=True)  # Then replace the rest of the NANs with 0s

    return df
    def __init__(self, Reuters):
        self.reuters = Reuters

        #actual price data
        url_csv = "http://matterhorn-lab.herokuapp.com/download/" + str(
            self.reuters)
        prices_data = pd.read_csv(url_csv, sep=",")
        start, stop, step = 0, -14, 1
        prices_data["Date"] = prices_data["Date"].str.slice(start, stop, step)

        prices_data = prices_data[::-1].reset_index()
        prices_data = prices_data.drop(['index'], axis=1)
        prices_data = prices_data.sort_values(["Date"],
                                              ascending=[1]).reset_index()
        prices_data = prices_data.drop(['index'], axis=1)

        #static
        stock_info = pd.read_csv('data/DB_Stock_Info.csv', sep=';')
        key_ratios = pd.read_csv('data/DB_Stock_Key_Ratios.csv', sep=';')

        # get the number of business days
        c_size = len(prices_data.columns)
        r_size = prices_data.shape[0]

        date_data = prices_data.iloc[:, 0]
        today = date_data.iloc[r_size - 1:r_size]
        today = pd.to_datetime(today)
        today = datetime.date(int(today.dt.year), int(today.dt.month),
                              int(today.dt.day))

        # calculate days yesterday
        yesterday = today - BDay(1)
        # calculate days last week
        lastweek = today - BDay(5)
        # calculate days  since start month
        startmonth = datetime.date(int(today.strftime('%Y')),
                                   int(today.strftime('%m')), 1)
        days_start_month = np.busday_count(startmonth, today)
        # calculate days  last month
        lastmonth = datetime.date(int(today.strftime('%Y')),
                                  int(today.strftime('%m')) - 1,
                                  int(today.strftime('%d')))
        days_last_month = np.busday_count(lastmonth, today)
        # calculate days since start year
        yearstart = datetime.date(int(today.strftime('%Y')), 1, 1)
        days_start_year = np.busday_count(yearstart, today)
        # calculate days one year
        lastyear = datetime.date(
            int(today.strftime('%Y')) - 1, int(today.strftime('%m')),
            int(today.strftime('%d')))
        days_last_year = np.busday_count(lastyear, today)
        # calculate days three years
        last3years = datetime.date(
            int(today.strftime('%Y')) - 3, int(today.strftime('%m')),
            int(today.strftime('%d')))
        days_last_3years = np.busday_count(last3years, today)
        # calculate days five years
        last5years = datetime.date(
            int(today.strftime('%Y')) - 5, int(today.strftime('%m')),
            int(today.strftime('%d')))
        days_last_5years = np.busday_count(last5years, today)
        # calculate days ten years
        last10years = datetime.date(
            int(today.strftime('%Y')) - 10, int(today.strftime('%m')),
            int(today.strftime('%d')))
        days_last_10years = np.busday_count(last10years, today)

        # calculate returns
        prices = prices_data.iloc[:, 1:c_size]
        #returns = math.log(prices/prices.shift(1))
        #prices_year = prices.iloc[r_size-days_year:r_size]
        price_change = pd.DataFrame(prices.values[r_size - 1] - prices)
        price_change.columns = [Reuters]
        returns = prices.pct_change(1)

        # calculate price and return today
        returns_today = returns.iloc[r_size - 1:r_size]
        prices_today = prices.iloc[r_size - 1:r_size]
        price_change_today = price_change.iloc[r_size - 1:r_size]

        # calculate price and return yesterday
        returns_yesterday = returns.iloc[r_size - 2:r_size]
        prices_yesterday = prices.iloc[r_size - 2:r_size]
        cum_return_yesterday = prices_yesterday.loc[
            r_size - 1] / prices_yesterday.loc[r_size - 2] - 1
        average_return_yesterday = np.mean(returns_yesterday)
        price_change_yesterday = price_change.iloc[r_size - 2:r_size - 1]

        # calculate price and return last week
        returns_last_week = returns.iloc[r_size - 5:r_size]
        prices_last_week = prices.iloc[r_size - 5:r_size]
        cum_return_last_week = prices_last_week.loc[
            r_size - 1] / prices_last_week.loc[r_size - 5] - 1
        average_return_last_week = np.mean(returns_last_week)
        price_change_last_week = price_change.iloc[r_size - 5:r_size]
        vola_last_week = np.std(returns_last_week)
        sharpe_ratio_last_week = average_return_last_week / vola_last_week

        # calculate price and return since start month
        returns_start_month = returns.iloc[r_size - days_start_month:r_size]
        prices_start_month = prices.iloc[r_size - days_start_month:r_size]
        cum_return_start_month = prices_start_month.loc[
            r_size - 1] / prices_start_month.loc[r_size - days_start_month] - 1
        average_return_start_month = np.mean(returns_start_month)
        price_change_start_month = price_change.iloc[r_size -
                                                     days_start_month:r_size]
        vola_start_month = np.std(returns_start_month)
        sharpe_ratio_start_month = average_return_start_month / vola_start_month

        # calculate price and return last month
        returns_last_month = returns.iloc[r_size - days_last_month:r_size]
        prices_last_month = prices.iloc[r_size - days_last_month:r_size]
        cum_return_last_month = prices_last_month.loc[
            r_size - 1] / prices_last_month.loc[r_size - days_last_month] - 1
        average_return_last_month = np.mean(returns_last_month)
        price_change_last_month = price_change.iloc[r_size -
                                                    days_last_month:r_size]

        # calculate price and return since start year
        returns_start_year = returns.iloc[r_size - days_start_year:r_size]
        prices_start_year = prices.iloc[r_size - days_start_year:r_size]
        cum_return_start_year = prices_start_year.loc[
            r_size - 1] / prices_start_year.loc[r_size - days_start_year] - 1
        average_return_start_year = np.mean(returns_start_year)
        price_change_start_year = price_change.iloc[r_size -
                                                    days_start_year:r_size]
        vola_start_year = np.std(returns_start_year)
        sharpe_ratio_start_year = average_return_start_year / vola_start_year

        # calculate price and return one year
        returns_last_year = returns.iloc[r_size - days_last_year:r_size]
        prices_last_year = prices.iloc[r_size - days_last_year:r_size]
        cum_return_last_year = prices_last_year.loc[
            r_size - 1] / prices_last_year.loc[r_size - days_last_year] - 1
        average_return_last_year = np.mean(returns_last_year)
        price_change_last_year = price_change.iloc[r_size -
                                                   days_last_year:r_size]
        vola_last_year = np.std(returns_last_year)
        sharpe_ratio_last_year = average_return_last_year / vola_last_year

        # calculate price and return three years
        returns_last_3years = returns.iloc[r_size - days_last_3years:r_size]
        prices_last_3years = prices.iloc[r_size - days_last_3years:r_size]
        cum_return_last_3years = prices_last_3years.loc[
            r_size - 1] / prices_last_3years.loc[r_size - days_last_3years] - 1
        average_return_last_3years = np.mean(returns_last_3years)
        price_change_last_3years = price_change.iloc[r_size -
                                                     days_last_3years:r_size]
        vola_last_3years = np.std(returns_last_3years)
        sharpe_ratio_last_3years = average_return_last_3years / vola_last_3years

        # calculate price and return five years
        returns_last_5years = returns.iloc[r_size - days_last_5years:r_size]
        prices_last_5years = prices.iloc[r_size - days_last_5years:r_size]
        cum_return_last_5years = prices_last_5years.loc[
            r_size - 1] / prices_last_5years.loc[r_size - days_last_5years] - 1
        average_return_last_5years = np.mean(returns_last_5years)
        price_change_last_5years = price_change.iloc[r_size -
                                                     days_last_5years:r_size]
        vola_last_5years = np.std(returns_last_5years)
        sharpe_ratio_last_5years = average_return_last_5years / vola_last_5years

        # calculate price and return ten years
        returns_last_10years = returns.iloc[r_size - days_last_10years:r_size]
        prices_last_10years = prices.iloc[r_size - days_last_10years:r_size]
        cum_return_last_10years = prices_last_10years.loc[
            r_size - 1] / prices_last_10years.loc[r_size -
                                                  days_last_10years] - 1
        average_return_last_10years = np.mean(returns_last_10years)
        price_change_last_10years = price_change.iloc[r_size -
                                                      days_last_10years:r_size]
        vola_last_10years = np.std(returns_last_10years)
        sharpe_ratio_last_10years = average_return_last_10years / vola_last_10years

        # all time
        cum_return_all = prices.loc[r_size - 1] / prices.loc[3] - 1
        average_return_all = np.mean(returns)
        vola_all = np.std(returns)
        sharpe_ratio_all = average_return_all / vola_all
        # year high, low and range
        year_high = prices_last_year.max()
        year_low = prices_last_year.min()
        range_low_high = year_high - year_low
        range_percent = range_low_high / year_high

        # investment of 10000 CHF
        help_investment = returns
        help_investment = help_investment.drop(help_investment.index[0:2])
        help_invest = [0] * (c_size - 1)
        help_investment.iloc[0] = help_invest
        investment = (1 + help_investment).cumprod() * 10000

        # describtive statistics
        mean = np.mean(returns_last_year)
        std = np.std(returns_last_year)
        Z_99 = norm.ppf([0.01])

        # Value at risk
        Covar_Var = -(mean - Z_99 * std)
        n_sims = 1000000
        SimVar = []
        for i in range(c_size - 1):
            np.random.seed(i)
            random_numbers = np.random.normal(0, 1, n_sims)
            sim_returns = mean[i] + std[i] * random_numbers
            SimVar = (np.percentile(sim_returns, 1))

        HistVar = []
        for i in range(0, r_size - days_last_year):
            help_VaR = returns.iloc[r_size - days_last_year - i:r_size - i]
            HistVar.append(np.percentile(help_VaR, 1))

        df_HistVar = {}
        df_HistVar = {"Name": HistVar}
        HistVar = pd.DataFrame(HistVar)

        # Expected Shortfall
        cutoff = int(round(days_last_year * 0.01, 0))

        ES = []
        for i in range(0, r_size - days_last_year):
            help_ES = returns.Price.iloc[r_size - days_last_year - i:r_size -
                                         i]
            losses = help_ES.sort_values()
            expectedloss = np.mean(losses.iloc[0:cutoff])
            ES.append(expectedloss)

        data_ES = {}
        data_ES = {"Name": ES}
        ES = pd.DataFrame(ES)

        # Drawdown
        Roll_Max = prices.cummax()
        Daily_Drawdown = (prices / Roll_Max - 1.0)
        Max_Daily_Drawdown = Daily_Drawdown.cummin()

        Daily_Drawdown = abs(Daily_Drawdown)
        Max_Daily_Drawdown = abs(Max_Daily_Drawdown)

        #Key Ratios
        key_ratios.columns = [
            "Name", "ABBN.S", "ADEN.S", "ALCC.S", "CSGN.S", "GEBN.S", "GIVN.S",
            "LHN.S", "LONN.S", "NESN.S", "NOVN.S", "CFR.S", "ROG.S", "SGSN.S",
            "SIKA.S", "UHR.S", "SLHN.S", "SRENH.S", "SCMN.S", "UBSG.S",
            "ZURN.S"
        ]

        key_ratios_clean = key_ratios["NESN.S"]
        price_earnings_ratio = key_ratios_clean.iloc[4]

        # price/book ratio
        price_book_ratio = key_ratios_clean.iloc[5]

        # return on equity ratio
        return_on_equity_ratio = key_ratios_clean.iloc[12]

        # Dividend yield - indicated annual dividend divided by closing price
        dividend_yield_ratio = key_ratios_clean.iloc[8]

        # debt to ratio
        debt_equity_ratio = key_ratios_clean.iloc[20]

        # =============================================================================
        #Sort all analysis from above to get dataframes which are used on the webpage for the tables and figures

        #Overview: Data for Figure Annual Performance
        Data = {
            'Date': [lastmonth, lastyear, last3years, last5years, last10years],
            'Price': [
                cum_return_last_month.Price, cum_return_last_year.Price,
                cum_return_last_3years.Price, cum_return_last_5years.Price,
                cum_return_last_10years.Price
            ],
        }

        self.df_annual_perf = pd.DataFrame(Data, columns=['Date', 'Price'])

        #Table Price Performance
        Data_Price_Performance = {
            'Name': ["Placeholder"],
            '1 month': [cum_return_last_month.Price],
            '1 Years': [cum_return_last_year.Price],
            '3 Years': [cum_return_last_3years.Price],
            '5 Years': [cum_return_last_5years.Price],
            '10 Years': [cum_return_last_10years.Price],
            'Since Inception': [cum_return_all.Price],
        }

        self.df_Price_Performance = pd.DataFrame(Data_Price_Performance,
                                                 columns=[
                                                     '1 month', '1 Years',
                                                     '3 Years', '5 Years',
                                                     '10 Years',
                                                     'Since Inception'
                                                 ])

        #Overview: Hypothetical Growth
        V2007 = investment.iloc[r_size - 3 - days_last_year * 12].Price
        V2008 = investment.iloc[r_size - 3 - days_last_year * 11].Price
        V2009 = investment.iloc[r_size - 3 - days_last_year * 10].Price
        V2010 = investment.iloc[r_size - 3 - days_last_year * 9].Price
        V2011 = investment.iloc[r_size - 3 - days_last_year * 8].Price
        V2012 = investment.iloc[r_size - 3 - days_last_year * 7].Price
        V2013 = investment.iloc[r_size - 3 - days_last_year * 6].Price
        V2014 = investment.iloc[r_size - 3 - days_last_year * 5].Price
        V2015 = investment.iloc[r_size - 3 - days_last_year * 4].Price
        V2016 = investment.iloc[r_size - 3 - days_last_year * 3].Price
        V2017 = investment.iloc[r_size - 3 - days_last_year * 2].Price
        V2018 = investment.iloc[r_size - 3 - days_last_year].Price
        V2019 = investment.iloc[r_size - 3].Price

        hypothetical_growth = {
            'Date': [
                '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013',
                '2014', '2015', '2016', '2017', '2018', '2019'
            ],
            'Value': [
                10000, V2007, V2008, V2009, V2010, V2011, V2012, V2013, V2014,
                V2015, V2016, V2017, V2018, V2019
            ]
        }

        self.df_hypothetical_growth = pd.DataFrame(hypothetical_growth,
                                                   columns=['Date', 'Value'])

        #Overview: Figure Average Annual Performance
        annual_perf_average = {
            'Date': [lastmonth, lastyear, last3years, last5years, last10years],
            'Price': [
                average_return_last_month.Price * 252,
                average_return_last_year.Price * 252,
                average_return_last_3years.Price * 252,
                average_return_last_5years.Price * 252,
                average_return_last_10years.Price * 252
            ],
        }

        self.df_annual_perf_average = pd.DataFrame(annual_perf_average,
                                                   columns=['Date', 'Price'])

        #Overview: igure Risk Potential
        #Define quantiles for Graph
        q0 = -1.854444201294828
        q1 = -0.8269888130616426
        q2 = 0.22536003249425604
        q3 = 0.6619326773878177
        q4 = 1.1356494832642325
        SR = sharpe_ratio_last_year.Price * math.sqrt(252)

        #Define Values for Figure
        if (SR < q1):
            self.SR_q = 0.09
        elif (SR >= q1 and SR < q2):
            self.SR_q = 0.29
        elif (SR >= q2 and SR < q3):
            self.SR_q = 0.49
        elif (SR >= q3 and SR < q4):
            self.SR_q = 0.69
        elif (SR >= q4):
            self.SR_q = 0.89

        Data_Current_Statistic = {
            "Name": [
                "Price change yesterday", "Average Annual Return",
                "Average daily Volatility", "1 Year Volatilty",
                "1 Year Sharpe Ratio"
            ],
            "Numbers": [
                round(float(price_change_yesterday.values[0]), 2),
                round(average_return_all.Price * 252 * 100, 2).astype(str) +
                '%',
                round(vola_last_year.Price, 3),
                round(vola_last_year.Price * math.sqrt(252), 3),
                round(sharpe_ratio_last_year.Price * math.sqrt(252), 3)
            ]
        }

        self.df_Current_Statistic = pd.DataFrame(Data_Current_Statistic,
                                                 columns=["Name", "Numbers"])

        #Price Performance: Table Historic Prices
        Avg_price = pd.DataFrame.mean(prices)
        Data_Historic_Prices = {
            "Name": [
                "Current Price", "Price Last Year", "Average Price",
                "Year High", "Year Low"
            ],
            "Numbers": [
                prices_today.Price.iloc[0], prices_last_year.Price.iloc[0],
                Avg_price.Price, year_high.Price, year_low.Price
            ]
        }

        self.df_Historic_Prices = pd.DataFrame(Data_Historic_Prices,
                                               columns=["Name", "Numbers"])
        self.df_Historic_Prices.Numbers = round(
            self.df_Historic_Prices.Numbers, 2)

        #Price Performance: Figure Price Development
        date_data_clean = pd.DataFrame(date_data)
        date_data_clean["Prices"] = prices

        self.df_Performance_Graph = date_data_clean

        #Price Performance: Figure returns
        date_data_clean2 = pd.DataFrame(date_data)
        date_data_clean2["Returns"] = returns

        self.df_Return_Graph = date_data_clean2

        #Price Performance: Key Ratios
        Data_Key_Ratios = {
            "Name": [
                "Price Earnings Ratio",
                "Price Book Ratio",
                "Return on Equity",
                "Debt Equity Ratio",
                "Dividend Yield Ratio",
            ],
            "Numbers": [
                round(price_earnings_ratio, 2),
                round(price_book_ratio, 2),
                round(return_on_equity_ratio, 2),
                round(debt_equity_ratio * 100, 2).astype(str) + '%',
                round(dividend_yield_ratio * 100, 2).astype(str) + '%'
            ]
        }

        self.df_Key_Ratios = pd.DataFrame(Data_Key_Ratios,
                                          columns=["Name", "Numbers"])

        #Risk Measures: Table 1
        Data_Risk_Measures1 = {
            "Name": [
                "Sharpe Ratio last year", "Sharpe Ratio Total",
                "Daily Drawdown", "Max Daily Drawdown"
            ],
            "Numbers": [
                round(sharpe_ratio_last_year.Price * math.sqrt(252), 2),
                round(sharpe_ratio_all.Price * math.sqrt(r_size), 2),
                round(Daily_Drawdown.Price.iloc[-1] * 100, 2).astype(str) +
                '%',
                round(Max_Daily_Drawdown.Price.iloc[-1] * 100, 2).astype(str) +
                '%'
            ]
        }

        self.df_Risk_Measure1 = pd.DataFrame(Data_Risk_Measures1,
                                             columns=["Name", "Numbers"])

        #Risk Measures: Table 2
        Data_Risk_Measures2 = {
            "Name": [
                "Historic Value at Risk", "Simulated Value at Risk",
                "Parametic Value at Risk", "Expected Shortfall"
            ],
            "Numbers": [
                round(float(HistVar.values[0]), 4),
                round(SimVar, 4),
                round(Covar_Var.Price, 4),
                round(float(ES.values[0]), 4)
            ]
        }

        self.df_Risk_Measure2 = pd.DataFrame(Data_Risk_Measures2,
                                             columns=["Name", "Numbers"])

        #Risk Measures: Value at Risk
        data_VaR = pd.DataFrame(df_HistVar, columns=["Name"])
        data_VaR = data_VaR[::-1].reset_index()
        data_VaR = data_VaR.drop(['index'], axis=1)
        Date_VaR = pd.DataFrame(
            date_data.iloc[days_last_year:r_size]).reset_index()
        Date_VaR = Date_VaR.drop(['index'], axis=1)
        Date_VaR["Price"] = data_VaR
        self.df_VaR = Date_VaR

        #Risk Measures: Expected Shortfall
        Data_ES = pd.DataFrame(data_ES, columns=["Name"])
        Data_ES = Data_ES[::-1].reset_index()
        Data_ES = Data_ES.drop(['index'], axis=1)
        Date_ES = pd.DataFrame(
            date_data.iloc[days_last_year:r_size]).reset_index()
        Date_ES = Date_ES.drop(['index'], axis=1)
        Date_ES["Price"] = Data_ES
        self.df_ES = Date_ES

        #Risk Measures: Drawdown
        date_data_clean1 = pd.DataFrame(date_data)
        date_data_clean1["Max_DD"] = Max_Daily_Drawdown
        date_data_clean1["DD"] = Daily_Drawdown
        date_data_clean1["Roll_Max"] = Roll_Max
        self.df_Max_Daily_Drawdown = date_data_clean1

        #Technical
        b = prices.Price
        bollinger_mavg = ta.bollinger_mavg(b)
        bollinger_hband = ta.bollinger_hband(b)
        bollinger_lband = ta.bollinger_lband(b)
        bollinger_hband_indicator = ta.bollinger_hband_indicator(b)
        bollinger_lband_indicator = ta.bollinger_lband_indicator(b)

        rsi = ta.rsi(b)
        aroon_up = ta.aroon_up(b)
        aroon_down = ta.aroon_down(b)

        #Technical Analysis: Table Technical Analysis
        aroon_up_today = aroon_up.values[r_size - 2]
        aroon_down_today = aroon_down.values[r_size - 2]
        if (aroon_up_today > aroon_down_today):
            if (aroon_up_today > 50):
                aroon_text = 'The Aroon Indicator detects a current strong upwards trend'
            else:
                aroon_text = 'The Aroon Indicator detects a current weak upwards trend'
        else:
            if (aroon_down_today > 50):
                aroon_text = 'The Aroon Indicator detects a current strong downwards trend'
            else:
                aroon_text = 'The Aroon Indicator detects a current weak downwards trend'

        rsi_today = rsi.values[r_size - 2]
        if (rsi_today > 70):
            rsi_text = 'The Relative Strength Index detects a current overvaluation of the stock'
        elif (rsi_today > 30 and rsi_today < 70):
            rsi_text = 'The Relative Strength Index detects no current overvaluation or undervaluation of the stock'
        else:
            rsi_text = 'The Relative Strength Index detects a current undervaluation of the stock'

        bollinger_hband_indicator_today = bollinger_hband_indicator.values[
            r_size - 2]
        bollinger_lband_indicator_today = bollinger_lband_indicator.values[
            r_size - 2]
        if (bollinger_hband_indicator_today > bollinger_lband_indicator_today):
            bollinger_text = 'The Bollinger Band Oscillator detects that the current price is higher than the higher Bollinger Band and therefore recommends a buy of the stock'
        elif (bollinger_lband_indicator_today > 0):
            bollinger_text = 'The Bollinger Band Oscillator detects that the current price is lower than the lower Bollinger Band and therefore recommends  a selling of the stock'
        else:
            bollinger_text = 'The Bollinger Band Oscillator detects that the current price is between the lower and higher Bollinger Band and therefore recommends no trading activities in the stock'

        TechnicalAnalysis = {
            "Name": [
                "Boolinger Band:", "Relative Strength Index:",
                "Aroon Indicator:"
            ],
            "Implications": [bollinger_text, rsi_text, aroon_text]
        }

        self.df_TechnicalAnalysis = pd.DataFrame(
            TechnicalAnalysis, columns=["Name", "Implications"])

        #Technical Analyis: Figure Bollinger
        Date_Bollinger = pd.DataFrame(date_data)
        Date_Bollinger["mavg"] = bollinger_mavg
        Date_Bollinger["hband"] = bollinger_hband
        Date_Bollinger["lband"] = bollinger_lband
        self.df_BollingerBands = Date_Bollinger

        #Technical Analyis: Figure RSI
        Date_RSI = pd.DataFrame(date_data)
        Date_RSI["RSI"] = rsi

        df_RSI = Date_RSI.drop(Date_RSI.index[0:14]).reset_index()
        self.df_RSI = df_RSI.drop(['index'], axis=1)

        #Technical Analyis: Figure Aroon
        Date_aroon = pd.DataFrame(date_data)
        Date_aroon["aroon_up"] = aroon_up
        Date_aroon["aroon_down"] = aroon_down
        self.df_AroonIndicator = Date_aroon
    def getDatas(self):
        self.score = ta.rsi(self.data, self.window_size)

        return self.score
Exemple #22
0
while True:
    if datetime.now().minute % 5 == 0 and datetime.now().second % 60 == 0: 
        klines = client.get_historical_klines("BTCUSDT", Client.KLINE_INTERVAL_5MINUTE, '150 minutes ago UTC')
        tabella = DataFrame.from_records(klines)
        tabella.columns = ['DateTime','Apertura','Massimo','Minimo','Chiusura','Volume(Asset)','DataChiusura','Volume($)','9','10','11','12']
        tabella['DateTime'] = pd.to_datetime(tabella['DateTime'], unit='ms')
        tabella['DataChiusura'] = pd.to_datetime(tabella['DataChiusura'], unit='ms')
        tabella['Apertura'] = tabella['Apertura'].astype(float)
        tabella['Massimo'] = tabella['Massimo'].astype(float)
        tabella['Minimo'] = tabella['Minimo'].astype(float)
        tabella['Chiusura'] = tabella['Chiusura'].astype(float)
        tabella = tabella[['DateTime','Apertura','Massimo','Minimo','Chiusura','Volume(Asset)','Volume($)']]

        if n_indicatori == 1: 
            if indicatore1 == 'RSI':
                tabella['RSI'] = ta.rsi(tabella['Chiusura'], n=3)
            if indicatore1 == 'MACD':
                tabella['MACD'] = ta.trend.macd(tabella['Chiusura'], n_fast=12, n_slow=26, fillna=False)
            if indicatore1 == 'ADX':
                tabella['ADX'] = ta.trend.macd(tabella['Chiusura'], n_fast=12, n_slow=26, fillna=False)

        if n_indicatori == 2: 
            if indicatore1 == 'RSI' or indicatore2 == 'RSI':
                tabella['RSI'] = ta.rsi(tabella['Chiusura'], n=3)
            if indicatore1 == 'MACD' or indicatore2 == 'MACD':
                tabella['MACD'] = ta.trend.macd(tabella['Chiusura'], n_fast=12, n_slow=26, fillna=False)
            if indicatore1 == 'ADX' or indicatore2 == 'ADX':
                tabella['ADX'] = ta.trend.macd(tabella['Chiusura'], n_fast=12, n_slow=26, fillna=False)

        if n_indicatori == 3: 
            if indicatore1 == 'RSI' or indicatore2 == 'RSI' or indicatore3 == 'RSI':
    def get_trayectory(self, t_intervals):
        """
        :param t_intervals: número de intervalos en cada trayectoria
        :return: Datos con características de la trayectoria sintética y precios de cierre en bruto de al misma
        """
        trayectories = []
        closes = []
        p = True
        for i, asset in enumerate(self.context.assets):
            synthetic_return = np.exp(
                self.drift[i] + self.stdev[i] * norm.ppf(np.random.rand((t_intervals * self.frequency) + self.frequency, 1)))
            initial_close = self.close[i, -1]
            synthetic_close = np.zeros_like(synthetic_return)
            synthetic_close[0] = initial_close

            for t in range(1, synthetic_return.shape[0]):
                synthetic_close[t] = synthetic_close[t - 1] * synthetic_return[t]

            OHLC = []

            for t in range(synthetic_return.shape[0]):
                if t % self.frequency == 0 and t > 0:
                    open = synthetic_close[t - self.frequency]
                    high = np.max(synthetic_close[t - self.frequency: t])
                    low = np.min(synthetic_close[t - self.frequency: t])
                    close = synthetic_close[t]

                    OHLC.append([open, high, close, low])

            data = pd.DataFrame(data=OHLC, columns=["open", "high", "low", "close"])

            close = data.close

            if self.context.include_ha:
                ha = heikenashi(data)
                data = pd.concat((data, ha), axis=1)

            for period in [3, 6, 8, 10, 15, 20]:
                data["rsi" + str(period)] = ta.rsi(data.close, n=period, fillna=True)
                data["stoch" + str(period)] = ta.stoch(data.high, data.low, data.close, n=period, fillna=True)
                data["stoch_signal" + str(period)] = ta.stoch_signal(high=data.high,
                                                                     low=data.low,
                                                                     close=data.close,
                                                                     n=period,
                                                                     d_n=3,
                                                                     fillna=True)

                data["dpo" + str(period)] = ta.dpo(close=data.close,
                                                   n=period,
                                                   fillna=True)

                data["atr" + str(period)] = ta.average_true_range(high=data.high,
                                                                  low=data.low,
                                                                  close=data.close,
                                                                  n=period,
                                                                  fillna=True)

            for period in [6, 7, 8, 9, 10]:
                data["williams" + str(period)] = ta.wr(high=data.high,
                                                       low=data.low,
                                                       close=data.close,
                                                       lbp=period,
                                                       fillna=True)
            for period in [12, 13, 14, 15]:
                data["proc" + str(period)] = ta.trix(close=data.close,
                                                     n=period,
                                                     fillna=True)

            data["macd_diff"] = ta.macd_diff(close=data.close,
                                             n_fast=15,
                                             n_slow=30,
                                             n_sign=9,
                                             fillna=True)

            data["macd_signal"] = ta.macd_signal(close=data.close,
                                                 n_fast=15,
                                                 n_slow=30,
                                                 n_sign=9,
                                                 fillna=True)

            data["bb_high_indicator"] = ta.bollinger_hband_indicator(close=data.close,
                                                                     n=15,
                                                                     ndev=2,
                                                                     fillna=True)

            data["bb_low_indicator"] = ta.bollinger_lband_indicator(close=data.close,
                                                                    n=15,
                                                                    ndev=2,
                                                                    fillna=True)

            data["dc_high_indicator"] = ta.donchian_channel_hband_indicator(close=data.close,
                                                                            n=20,
                                                                            fillna=True)

            data["dc_low_indicator"] = ta.donchian_channel_lband_indicator(close=data.close,
                                                                           n=20,
                                                                           fillna=True)

            data["ichimoku_a"] = ta.ichimoku_a(high=data.high,
                                               low=data.low,
                                               n1=9,
                                               n2=26,
                                               fillna=True)

            data.fillna(method="bfill")

            # Normalizar los valores
            for feature in data.columns:
                norm_feature = preprocessing.normalize(data[feature].values.reshape(-1, 1), axis=0)
                data[feature] = pd.DataFrame(data=norm_feature, index=data.index, columns=[feature])

            self.assets = data.columns

            trayectories.append(data.values)
            closes.append(close)

        return np.array(trayectories), np.array(closes)
Exemple #24
0
def addTechnicalAnalysisIndicators(df):
	df['rsi'] = ta.rsi(close, n=14)
	df['obv'] = ta.on_balance_volume(close, volume, fillna=False)
	return df