Пример #1
0
def CCI(df0, n=160):
    df = df0
    df['cci'] = ema_indicator(cci(df['high'],
                                  df['low'],
                                  df['close'],
                                  n,
                                  0.015,
                                  fillna=False),
                              4,
                              fillna=False)
    return df
Пример #2
0
 def test_cci(self):
     target = 'CCI'
     result = cci(high=self._df['High'],
                  low=self._df['Low'],
                  close=self._df['Close'],
                  n=20,
                  c=0.015,
                  fillna=False)
     pd.testing.assert_series_equal(self._df[target].tail(),
                                    result.tail(),
                                    check_names=False)
Пример #3
0
def CCI(df, intervals):
    """
        Commodity Channel Index: Measures the current price level relative to an average price level over a given period of time.
        CCI is high when prices are far above their average and low when prices are below their average
        Reference: https://www.investopedia.com/articles/active-trading/031914/how-traders-can-utilize-cci-commodity-channel-index-trade-stock-trends.asp
    """
    from ta.trend import cci
    from tqdm.auto import tqdm

    for interval in tqdm(intervals):
        df['cci_' + str(interval)] = cci(df['high'],
                                         df['low'],
                                         df['close'],
                                         interval,
                                         fillna=True)
Пример #4
0
def comm_channel(datos, start, end = '', window = 10, factorC = 0.015):
    '''
    ENTRADA
    datos: Pandas dataframe que contiene al menos una columna de fechas (DATE) y otra
    columna numérica

    start, end: strings en formato 'YYYY-MM-DD' representando la fecha de inicio
    y la fecha final respectivamente

    window: Entero que representa la ventan de tiempo a utilizar

    factorC: Real (ver la teoría de este indicador)

    SALIDA
    resultado: Dataframe datos con una columna extra conteniendo la información
    del indicador
    '''
    #Localiza la fecha de inicio y revisa si hay suficiente información
    indiceInicio=datos[datos['Date']==start].index[0]
    if window > indiceInicio + 1:
        print 'No hay suficiente historia para esta fecha'
        return datos

    #Último índice
    if end=='':
        lastIndex=datos.shape[0] - 1
    else:
        lastIndex=datos[datos['Date']==end].index[0]

    #calcula el indicador
    indicador = cci(datos['High'], datos['Low'], datos['Adj Close'], window, factorC)

    #agrega la nueva columna
    resultado = deepcopy(datos)
    resName = 'Comm-Chan-' + str(window) + '-' + str(factorC)
    resultado[resName] = indicador

    #Filtra a partir del índice correspondiente a la fecha start
    resultado=resultado.iloc[indiceInicio:lastIndex+1,:]
    resultado=resultado.reset_index(drop=True)

    #añade metadatos
    resultado.tipo = 'comm-chan'
    resultado.resName = resName

    return resultado
Пример #5
0
        def cci_cb_pressed(stock_analysis_tool: QMainWindow,
                           cb: QCheckBox) -> None:
            """

            :param cb:
            :return:
            """
            if cb.isChecked():
                # Add CCI to Display Graph
                stock_analysis_tool.df['cci'] = cci(
                    close=stock_analysis_tool.df['close'],
                    low=stock_analysis_tool.df['low'],
                    high=stock_analysis_tool.df['high'],
                    n=stock_analysis_tool.cci_n)
                stock_analysis_tool.add_column_to_graph(column_name='cci')
            else:
                # Remove CCI from Display Graph
                stock_analysis_tool.remove_column_from_graph(column_name='cci')
                stock_analysis_tool.df = stock_analysis_tool.df.drop("cci",
                                                                     axis=1)
    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
