예제 #1
0
    def acceptCandle(self, candle):
        '''
        accepts a candle and updates current state of strategy to determine buy/sell
        '''
        self.addCandle(candle)

        macd = MACD(self.candleDf['C'])

        # print(macd.macd().iloc[-1], macd.macd_signal().iloc[-1], macd.macd_diff().iloc[-1], macd.macd().iloc[-1] - macd.macd_signal().iloc()[-1])

        if macd.macd_diff().iloc[-1] >= 0 and macd.macd_diff().iloc[-2] < 0:
            self.buy(0.05 * self.capital)
        elif macd.macd_diff().iloc[-1] <= 0 and macd.macd_diff().iloc[-2] > 0:
            self.sell()
    def __init__(self):
        dfr['EMA_12'] = EMAIndicator(close=dfr['close'], n=9,
                                     fillna=True).ema_indicator()
        dfr['EMA_26'] = EMAIndicator(close=dfr['close'], n=26,
                                     fillna=True).ema_indicator()

        MACD = MACD(close=dfr['close'])
        dfr['MACD'] = dfr['EMA_12'] - dfr['EMA_26']
        dfr['MACD2'] = MACD.macd()
        dfr['MACD_Signal'] = EMAIndicator(close=dfr['MACD'],
                                          n=9).ema_indicator()
        dfr['MACD_Signal2'] = MACD.macd_signal()
        dfr['MACD_HIST'] = dfr['MACD'] - dfr['MACD_Signal']
        dfr['MACD_HIST2'] = MACD.macd_diff()

        new_col = 'MACD_HIST_TYPE'
        new_col2 = 'MACD_HIST_TYPE2'
        nr = dfr.shape[0]
        dfr[new_col] = np.empty(nr)
        for k in range(1, nr):
            i1 = dfr.index.values[k - 1]
            i = dfr.index.values[k]
            if dfr.loc[i, 'MACD_HIST'] > 0 and dfr.loc[i1, 'MACD_HIST'] < 0:
                dfr.loc[i, new_col] = 1  # Cross over
                dfr.loc[i, new_col2] = 1  # Cross over
                if i not in long_asset_list.keys():
                    tlist = []
                    tlist.append(table_name)
                    long_asset_list[i] = tlist

                elif dfr.loc[i, 'MACD_HIST'] > 0 and dfr.loc[
                        i, 'MACD_HIST'] > dfr.loc[i1, 'MACD_HIST']:
                    dfr.loc[i, new_col] = 2  # Col grow above
                    dfr.loc[i, new_col2] = 2  # Cross over
                elif dfr.loc[i, 'MACD_HIST'] > 0 and dfr.loc[
                        i, 'MACD_HIST'] < dfr.loc[i1, 'MACD_HIST']:
                    dfr.loc[i, new_col] = 3  # Col fall above
                    dfr.loc[i, new_col2] = 3  # Cross over
                elif dfr.loc[i, 'MACD_HIST'] < 0 and dfr.loc[i1,
                                                             'MACD_HIST'] > 0:
                    a = (i, table_name)
                    dfr.loc[i, new_col] = -1  # Cross over
                    dfr.loc[i, new_col2] = -1  # Cross over
                    if i not in short_asset_list.keys():
                        tlist = []
                        tlist.append(table_name)
                        short_asset_list[i] = tlist
                    else:
                        short_asset_list[i].append(table_name)
                elif dfr.loc[i, 'MACD_HIST'] < 0 and dfr.loc[
                        i, 'MACD_HIST'] < dfr.loc[i1, 'MACD_HIST']:
                    dfr.loc[i, new_col] = -2  # Col fall above
                    dfr.loc[i, new_col2] = -2  # Cross over
                elif dfr.loc[i, 'MACD_HIST'] < 0 and dfr.loc[
                        i, 'MACD_HIST'] > dfr.loc[i1, 'MACD_HIST']:
                    dfr.loc[i, new_col] = -3  # Cross under
                    dfr.loc[i, new_col2] = -3  # Cross over
                else:
                    dfr.loc[i, new_col] = 0
                    dfr.loc[i, new_col2] = 0  # Cross over
예제 #3
0
    def init(self, base_data):
        base_data = base_data.sort_values("date")

        macd = MACD(close=base_data["close"], n_slow=26, n_fast=12, n_sign=9)

        base_data["macd_diff"] = macd.macd_diff()
        base_data["macd_signal"] = macd.macd_signal()

        base_data["fs_dif"] = base_data["macd_diff"] - base_data["macd_signal"]
        base_data["bool_signal"] = base_data["fs_dif"].map(
            lambda x: 1 if x > 0 else -1
        )
        base_data["bool_signal_shift1"] = base_data["bool_signal"].shift(1)

        base_data["signal"] = 0
        base_data.loc[
            (
                (base_data["bool_signal"] > 0)
                & (base_data["bool_signal_shift1"] < 0)
            ),
            "signal",
        ] = 1
        base_data.loc[
            (
                (base_data["bool_signal"] < 0)
                & (base_data["bool_signal_shift1"] > 0)
            ),
            "signal",
        ] = -1

        base_data.index = range(len(base_data))
        return base_data
 def get_MACD_Indicator(self, col='Close', fillna=False):
     """
     get MACD Indicator
     """
     stock_MACD = MACD(self.df[col], fillna=fillna)
     self.df['MACD'] = stock_MACD.macd()
     self.df['MACD_signal'] = stock_MACD.macd_signal()
     self.df['MACD_diff'] = stock_MACD.macd_diff()