Пример #7
0
def engineer_data_over_single_interval(df: pd.DataFrame,
                                       indicators: list,
                                       ticker: str = "",
                                       rsi_n: int = 14,
                                       cmo_n: int = 7,
                                       macd_fast: int = 12,
                                       macd_slow: int = 26,
                                       macd_sign: int = 9,
                                       roc_n: int = 12,
                                       cci_n: int = 20,
                                       dpo_n: int = 20,
                                       cmf_n: int = 20,
                                       adx_n: int = 14,
                                       mass_index_low: int = 9,
                                       mass_index_high: int = 25,
                                       trix_n: int = 15,
                                       stochastic_oscillator_n: int = 14,
                                       stochastic_oscillator_sma_n: int = 3,
                                       ultimate_oscillator_short_n: int = 7,
                                       ultimate_oscillator_medium_n: int = 14,
                                       ultimate_oscillator_long_n: int = 28,
                                       ao_short_n: int = 5,
                                       ao_long_n: int = 34,
                                       kama_n: int = 10,
                                       tsi_high_n: int = 25,
                                       tsi_low_n: int = 13,
                                       eom_n: int = 14,
                                       force_index_n: int = 13,
                                       ichimoku_low_n: int = 9,
                                       ichimoku_medium_n: int = 26):
    from ta.momentum import rsi, wr, roc, ao, stoch, uo, kama, tsi
    from ta.trend import macd, macd_signal, cci, dpo, adx, mass_index, trix, ichimoku_a
    from ta.volume import chaikin_money_flow, acc_dist_index, ease_of_movement, force_index

    # Momentum Indicators
    if Indicators.RELATIVE_STOCK_INDEX in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.RELATIVE_STOCK_INDEX.value +
                           " for stock " + ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.RELATIVE_STOCK_INDEX.value] = rsi(close=df['close'],
                                                        n=rsi_n)

    if Indicators.WILLIAMS_PERCENT_RANGE in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.WILLIAMS_PERCENT_RANGE.value +
                           " for stock " + ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.WILLIAMS_PERCENT_RANGE.value] = wr(
            df['high'], df['low'], df['close'])

    if Indicators.CHANDE_MOMENTUM_OSCILLATOR in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.CHANDE_MOMENTUM_OSCILLATOR.value +
                           " for stock " + ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.CHANDE_MOMENTUM_OSCILLATOR.
           value] = chande_momentum_oscillator(close_data=df['close'],
                                               period=cmo_n)

    if Indicators.RATE_OF_CHANGE in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.RATE_OF_CHANGE.value + " for stock " +
                           ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.RATE_OF_CHANGE.value] = roc(close=df['close'], n=roc_n)

    if Indicators.STOCHASTIC_OSCILLATOR in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.STOCHASTIC_OSCILLATOR.value +
                           " for stock " + ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.STOCHASTIC_OSCILLATOR.value] = stoch(
            high=df['high'],
            low=df['low'],
            close=df['close'],
            n=stochastic_oscillator_n,
            d_n=stochastic_oscillator_sma_n)

    if Indicators.ULTIMATE_OSCILLATOR in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.ULTIMATE_OSCILLATOR.value +
                           " for stock " + ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.ULTIMATE_OSCILLATOR.value] = uo(
            high=df['high'],
            low=df['low'],
            close=df['close'],
            s=ultimate_oscillator_short_n,
            m=ultimate_oscillator_medium_n,
            len=ultimate_oscillator_long_n)

    if Indicators.AWESOME_OSCILLATOR in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.AWESOME_OSCILLATOR.value +
                           " for stock " + ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.AWESOME_OSCILLATOR.value] = ao(high=df['high'],
                                                     low=df['low'],
                                                     s=ao_short_n,
                                                     len=ao_long_n)

    if Indicators.KAUFMAN_ADAPTIVE_MOVING_AVERAGE in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.KAUFMAN_ADAPTIVE_MOVING_AVERAGE.value +
                           " for stock " + ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.KAUFMAN_ADAPTIVE_MOVING_AVERAGE.value] = kama(
            close=df['close'], n=kama_n)

    if Indicators.TRUE_STRENGTH_INDEX in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.TRUE_STRENGTH_INDEX.value +
                           " for stock " + ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.TRUE_STRENGTH_INDEX.value] = tsi(close=df['close'],
                                                       r=tsi_high_n,
                                                       s=tsi_low_n)

    # Trend Indicator
    if Indicators.MOVING_AVERAGE_CONVERGENCE_DIVERGENCE in indicators:
        Logger.console_log(
            message="Calculating " +
            Indicators.MOVING_AVERAGE_CONVERGENCE_DIVERGENCE.value +
            " for stock " + ticker,
            status=Logger.LogStatus.EMPHASIS)
        df[Indicators.MOVING_AVERAGE_CONVERGENCE_DIVERGENCE.value] = macd(close=df['close'],
                                                                          n_slow=macd_slow,
                                                                          n_fast=macd_fast) - \
                                                                     macd_signal(close=df['close'],
                                                                                 n_slow=macd_slow,
                                                                                 n_fast=macd_fast,
                                                                                 n_sign=macd_sign)

    if Indicators.COMMODITY_CHANNEL_INDEX in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.COMMODITY_CHANNEL_INDEX.value +
                           " for stock " + ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.COMMODITY_CHANNEL_INDEX.value] = cci(high=df['high'],
                                                           low=df['low'],
                                                           close=df['close'],
                                                           n=cci_n)

    if Indicators.DETRENDED_PRICE_OSCILLATOR in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.DETRENDED_PRICE_OSCILLATOR.value +
                           " for stock " + ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.DETRENDED_PRICE_OSCILLATOR.value] = dpo(
            close=df['close'], n=dpo_n)

    if Indicators.AVERAGE_DIRECTIONAL_INDEX in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.AVERAGE_DIRECTIONAL_INDEX.value +
                           " for stock " + ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.AVERAGE_DIRECTIONAL_INDEX.value] = adx(high=df['high'],
                                                             low=df['low'],
                                                             close=df['close'],
                                                             n=adx_n)

    if Indicators.MASS_INDEX in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.MASS_INDEX.value + " for stock " +
                           ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.MASS_INDEX.value] = mass_index(high=df['high'],
                                                     low=df['low'],
                                                     n=mass_index_low,
                                                     n2=mass_index_high)

    if Indicators.TRIPLE_EXPONENTIALLY_SMOOTHED_MOVING_AVERAGE in indicators:
        Logger.console_log(
            message="Calculating " +
            Indicators.TRIPLE_EXPONENTIALLY_SMOOTHED_MOVING_AVERAGE.value +
            " for stock " + ticker,
            status=Logger.LogStatus.EMPHASIS)
        df[Indicators.TRIPLE_EXPONENTIALLY_SMOOTHED_MOVING_AVERAGE.
           value] = trix(close=df['close'], n=trix_n)

    if Indicators.ICHIMOKU_A in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.ICHIMOKU_A.value + " for stock " +
                           ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.ICHIMOKU_A.value] = ichimoku_a(high=df['high'],
                                                     low=df['low'],
                                                     n1=ichimoku_low_n,
                                                     n2=ichimoku_medium_n)

    # Volume Indicator
    if Indicators.CHAIKIN_MONEY_FLOW in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.CHAIKIN_MONEY_FLOW.value +
                           " for stock " + ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.CHAIKIN_MONEY_FLOW.value] = chaikin_money_flow(
            high=df['high'],
            low=df['low'],
            close=df['close'],
            volume=df['volume'],
            n=cmf_n)

    if Indicators.ACCUMULATION_DISTRIBUTION_INDEX in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.ACCUMULATION_DISTRIBUTION_INDEX.value +
                           " for stock " + ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.ACCUMULATION_DISTRIBUTION_INDEX.value] = acc_dist_index(
            high=df['high'],
            low=df['low'],
            close=df['close'],
            volume=df['volume'])

    if Indicators.EASE_OF_MOVEMENT in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.EASE_OF_MOVEMENT.value + " for stock " +
                           ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.EASE_OF_MOVEMENT.value] = ease_of_movement(
            high=df['high'], low=df['low'], volume=df['volume'], n=eom_n)

    if Indicators.FORCE_INDEX in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.FORCE_INDEX.value + " for stock " +
                           ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.FORCE_INDEX.value] = force_index(close=df['close'],
                                                       volume=df['volume'],
                                                       n=force_index_n)