예제 #5
0
    def acceptCandle(self, candle):
        '''
        accepts a candle and updates current state of strategy to determine buy/sell
        '''
        self.addCandle(candle)

        macd = MACD(self.candleDf['C'], 20, 6, 5)
        rsi = RSIIndicator(self.candleDf['C'], 8)

        prevRsi = rsi.rsi().iloc[-2]
        currentRsi = rsi.rsi().iloc[-1]

        # print(macd.macd().iloc[-1], macd.macd_signal().iloc[-1], macd.macd_diff().iloc[-1], macd.macd().iloc[-1] - macd.macd_signal().iloc()[-1])

        if macd.macd_diff().iloc[-1] >= 0 and macd.macd_diff().iloc[-2] < 0\
            and currentRsi >= self.oversold and prevRsi < self.oversold:
            self.buy(0.05 * self.capital)
        elif macd.macd_diff().iloc[-1] <= 0 and macd.macd_diff().iloc[-2] > 0\
            and currentRsi <= self.overbought and prevRsi > self.overbought:
            self.sell()
예제 #6
0
def ta_macd(df):
    """
    Moving Average Convergence Divergence (MACD) calculation.
    :param df: pandas dataframe
    :return: pandas dataframe
    """
    temp_df = df.copy()
    temp = MACD(close=temp_df["Close"], fillna=False)
    # temp = MACD(close=temp_df["Close"], window_slow=26, window_fast=12, window_sign=9, fillna=True)
    temp_df["macd"] = temp.macd()
    temp_df["macd_diff"] = temp.macd_diff()
    temp_df["macd_signal"] = temp.macd_signal()
    return temp_df
예제 #7
0
 def action(self, indicator):
     # Derive the action based on past data
     # action: 1 means buy, -1 means sell, 0 means do nothing
     close = indicator['c']
     macd = MACD(close=close,
                n_slow=self.parameters['ema26'],
                n_fast=self.parameters['ema12'],
                n_sign=self.parameters['ema9'])
     indicator['trend_macd'] = macd.macd()
     indicator['trend_macd_signal'] = macd.macd_signal()
     indicator['trend_macd_diff'] = macd.macd_diff()
     indicator['trend_macd_diff_prev'] = indicator['trend_macd_diff'].shift(1)
     indicator['action'] = (np.sign(indicator['trend_macd_diff']) \
                                 - np.sign(indicator['trend_macd_diff_prev'])) / 2
예제 #8
0
def get_macd(config, company):
    close_prices = company.prices
    dataframe = company.technical_indicators
    window_slow = 26
    signal = 9
    window_fast = 12
    macd = MACD(company.prices, window_slow, window_fast, signal)
    dataframe['MACD'] = macd.macd()
    dataframe['MACD_Histogram'] = macd.macd_diff()
    dataframe['MACD_Signal'] = macd.macd_signal()

    generate_buy_sell_signals(
        lambda x, dataframe: dataframe['MACD'].values[x] < dataframe[
            'MACD_Signal'].iloc[x], lambda x, dataframe: dataframe['MACD'].
        values[x] > dataframe['MACD_Signal'].iloc[x], dataframe, 'MACD')
    return dataframe
예제 #9
0
 def action(self, indicator):
     # Derive the action based on past data
     # action: 1 means buy, -1 means sell, 0 means do nothing
     close = indicator["c"]
     macd = MACD(
         close=close,
         n_slow=self.parameters["ema26"],
         n_fast=self.parameters["ema12"],
         n_sign=self.parameters["ema9"],
     )
     indicator["trend_macd"] = macd.macd()
     indicator["trend_macd_signal"] = macd.macd_signal()
     indicator["trend_macd_diff"] = macd.macd_diff()
     indicator["trend_macd_diff_prev"] = indicator["trend_macd_diff"].shift(
         1)
     indicator["action"] = (np.sign(indicator["trend_macd_diff"]) -
                            np.sign(indicator["trend_macd_diff_prev"])) / 2
예제 #10
0
    def get_signal(self, input_df, ticker, run_id):
        df = input_df.copy()

        indicator_macd = MACD(
            close=df["Close"],
            window_slow=self.indicator["window_slow"],
            window_fast=self.indicator["window_fast"],
            window_sign=self.indicator["window_sign"],
            fillna=self.indicator["fillna"],
        )

        # Add Bollinger Bands features
        df["macd"] = indicator_macd.macd()
        df["macd_signal"] = indicator_macd.macd_signal()
        df["macd_diff"] = indicator_macd.macd_diff()

        previous_row = df.iloc[-2]
        row = df.iloc[-1]

        if (row.macd_diff.item() < 0) and (previous_row.macd_diff.item() > 0):
            sell_signal = {
                "ticker": ticker,
                "datetime": row.Date,
                "indicator": self.name,
                "param": self.param,
                "reason": "MACD Downward Crossover",
                "image": self.draw_image(df, ticker, run_id),
            }
        else:
            sell_signal = None

        if (previous_row.macd_diff.item() < 0) and (row.macd_diff.item() > 0):
            buy_signal = {
                "ticker": ticker,
                "datetime": row.Date,
                "indicator": self.name,
                "param": self.param,
                "reason": "MACD Upward Crossover",
                "image": self.draw_image(df, ticker, run_id),
            }
        else:
            buy_signal = None

        return buy_signal, sell_signal
예제 #11
0
 def create_trade_sign(self, stock_price: pd.DataFrame) -> pd.DataFrame:
     stock_price = stock_price.sort_values("date")
     macd = MACD(close=stock_price["close"], n_slow=26, n_fast=12, n_sign=9)
     stock_price["macd_diff"] = macd.macd_diff()
     stock_price["macd_signal"] = macd.macd_signal()
     stock_price["fs_dif"] = (stock_price["macd_diff"] -
                              stock_price["macd_signal"])
     stock_price["bool_signal"] = stock_price["fs_dif"].map(
         lambda x: 1 if x > 0 else -1)
     stock_price["bool_signal_shift1"] = stock_price["bool_signal"].shift(1)
     stock_price["signal"] = 0
     stock_price.loc[((stock_price["bool_signal"] > 0)
                      & (stock_price["bool_signal_shift1"] < 0)),
                     "signal", ] = 1
     stock_price.loc[((stock_price["bool_signal"] < 0)
                      & (stock_price["bool_signal_shift1"] > 0)),
                     "signal", ] = -1
     stock_price.index = range(len(stock_price))
     return stock_price