Пример #8
0
 def test_cci(self):
     target = 'CCI'
     result = cci(**self._params)
     pd.testing.assert_series_equal(self._df[target].tail(),
                                    result.tail(),
                                    check_names=False)
 def cci(self, high, low, close):
     cci = tat.cci(high=high, low=low, close=close).to_numpy()
     return cci
Пример #10
0
def bar():

    history = fx.get_history(instrument=symbol,
                             timeframe="m1",
                             quotes_count=300)
    # print (history)
    if history.size != 0:
        df = pd.DataFrame(history)
        df = df[[
            'Date',
            'BidOpen',
            'BidHigh',
            'BidLow',
            'BidClose',
            'Volume',
        ]]
        df.rename(columns={
            'Date': "datetime",
            'BidOpen': "open",
            "BidHigh": "high",
            "BidLow": "low",
            "BidClose": "close",
            'Volume': "volume",
        },
                  inplace=True)

        df['ema_f_h'] = trend.ema(df.high, periods=34)
        df['ema_f_c'] = trend.ema(df.close, periods=34)
        df['ema_f_l'] = trend.ema(df.low, periods=34)
        df['ema_s_h'] = trend.ema(df.high, periods=144)
        df['ema_s_c'] = trend.ema(df.close, periods=144)
        df['ema_s_l'] = trend.ema(df.low, periods=144)
        df['ema_across'] = np.where(df.ema_f_c > df.ema_s_c, int(1),
                                    int(-1))  # 上穿1,下穿-1
        # MACD(df, fast=55, slow=144, n=55)
        df["macd"] = trend.MACD(df.close, n_slow=144, n_fast=34,
                                n_sign=34).macd()
        df["macd_signal"] = trend.MACD(df.close,
                                       n_slow=144,
                                       n_fast=34,
                                       n_sign=34).macd_signal()
        df['macd_across'] = np.where(df.macd > df.macd_signal, int(1),
                                     int(-1))  # 上穿1,下穿-1

        df['rsi'] = momentum.rsi(
            df.close,
            n=34,
        )
        df['emarsi'] = trend.ema(df.rsi, periods=34)
        df['rsi_postion'] = np.where(df.rsi > df.emarsi, int(1),
                                     int(-1))  # 上穿1,下穿-1

        # df['stoch'] = momentum.stoch(high=df["high"],low=df["low"],close=df["close"],n=144)
        # df['stoch_signal'] = momentum.stoch_signal(high=df["high"],low=df["low"],close=df["close"],n=144)
        # df["stoch_sig"] = np.where(df["stoch"] > df["stoch_signal"], 1, 0)
        # df["stoch_sig_shfit"] = df["stoch_sig"].shift(1)

        df['cci'] = trend.cci(
            df.high,
            df.low,
            df.close,
            n=55,
        )
        df['emacci'] = trend.ema(df.cci, periods=55)
        df['cci_postion'] = np.where(df.cci > df.emacci, int(1),
                                     int(-1))  # 上穿1,下穿-1

        # 价格为于快线与慢线之上则为1,快慢线之下则为-1,其它为0
        df["close_postion"] = np.where(
            (df['close'] > df['ema_f_c']) & (df['close'] > df['ema_s_c']),
            int(1),
            np.where(
                (df['close'] < df['ema_f_c']) & (df['close'] < df['ema_s_c']),
                int(-1), int(0)))
        return df