예제 #12
0
 def create_trade_sign(self, stock_price: pd.DataFrame) -> pd.DataFrame:
     stock_price = stock_price.sort_values("date")
     macd = MACD(close=stock_price["close"], n_slow=26, n_fast=12, n_sign=9)
     stock_price["DIF"] = macd.macd_diff()
     stock_price["MACD"] = macd.macd_signal()
     stock_price["OSC"] = stock_price["DIF"] - stock_price["MACD"]
     stock_price["OSC_signal"] = stock_price["OSC"].map(lambda x: 1
                                                        if x > 0 else -1)
     stock_price["OSC_signal_yesterday"] = stock_price["OSC_signal"].shift(
         1)
     stock_price["signal"] = 0
     stock_price.loc[((stock_price["OSC_signal"] > 0)
                      & (stock_price["OSC_signal_yesterday"] < 0)),
                     "signal", ] = 1  # 下而上穿過
     stock_price.loc[((stock_price["OSC_signal"] < 0)
                      & (stock_price["OSC_signal_yesterday"] > 0)),
                     "signal", ] = -1  # 上而下穿過
     stock_price.index = range(len(stock_price))
     return stock_price
예제 #13
0
def add_trend_indicators(data: pd.DataFrame) -> pd.DataFrame:
    """Adds the trend indicators.

    Parameters
    ----------
    data : pd.DataFrame
        A dataframe with daily stock values. Must include: open, high,
        low, close and volume. It should also be sorted in a descending
        manner.

    Returns
    -------
    pd.DataFrame
        The input dataframe with the indicators added.
    """
    adx = ADXIndicator(data['high'], data['low'], data['close'])
    ema = EMAIndicator(data['close'])
    ema_200 = EMAIndicator(data['close'], n=200)
    ichimoku = IchimokuIndicator(data['high'], data['low'])
    macd = MACD(data['close'])
    sma = SMAIndicator(data['close'], n=14)
    sma_200 = SMAIndicator(data['close'], n=200)

    data.loc[:, 'adx'] = adx.adx()
    data.loc[:, 'adx_pos'] = adx.adx_pos()
    data.loc[:, 'adx_neg'] = adx.adx_neg()
    data.loc[:, 'ema'] = ema.ema_indicator()
    data.loc[:, 'ema_200'] = ema_200.ema_indicator()
    data.loc[:, 'ichimoku_a'] = ichimoku.ichimoku_a()
    data.loc[:, 'ichimoku_b'] = ichimoku.ichimoku_b()
    data.loc[:, 'ichimoku_base_line'] = ichimoku.ichimoku_base_line()
    data.loc[:, 'ichimoku_conversion_line'] = (
        ichimoku.ichimoku_conversion_line())
    data.loc[:, 'macd'] = macd.macd()
    data.loc[:, 'macd_diff'] = macd.macd_diff()
    data.loc[:, 'macd_signal'] = macd.macd_signal()
    data.loc[:, 'sma'] = sma.sma_indicator()
    data.loc[:, 'sma_200'] = sma_200.sma_indicator()

    return data
예제 #14
0
def macd(df):
    indicator_macd = MACD(close=df["Close"])
    df['macd'] = indicator_macd.macd()
    df['macd_diff'] = indicator_macd.macd_diff()
    df['macd_signal'] = indicator_macd.macd_signal()
예제 #15
0
 def _macd(self, df, close):
     macd = MACD(close=close)
     df['macd'] = macd.macd()
     df['macd_signal'] = macd.macd_signal()
     df['macd_diff'] = macd.macd_diff()
예제 #16
0
    def handle(self, *args, **options):
        # import pdb
        # pdb.set_trace()
        if not options['update']:
            NSETechnical.objects.all().delete()
        symbols = Symbol.objects.all()
        for symbol in symbols:
            nse_history_data = NSEHistoricalData.objects.filter(
                symbol__symbol_name=symbol).order_by('timestamp')
            if not nse_history_data:
                continue
            nse_technical = pd.DataFrame(
                list(
                    nse_history_data.values('timestamp', 'open', 'high', 'low',
                                            'close', 'total_traded_quantity')))
            '''
                Moving average convergence divergence
            '''
            indicator_macd = MACD(close=nse_technical['close'],
                                  window_slow=26,
                                  window_fast=12,
                                  window_sign=9,
                                  fillna=False)
            nse_technical["trend_macd"] = indicator_macd.macd()
            nse_technical["trend_macd_signal"] = indicator_macd.macd_signal()
            nse_technical["trend_macd_diff"] = indicator_macd.macd_diff()
            '''
                Simple Moving Average
            '''
            nse_technical["trend_sma_fast"] = SMAIndicator(
                close=nse_technical['close'], window=12,
                fillna=False).sma_indicator()
            nse_technical["trend_sma_slow"] = SMAIndicator(
                close=nse_technical['close'], window=26,
                fillna=False).sma_indicator()
            '''
                Exponential Moving Average
            '''
            nse_technical["trend_ema_fast"] = EMAIndicator(
                close=nse_technical['close'], window=12,
                fillna=False).ema_indicator()
            nse_technical["trend_ema_slow"] = EMAIndicator(
                close=nse_technical['close'], window=26,
                fillna=False).ema_indicator()
            '''
                Ichimoku Indicator
            '''
            indicator_ichi = IchimokuIndicator(
                high=nse_technical['high'],
                low=nse_technical['low'],
                window1=9,
                window2=26,
                window3=52,
                visual=False,
                fillna=False,
            )
            nse_technical[
                "trend_ichimoku_conv"] = indicator_ichi.ichimoku_conversion_line(
                )
            nse_technical[
                "trend_ichimoku_base"] = indicator_ichi.ichimoku_base_line()
            nse_technical["trend_ichimoku_a"] = indicator_ichi.ichimoku_a()
            nse_technical["trend_ichimoku_b"] = indicator_ichi.ichimoku_b()
            indicator_ichi_visual = IchimokuIndicator(
                high=nse_technical['high'],
                low=nse_technical['low'],
                window1=9,
                window2=26,
                window3=52,
                visual=True,
                fillna=False,
            )
            nse_technical[
                "trend_visual_ichimoku_a"] = indicator_ichi_visual.ichimoku_a(
                )
            nse_technical[
                "trend_visual_ichimoku_b"] = indicator_ichi_visual.ichimoku_b(
                )
            '''
                Bollinger Band
            '''
            indicator_bb = BollingerBands(close=nse_technical['close'],
                                          window=20,
                                          window_dev=2,
                                          fillna=False)
            nse_technical["volatility_bbm"] = indicator_bb.bollinger_mavg()
            nse_technical["volatility_bbh"] = indicator_bb.bollinger_hband()
            nse_technical["volatility_bbl"] = indicator_bb.bollinger_lband()
            nse_technical["volatility_bbw"] = indicator_bb.bollinger_wband()
            nse_technical["volatility_bbp"] = indicator_bb.bollinger_pband()
            nse_technical[
                "volatility_bbhi"] = indicator_bb.bollinger_hband_indicator()
            nse_technical[
                "volatility_bbli"] = indicator_bb.bollinger_lband_indicator()
            '''
                Accumulation Distribution Index
            '''
            nse_technical["volume_adi"] = AccDistIndexIndicator(
                high=nse_technical['high'],
                low=nse_technical['low'],
                close=nse_technical['close'],
                volume=nse_technical['total_traded_quantity'],
                fillna=False).acc_dist_index()
            '''
                Money Flow Index
            '''
            nse_technical["volume_mfi"] = MFIIndicator(
                high=nse_technical['high'],
                low=nse_technical['low'],
                close=nse_technical['close'],
                volume=nse_technical['total_traded_quantity'],
                window=14,
                fillna=False,
            ).money_flow_index()
            '''
                Relative Strength Index (RSI)
            '''
            nse_technical["momentum_rsi"] = RSIIndicator(
                close=nse_technical['close'], window=14, fillna=False).rsi()
            '''
                Stoch RSI (StochRSI)
            '''
            indicator_srsi = StochRSIIndicator(close=nse_technical['close'],
                                               window=14,
                                               smooth1=3,
                                               smooth2=3,
                                               fillna=False)
            nse_technical["momentum_stoch_rsi"] = indicator_srsi.stochrsi()
            nse_technical["momentum_stoch_rsi_k"] = indicator_srsi.stochrsi_k()
            nse_technical["momentum_stoch_rsi_d"] = indicator_srsi.stochrsi_d()

            nse_technical.replace({np.nan: None}, inplace=True)
            nse_technical.replace([np.inf, -np.inf], None, inplace=True)
            list_to_create = []
            list_to_update = []
            for index in range(len(nse_history_data) - 1, -1, -1):
                data = nse_history_data[index]
                if data.technicals:
                    break
                technical = NSETechnical(
                    nse_historical_data=data,
                    trend_macd=nse_technical['trend_macd'][index],
                    trend_macd_signal=nse_technical['trend_macd_signal']
                    [index],
                    trend_macd_diff=nse_technical['trend_macd_diff'][index],
                    trend_sma_fast=nse_technical['trend_sma_fast'][index],
                    trend_sma_slow=nse_technical['trend_sma_slow'][index],
                    trend_ema_fast=nse_technical['trend_ema_fast'][index],
                    trend_ema_slow=nse_technical['trend_ema_slow'][index],
                    trend_ichimoku_conv=nse_technical['trend_ichimoku_conv']
                    [index],
                    trend_ichimoku_base=nse_technical['trend_ichimoku_base']
                    [index],
                    trend_ichimoku_a=nse_technical['trend_ichimoku_a'][index],
                    trend_ichimoku_b=nse_technical['trend_ichimoku_b'][index],
                    trend_visual_ichimoku_a=nse_technical[
                        'trend_visual_ichimoku_a'][index],
                    trend_visual_ichimoku_b=nse_technical[
                        'trend_visual_ichimoku_b'][index],
                    volatility_bbm=nse_technical['volatility_bbm'][index],
                    volatility_bbh=nse_technical['volatility_bbh'][index],
                    volatility_bbl=nse_technical['volatility_bbl'][index],
                    volatility_bbw=nse_technical['volatility_bbw'][index],
                    volatility_bbp=nse_technical['volatility_bbp'][index],
                    volatility_bbhi=nse_technical['volatility_bbhi'][index],
                    volatility_bbli=nse_technical['volatility_bbli'][index],
                    volume_adi=nse_technical['volume_adi'][index],
                    volume_mfi=nse_technical['volume_mfi'][index],
                    momentum_rsi=nse_technical['momentum_rsi'][index],
                    momentum_stoch_rsi=nse_technical['momentum_stoch_rsi']
                    [index],
                    momentum_stoch_rsi_k=nse_technical['momentum_stoch_rsi_k']
                    [index],
                    momentum_stoch_rsi_d=nse_technical['momentum_stoch_rsi_d']
                    [index])
                data.technicals = True
                list_to_update.append(data)
                list_to_create.append(technical)
            NSETechnical.objects.bulk_create(list_to_create)
            NSEHistoricalData.objects.bulk_update(list_to_update,
                                                  ['technicals'])
            print(f"Technicals updated for {symbol}")