Пример #11
0
                df['rsi'] = momentum.rsi(
                    df.close,
                    n=34,
                )
                df['emarsi'] = trend.ema(df.rsi, periods=34)
                df['rsi_postion'] = np.where(df.rsi > df.emarsi, int(1),
                                             int(-1))  # 上穿1,下穿-1

                # df['stoch'] = momentum.stoch(high=df["high"],low=df["low"],close=df["close"],n=144)
                # df['stoch_signal'] = momentum.stoch_signal(high=df["high"],low=df["low"],close=df["close"],n=144)
                # df["stoch_sig"] = np.where(df["stoch"] > df["stoch_signal"], 1, 0)
                # df["stoch_sig_shfit"] = df["stoch_sig"].shift(1)

                df['cci'] = trend.cci(
                    df.high,
                    df.low,
                    df.close,
                    n=55,
                )
                df['emacci'] = trend.ema(df.cci, periods=55)
                df['cci_postion'] = np.where(df.cci > df.emacci, int(1),
                                             int(-1))  # 上穿1,下穿-1

                # 价格为于快线与慢线之上则为1,快慢线之下则为-1,其它为0
                df["close_postion"] = np.where(
                    (df['close'] > df['ema_f_c']) &
                    (df['close'] > df['ema_s_c']), int(1),
                    np.where((df['close'] < df['ema_f_c']) &
                             (df['close'] < df['ema_s_c']), int(-1), int(0)))

                # if df.iloc[-1]["macd_across"] != df.iloc[-2]["macd_across"]:
                #     if df.iloc[-1]["macd_across"] ==1:
Пример #12
0
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)