예제 #17
0
def add_trend_ta(
    df: pd.DataFrame,
    high: str,
    low: str,
    close: str,
    fillna: bool = False,
    colprefix: str = "",
    vectorized: bool = False,
) -> pd.DataFrame:
    """Add trend technical analysis features to dataframe.

    Args:
        df (pandas.core.frame.DataFrame): Dataframe base.
        high (str): Name of 'high' column.
        low (str): Name of 'low' column.
        close (str): Name of 'close' column.
        fillna(bool): if True, fill nan values.
        colprefix(str): Prefix column names inserted
        vectorized(bool): if True, use only vectorized functions indicators

    Returns:
        pandas.core.frame.DataFrame: Dataframe with new features.
    """

    # MACD
    indicator_macd = MACD(close=df[close],
                          window_slow=26,
                          window_fast=12,
                          window_sign=9,
                          fillna=fillna)
    df[f"{colprefix}trend_macd"] = indicator_macd.macd()
    df[f"{colprefix}trend_macd_signal"] = indicator_macd.macd_signal()
    df[f"{colprefix}trend_macd_diff"] = indicator_macd.macd_diff()

    # SMAs
    df[f"{colprefix}trend_sma_fast"] = SMAIndicator(
        close=df[close], window=12, fillna=fillna).sma_indicator()
    df[f"{colprefix}trend_sma_slow"] = SMAIndicator(
        close=df[close], window=26, fillna=fillna).sma_indicator()

    # EMAs
    df[f"{colprefix}trend_ema_fast"] = EMAIndicator(
        close=df[close], window=12, fillna=fillna).ema_indicator()
    df[f"{colprefix}trend_ema_slow"] = EMAIndicator(
        close=df[close], window=26, fillna=fillna).ema_indicator()

    # Vortex Indicator
    indicator_vortex = VortexIndicator(high=df[high],
                                       low=df[low],
                                       close=df[close],
                                       window=14,
                                       fillna=fillna)
    df[f"{colprefix}trend_vortex_ind_pos"] = indicator_vortex.vortex_indicator_pos(
    )
    df[f"{colprefix}trend_vortex_ind_neg"] = indicator_vortex.vortex_indicator_neg(
    )
    df[f"{colprefix}trend_vortex_ind_diff"] = indicator_vortex.vortex_indicator_diff(
    )

    # TRIX Indicator
    df[f"{colprefix}trend_trix"] = TRIXIndicator(close=df[close],
                                                 window=15,
                                                 fillna=fillna).trix()

    # Mass Index
    df[f"{colprefix}trend_mass_index"] = MassIndex(high=df[high],
                                                   low=df[low],
                                                   window_fast=9,
                                                   window_slow=25,
                                                   fillna=fillna).mass_index()

    # DPO Indicator
    df[f"{colprefix}trend_dpo"] = DPOIndicator(close=df[close],
                                               window=20,
                                               fillna=fillna).dpo()

    # KST Indicator
    indicator_kst = KSTIndicator(
        close=df[close],
        roc1=10,
        roc2=15,
        roc3=20,
        roc4=30,
        window1=10,
        window2=10,
        window3=10,
        window4=15,
        nsig=9,
        fillna=fillna,
    )
    df[f"{colprefix}trend_kst"] = indicator_kst.kst()
    df[f"{colprefix}trend_kst_sig"] = indicator_kst.kst_sig()
    df[f"{colprefix}trend_kst_diff"] = indicator_kst.kst_diff()

    # Ichimoku Indicator
    indicator_ichi = IchimokuIndicator(
        high=df[high],
        low=df[low],
        window1=9,
        window2=26,
        window3=52,
        visual=False,
        fillna=fillna,
    )
    df[f"{colprefix}trend_ichimoku_conv"] = indicator_ichi.ichimoku_conversion_line(
    )
    df[f"{colprefix}trend_ichimoku_base"] = indicator_ichi.ichimoku_base_line()
    df[f"{colprefix}trend_ichimoku_a"] = indicator_ichi.ichimoku_a()
    df[f"{colprefix}trend_ichimoku_b"] = indicator_ichi.ichimoku_b()

    # Schaff Trend Cycle (STC)
    df[f"{colprefix}trend_stc"] = STCIndicator(
        close=df[close],
        window_slow=50,
        window_fast=23,
        cycle=10,
        smooth1=3,
        smooth2=3,
        fillna=fillna,
    ).stc()

    if not vectorized:
        # Average Directional Movement Index (ADX)
        indicator_adx = ADXIndicator(high=df[high],
                                     low=df[low],
                                     close=df[close],
                                     window=14,
                                     fillna=fillna)
        df[f"{colprefix}trend_adx"] = indicator_adx.adx()
        df[f"{colprefix}trend_adx_pos"] = indicator_adx.adx_pos()
        df[f"{colprefix}trend_adx_neg"] = indicator_adx.adx_neg()

        # CCI Indicator
        df[f"{colprefix}trend_cci"] = CCIIndicator(
            high=df[high],
            low=df[low],
            close=df[close],
            window=20,
            constant=0.015,
            fillna=fillna,
        ).cci()

        # Ichimoku Visual Indicator
        indicator_ichi_visual = IchimokuIndicator(
            high=df[high],
            low=df[low],
            window1=9,
            window2=26,
            window3=52,
            visual=True,
            fillna=fillna,
        )
        df[f"{colprefix}trend_visual_ichimoku_a"] = indicator_ichi_visual.ichimoku_a(
        )
        df[f"{colprefix}trend_visual_ichimoku_b"] = indicator_ichi_visual.ichimoku_b(
        )

        # Aroon Indicator
        indicator_aroon = AroonIndicator(close=df[close],
                                         window=25,
                                         fillna=fillna)
        df[f"{colprefix}trend_aroon_up"] = indicator_aroon.aroon_up()
        df[f"{colprefix}trend_aroon_down"] = indicator_aroon.aroon_down()
        df[f"{colprefix}trend_aroon_ind"] = indicator_aroon.aroon_indicator()

        # PSAR Indicator
        indicator_psar = PSARIndicator(
            high=df[high],
            low=df[low],
            close=df[close],
            step=0.02,
            max_step=0.20,
            fillna=fillna,
        )
        # df[f'{colprefix}trend_psar'] = indicator.psar()
        df[f"{colprefix}trend_psar_up"] = indicator_psar.psar_up()
        df[f"{colprefix}trend_psar_down"] = indicator_psar.psar_down()
        df[f"{colprefix}trend_psar_up_indicator"] = indicator_psar.psar_up_indicator(
        )
        df[f"{colprefix}trend_psar_down_indicator"] = indicator_psar.psar_down_indicator(
        )

    return df
예제 #18
0
import pandas as pd
from ta.utils import dropna
import matplotlib.pyplot as plt
from ta.trend import MACD
import numpy as np

df = pd.read_csv('TSLA.csv', sep=',')

# clean NaN
df = dropna(df)

macd = MACD(close=df["Close"])


def normalize(col):
    return (col - col.mean()) / col.std()


df["macd"] = normalize(macd.macd())
df["macd_signal"] = normalize(macd.macd_signal())
df["macd_diff"] = normalize(macd.macd_diff())

plt.plot(df.macd, label="MACD")
plt.plot(df.macd_signal, label="MACD signal")
plt.plot(df.macd_diff, label="MACD diff")
plt.title("TSLA MACD")
plt.show()

with open("TSLA_ta.csv", "w") as f:
    f.write(df.to_csv())
예제 #19
0
def create_env(config):

    df = load_csv('btc_usdt_m5_history.csv')

    from ta.trend import (
        MACD,
        ADXIndicator,
        AroonIndicator,
        CCIIndicator,
        DPOIndicator,
        EMAIndicator,
        IchimokuIndicator,
        KSTIndicator,
        MassIndex,
        PSARIndicator,
        SMAIndicator,
        STCIndicator,
        TRIXIndicator,
        VortexIndicator,
    )

    colprefix = ""
    # MACD
    indicator_macd = MACD(close=df['close'],
                          window_slow=26,
                          window_fast=12,
                          window_sign=9,
                          fillna=True)
    df[f"{colprefix}trend_macd"] = indicator_macd.macd()
    df[f"{colprefix}trend_macd_signal"] = indicator_macd.macd_signal()
    df[f"{colprefix}trend_macd_diff"] = indicator_macd.macd_diff()

    #df = ta.add_trend_ta(df,'high', 'low', 'close', fillna=True)
    #df = ta.add_volume_ta(df,'high', 'low', 'close', 'volume', fillna=True)
    #df = ta.add_volume_ta(df, 'high', 'low', 'close', 'volume', fillna=True)
    #df = ta.add_volatility_ta(df, 'high', 'low', 'close', fillna=True)
    price_history = df[['date', 'open', 'high', 'low', 'close',
                        'volume']]  # chart data
    df.drop(columns=['date', 'open', 'high', 'low', 'close', 'volume'],
            inplace=True)

    print(df.head(5))
    with NameSpace("bitfinex"):
        streams = [
            Stream.source(df[c].tolist(), dtype="float").rename(c)
            for c in df.columns
        ]

    feed_ta_features = DataFeed(streams)

    price_list = price_history['close'].tolist()
    p = Stream.source(price_list, dtype="float").rename("USD-BTC")

    bitfinex = Exchange("bitfinex", service=execute_order)(p)

    cash = Wallet(bitfinex, 10000 * USD)
    asset = Wallet(bitfinex, 0 * BTC)

    portfolio = Portfolio(USD, [cash, asset])

    reward_scheme = default.rewards.SimpleProfit(window_size=1)
    #action_scheme = default.actions.BSHEX(
    #    cash=cash,
    #    asset=asset
    #).attach(reward_scheme)
    action_scheme = default.actions.SimpleOrders(trade_sizes=3)

    renderer_feed_ptc = DataFeed([
        Stream.source(list(price_history["date"])).rename("date"),
        Stream.source(list(price_history["open"]),
                      dtype="float").rename("open"),
        Stream.source(list(price_history["high"]),
                      dtype="float").rename("high"),
        Stream.source(list(price_history["low"]), dtype="float").rename("low"),
        Stream.source(list(price_history["close"]),
                      dtype="float").rename("close"),
        Stream.source(list(price_history["volume"]),
                      dtype="float").rename("volume")
    ])

    env = default.create(
        feed=feed_ta_features,
        portfolio=portfolio,
        #renderer=PositionChangeChart(),
        renderer=default.renderers.PlotlyTradingChart(),
        action_scheme=action_scheme,
        reward_scheme=reward_scheme,
        renderer_feed=renderer_feed_ptc,
        window_size=config["window_size"],
        max_allowed_loss=0.1)
    return env
예제 #20
0
파일: chart.py 프로젝트: cjj208/jimc
    #%%画K线主图
    datacent = go.Datacent()
    if datacent.qihuo_connectSer():

        qihuocount = list(range(len(cf.cfqihuo)))
        df = datacent.qihuoK(cflen)

        df = tdx_tools.SuperTrend(
            df,
            period=cf.st_period_fast,
            multiplier=cf.st_mult_fast,
        )
        df = tdx_tools.StochRSI(df, m=14, p=7)
        dfmacd = MACD(df['close'], n_slow=10, n_fast=5, n_sign=89)
        df["macd"] = dfmacd.macd()
        df['diff'] = dfmacd.macd_diff()
        df['macd_signal'] = dfmacd.macd_signal()

        df = df.iloc[100:]

        weekday_quotes = [
            tuple([i] + list(quote[1:]))
            for i, quote in enumerate(df.values, )
        ]
        fig = plt.figure(figsize=(1000 / 72, 500 / 72),
                         facecolor='#CCCCCC',
                         edgecolor='#CCCCCC')

        df = df.reset_index()
        df = actionOrder(df)
예제 #21
0
    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()
예제 #22
0
    def __init__(self, symbols):

        # data = json.loads(symbols)
        # df_stock = pd.json_normalize(symbols)
        # df_stock = pd.read_csv(fn,names = ['sym']).drop_duplicates()
        df_stock = pd.DataFrame(symbols)
        ls_stock = df_stock['sym'].to_list()

        df_stock = df_stock.reset_index()

        df_stock.columns = ['sort', 'sym']

        df_stock.head()

        # In[3]:

        start = dt.date.today() + relativedelta(days=-150)
        end = dt.date.today() + relativedelta(days=-0)

        ls_tickers = ls_stock

        ls_df = []
        for ticker in ls_tickers:
            try:
                df = web.DataReader(ticker, 'yahoo', start, end)
            except Exception as e:
                print(str(e))
                continue
            df['sym'] = ticker
            ls_df.append(df.copy())

        df_price = pd.concat(ls_df).reset_index()
        df_price.columns = [
            'dte', 'hgh', 'low', 'opn', 'cls', 'vol', 'cls_adj', 'sym'
        ]
        df_price.sort_values(['sym', 'dte'], inplace=True)

        df_price = df_price[['dte', 'sym', 'hgh', 'low', 'cls', 'vol']].copy()

        df_price['curr'] = end

        df_price['curr'] = pd.to_datetime(df_price['curr'])
        df_price['dte'] = pd.to_datetime(df_price['dte'])

        df_price['ndays'] = (df_price['curr'] - df_price['dte']).dt.days

        df_price['ndays'] = df_price.groupby(['sym'])['ndays'].rank()

        df_price[df_price['sym'] == 'SPY'].head()

        # In[4]:

        ls_df = []
        ls_tickers = ls_stock

        for ticker in ls_tickers:

            #df = dropna(df_price[df_price['sym']==ticker])
            df = df_price[df_price['sym'] == ticker].copy()

            indicator_bb = BollingerBands(close=df['cls'],
                                          window=20,
                                          window_dev=2)
            indicator_macd = MACD(close=df['cls'],
                                  window_fast=12,
                                  window_slow=26,
                                  window_sign=9)
            indicator_rsi14 = RSIIndicator(close=df['cls'], window=14)
            indicator_cci20 = cci(high=df['hgh'],
                                  low=df['low'],
                                  close=df['cls'],
                                  window=20,
                                  constant=0.015)
            indicator_obv = OnBalanceVolumeIndicator(close=df['cls'],
                                                     volume=df['vol'],
                                                     fillna=True)

            indicator_vol_sma20 = SMAIndicator(close=df['vol'], window=20)

            indicator_ema03 = EMAIndicator(close=df['cls'], window=3)
            indicator_ema05 = EMAIndicator(close=df['cls'], window=5)
            indicator_ema08 = EMAIndicator(close=df['cls'], window=8)
            indicator_ema10 = EMAIndicator(close=df['cls'], window=10)
            indicator_ema12 = EMAIndicator(close=df['cls'], window=12)
            indicator_ema15 = EMAIndicator(close=df['cls'], window=15)
            indicator_ema30 = EMAIndicator(close=df['cls'], window=30)
            indicator_ema35 = EMAIndicator(close=df['cls'], window=35)
            indicator_ema40 = EMAIndicator(close=df['cls'], window=40)
            indicator_ema45 = EMAIndicator(close=df['cls'], window=45)
            indicator_ema50 = EMAIndicator(close=df['cls'], window=50)
            indicator_ema60 = EMAIndicator(close=df['cls'], window=60)

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

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

            #df['macd'] = indicator_macd.macd()
            df['macd'] = indicator_macd.macd_diff()
            #df['macd_signal'] = indicator_macd.macd_signal()

            df['obv'] = indicator_obv.on_balance_volume()

            df['vol_sma20'] = indicator_vol_sma20.sma_indicator()

            df['ema03'] = indicator_ema03.ema_indicator()
            df['ema05'] = indicator_ema05.ema_indicator()
            df['ema08'] = indicator_ema08.ema_indicator()
            df['ema10'] = indicator_ema10.ema_indicator()
            df['ema12'] = indicator_ema12.ema_indicator()
            df['ema15'] = indicator_ema15.ema_indicator()
            df['ema30'] = indicator_ema30.ema_indicator()
            df['ema35'] = indicator_ema35.ema_indicator()
            df['ema40'] = indicator_ema40.ema_indicator()
            df['ema45'] = indicator_ema45.ema_indicator()
            df['ema50'] = indicator_ema50.ema_indicator()
            df['ema60'] = indicator_ema60.ema_indicator()

            df['rsi14'] = indicator_rsi14.rsi()
            df['cci20'] = indicator_cci20

            ls_df.append(df.copy())

        df = pd.concat(ls_df)

        df['score_vol_sma20'] = df[['vol',
                                    'vol_sma20']].apply(lambda x: x[0] / x[1],
                                                        axis=1)

        df['emash_min'] = df[[
            'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15'
        ]].min(axis=1)
        df['emash_max'] = df[[
            'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15'
        ]].max(axis=1)
        df['emash_avg'] = df[[
            'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15'
        ]].mean(axis=1)

        #df['score_short'] = df[['cls','emash_min','emash_max','emash_min']].apply(lambda x: 100 * (x[0]-x[1])/(x[2]-x[3]),axis=1)

        df['emalg_min'] = df[[
            'ema30', 'ema35', 'ema40', 'ema45', 'ema50', 'ema60'
        ]].min(axis=1)
        df['emalg_max'] = df[[
            'ema30', 'ema35', 'ema40', 'ema45', 'ema50', 'ema60'
        ]].max(axis=1)
        df['emalg_avg'] = df[[
            'ema30', 'ema35', 'ema40', 'ema45', 'ema50', 'ema60'
        ]].mean(axis=1)

        #df['score_long'] = df[['cls','emalg_min','emalg_max','emalg_min']].apply(lambda x: 100 * (x[0]-x[1])/(x[2]-x[3]),axis=1)

        df['ema_min'] = df[[
            'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15', 'ema30',
            'ema35', 'ema40', 'ema45', 'ema50', 'ema60'
        ]].min(axis=1)
        df['ema_max'] = df[[
            'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15', 'ema30',
            'ema35', 'ema40', 'ema45', 'ema50', 'ema60'
        ]].max(axis=1)

        df['score_ovlp_ema'] = df[[
            'emash_min', 'emalg_max', 'ema_max', 'ema_min'
        ]].apply(lambda x: 100 * (x[0] - x[1]) / (x[2] - x[3]), axis=1)

        df = pd.merge(df_stock, df, on=['sym'],
                      how='inner').sort_values(['sort', 'ndays'])

        decimals = pd.Series([1, 0, 0, 2, 0, 0, 2, 0, 0, 0, 0],
                             index=[
                                 'cls', 'ndays', 'vol', 'score_vol_sma20',
                                 'bb_bbhi', 'bb_bbli', 'macd', 'obv', 'rsi14',
                                 'cci20', 'score_ovlp_ema'
                             ])

        cols = [
            'ndays', 'dte', 'sort', 'sym', 'cls', 'vol', 'score_vol_sma20',
            'bb_bbhi', 'bb_bbli', 'macd', 'obv', 'rsi14', 'cci20',
            'score_ovlp_ema'
        ]

        df = df[df['ndays'] <= 10][cols].round(decimals).copy()

        print(df['score_ovlp_ema'].min(), df['score_ovlp_ema'].max())

        df[df['sym'] == 'QQQ'].head(50)
        self.df = df
예제 #23
0
def add_trend_ta(df: pd.DataFrame,
                 high: str,
                 low: str,
                 close: str,
                 fillna: bool = False,
                 colprefix: str = ""):
    """Add trend technical analysis features to dataframe.

    Args:
        df (pandas.core.frame.DataFrame): Dataframe base.
        high (str): Name of 'high' column.
        low (str): Name of 'low' column.
        close (str): Name of 'close' column.
        fillna(bool): if True, fill nan values.
        colprefix(str): Prefix column names inserted

    Returns:
        pandas.core.frame.DataFrame: Dataframe with new features.
    """

    # MACD
    indicator_macd = MACD(close=df[close],
                          n_fast=12,
                          n_slow=26,
                          n_sign=9,
                          fillna=fillna)
    df[f'{colprefix}trend_macd'] = indicator_macd.macd()
    df[f'{colprefix}trend_macd_signal'] = indicator_macd.macd_signal()
    df[f'{colprefix}trend_macd_diff'] = indicator_macd.macd_diff()

    # EMAs
    df[f'{colprefix}trend_ema_fast'] = EMAIndicator(
        close=df[close], n=12, fillna=fillna).ema_indicator()
    df[f'{colprefix}trend_ema_slow'] = EMAIndicator(
        close=df[close], n=26, fillna=fillna).ema_indicator()

    # Average Directional Movement Index (ADX)
    indicator = ADXIndicator(high=df[high],
                             low=df[low],
                             close=df[close],
                             n=14,
                             fillna=fillna)
    df[f'{colprefix}trend_adx'] = indicator.adx()
    df[f'{colprefix}trend_adx_pos'] = indicator.adx_pos()
    df[f'{colprefix}trend_adx_neg'] = indicator.adx_neg()

    # Vortex Indicator
    indicator = VortexIndicator(high=df[high],
                                low=df[low],
                                close=df[close],
                                n=14,
                                fillna=fillna)
    df[f'{colprefix}trend_vortex_ind_pos'] = indicator.vortex_indicator_pos()
    df[f'{colprefix}trend_vortex_ind_neg'] = indicator.vortex_indicator_neg()
    df[f'{colprefix}trend_vortex_ind_diff'] = indicator.vortex_indicator_diff()

    # TRIX Indicator
    indicator = TRIXIndicator(close=df[close], n=15, fillna=fillna)
    df[f'{colprefix}trend_trix'] = indicator.trix()

    # Mass Index
    indicator = MassIndex(high=df[high],
                          low=df[low],
                          n=9,
                          n2=25,
                          fillna=fillna)
    df[f'{colprefix}trend_mass_index'] = indicator.mass_index()

    # CCI Indicator
    indicator = CCIIndicator(high=df[high],
                             low=df[low],
                             close=df[close],
                             n=20,
                             c=0.015,
                             fillna=fillna)
    df[f'{colprefix}trend_cci'] = indicator.cci()

    # DPO Indicator
    indicator = DPOIndicator(close=df[close], n=20, fillna=fillna)
    df[f'{colprefix}trend_dpo'] = indicator.dpo()

    # KST Indicator
    indicator = KSTIndicator(close=df[close],
                             r1=10,
                             r2=15,
                             r3=20,
                             r4=30,
                             n1=10,
                             n2=10,
                             n3=10,
                             n4=15,
                             nsig=9,
                             fillna=fillna)
    df[f'{colprefix}trend_kst'] = indicator.kst()
    df[f'{colprefix}trend_kst_sig'] = indicator.kst_sig()
    df[f'{colprefix}trend_kst_diff'] = indicator.kst_diff()

    # Ichimoku Indicator
    indicator = IchimokuIndicator(high=df[high],
                                  low=df[low],
                                  n1=9,
                                  n2=26,
                                  n3=52,
                                  visual=False,
                                  fillna=fillna)
    df[f'{colprefix}trend_ichimoku_a'] = indicator.ichimoku_a()
    df[f'{colprefix}trend_ichimoku_b'] = indicator.ichimoku_b()
    indicator = IchimokuIndicator(high=df[high],
                                  low=df[low],
                                  n1=9,
                                  n2=26,
                                  n3=52,
                                  visual=True,
                                  fillna=fillna)
    df[f'{colprefix}trend_visual_ichimoku_a'] = indicator.ichimoku_a()
    df[f'{colprefix}trend_visual_ichimoku_b'] = indicator.ichimoku_b()

    # Aroon Indicator
    indicator = AroonIndicator(close=df[close], n=25, fillna=fillna)
    df[f'{colprefix}trend_aroon_up'] = indicator.aroon_up()
    df[f'{colprefix}trend_aroon_down'] = indicator.aroon_down()
    df[f'{colprefix}trend_aroon_ind'] = indicator.aroon_indicator()

    # PSAR Indicator
    indicator = PSARIndicator(high=df[high],
                              low=df[low],
                              close=df[close],
                              step=0.02,
                              max_step=0.20,
                              fillna=fillna)
    df[f'{colprefix}trend_psar'] = indicator.psar()
    df[f'{colprefix}trend_psar_up'] = indicator.psar_up()
    df[f'{colprefix}trend_psar_down'] = indicator.psar_down()
    df[f'{colprefix}trend_psar_up_indicator'] = indicator.psar_up_indicator()
    df[f'{colprefix}trend_psar_down_indicator'] = indicator.psar_down_indicator(
    )

    return df