示例#1
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 __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
 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()
示例#4
0
 def analyze(self):
     macd = MACD(self.df.close, n_fast=12, n_slow=26, n_sign=9)
     self.df["macd"] = macd.macd()
     self.df["signal"] = macd.macd_signal()
     self.df["buy_signal_macd"] = (is_crossover(self.df['macd'],
                                                self.df['signal']))
     self.df["sell_signal_macd"] = (is_crossover(self.df['signal'],
                                                 self.df['macd']))
     self.df["buy_signal"] = (self.df["buy_signal_macd"])
示例#5
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
示例#6
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
示例#7
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
示例#8
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
示例#9
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
示例#10
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
示例#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["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
示例#12
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
示例#13
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()
示例#14
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()
示例#15
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
示例#16
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())
示例#17
0
    def applyIndicator(self, full_company_price):
        self.data = full_company_price

        high = self.data['high']
        low = self.data['low']
        close = self.data['close']
        volume = self.data['volume']

        EMA12 = EMAIndicator(close, 12, fillna=False)
        EMA30 = EMAIndicator(close, 20, fillna=False)
        EMA60 = EMAIndicator(close, 60, fillna=False)
        MACD1226 = MACD(close, 26, 12, 9, fillna=False)
        MACD2452 = MACD(close, 52, 24, 18, fillna=False)
        ROC12 = ROCIndicator(close, 12, fillna=False)
        ROC30 = ROCIndicator(close, 30, fillna=False)
        ROC60 = ROCIndicator(close, 60, fillna=False)
        RSI14 = RSIIndicator(close, 14, fillna=False)
        RSI28 = RSIIndicator(close, 28, fillna=False)
        RSI60 = RSIIndicator(close, 60, fillna=False)
        AROON25 = AroonIndicator(close, 25, fillna=False)
        AROON50 = AroonIndicator(close, 50, fillna=False)
        AROON80 = AroonIndicator(close, 80, fillna=False)
        MFI14 = MFIIndicator(high, low, close, volume, 14, fillna=False)
        MFI28 = MFIIndicator(high, low, close, volume, 28, fillna=False)
        MFI80 = MFIIndicator(high, low, close, volume, 80, fillna=False)
        CCI20 = CCIIndicator(high, low, close, 20, 0.015, fillna=False)
        CCI40 = CCIIndicator(high, low, close, 40, 0.015, fillna=False)
        CCI100 = CCIIndicator(high, low, close, 100, 0.015, fillna=False)
        WILLR14 = WilliamsRIndicator(high, low, close, 14, fillna=False)
        WILLR28 = WilliamsRIndicator(high, low, close, 28, fillna=False)
        WILLR60 = WilliamsRIndicator(high, low, close, 60, fillna=False)
        BBANDS20 = BollingerBands(close, 20, 2, fillna=False)
        KC20 = KeltnerChannel(high, low, close, 20, 10, fillna=False)
        STOCH14 = StochasticOscillator(high, low, close, 14, 3, fillna=False)
        STOCH28 = StochasticOscillator(high, low, close, 28, 6, fillna=False)
        STOCH60 = StochasticOscillator(high, low, close, 60, 12, fillna=False)
        CMI20 = ChaikinMoneyFlowIndicator(high,
                                          low,
                                          close,
                                          volume,
                                          20,
                                          fillna=False)
        CMI40 = ChaikinMoneyFlowIndicator(high,
                                          low,
                                          close,
                                          volume,
                                          40,
                                          fillna=False)
        CMI100 = ChaikinMoneyFlowIndicator(high,
                                           low,
                                           close,
                                           volume,
                                           100,
                                           fillna=False)

        self.data['ema12'] = (close - EMA12.ema_indicator()) / close
        self.data['ema30'] = (close - EMA30.ema_indicator()) / close
        self.data['ema60'] = (close - EMA60.ema_indicator()) / close
        self.data['macd1226'] = MACD1226.macd() - MACD1226.macd_signal()
        self.data['macd2452'] = MACD2452.macd() - MACD2452.macd_signal()
        self.data['roc12'] = ROC12.roc()
        self.data['roc30'] = ROC30.roc()
        self.data['roc60'] = ROC60.roc()
        self.data['rsi14'] = RSI14.rsi()
        self.data['rsi28'] = RSI28.rsi()
        self.data['rsi60'] = RSI60.rsi()
        self.data['aroon25'] = AROON25.aroon_indicator()
        self.data['aroon50'] = AROON50.aroon_indicator()
        self.data['aroon80'] = AROON80.aroon_indicator()
        self.data['mfi14'] = MFI14.money_flow_index()
        self.data['mfi28'] = MFI28.money_flow_index()
        self.data['mfi80'] = MFI80.money_flow_index()
        self.data['cci20'] = CCI20.cci()
        self.data['cci40'] = CCI40.cci()
        self.data['cci100'] = CCI100.cci()
        self.data['willr14'] = WILLR14.wr()
        self.data['willr28'] = WILLR28.wr()
        self.data['willr60'] = WILLR60.wr()
        self.data['bband20up'] = (BBANDS20.bollinger_hband() - close) / close
        self.data['bband20down'] = (close - BBANDS20.bollinger_lband()) / close
        self.data['stoch14'] = STOCH14.stoch()
        self.data['stoch28'] = STOCH28.stoch()
        self.data['stoch60'] = STOCH60.stoch()
        self.data['cmi20'] = CMI20.chaikin_money_flow()
        self.data['cmi40'] = CMI40.chaikin_money_flow()
        self.data['cmi100'] = CMI100.chaikin_money_flow()
        self.data['kc20up'] = (KC20.keltner_channel_hband() - close) / close
        self.data['kc20down'] = (close - KC20.keltner_channel_lband()) / close
        return self.data
示例#18
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
    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}")
示例#20
0
    except TypeError  as e:
        df['Signal Line Crossover'] = 111
        df['Signal Line Crossover'] = 111
        df['Buy Sell signal line'] = 111
        df['Centerline Crossover'] =111
        df['Centerline Crossover'] =111

    """For MACD"""

    indicator = MACD(close=df["close_price"], n_slow=26, n_fast=12, n_sign=9, fillna=False)

    MACD_INDICATOR = "MACD_indicator"

    # print(indicator)
    df[MACD_INDICATOR] = indicator.macd()
    df["MACD_SIGNAL_indicator"] = indicator.macd_signal()
    df2 = df2.append(df)
    df2.to_csv('MACD_price_buy_sell.csv', mode='w', header=False)
    m=m+1


def pg_load_table(file_path, table_name1, dbname, host, port, user, pwd):
    '''
    This function upload csv to a target table
        '''
    try:
        conn = psycopg2.connect(dbname=dbname, host=host, port=port,
                                user=user, password=pwd)
        print("Connecting to Database")
        cur = conn.cursor()
        f = open(file_path, "r")
示例#21
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
示例#22
0
print(EURUSD_T_FX.head())

#input()


# Calculate the macd and macd_sig lines.

# Start an instance of a MACD object

EURUSD_T_FX_MACD = MACD(close = EURUSD_T_FX["Last"])

# Set up new columns in df to hold macd method outputs for macd line and the signal line

EURUSD_T_FX['MACD'] = EURUSD_T_FX_MACD.macd()
EURUSD_T_FX['MACD_sig'] = EURUSD_T_FX_MACD.macd_signal()

# Run the macd line and signal line though the cross-over trigger function

MACD_crossover_signal = MACD_crossover_trigger(EURUSD_T_FX.Last, EURUSD_T_FX['MACD'], EURUSD_T_FX['MACD_sig'])

MACD_buy_sig = MACD_crossover_signal[0]
MACD_sell_sig = MACD_crossover_signal[1]

length = len(MACD_buy_sig)

for i in range(0, length):

    if str(MACD_buy_sig[i]) == 'nan':
        MACD_buy_sig[i] = 0
    else:
示例#23
0
文件: chart.py 项目: cjj208/jimc
    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)

        #%%画K线主图
示例#24
0
print(FX_data.head())

print("Data loaded")
print("###########")

# Calculate the macd and macd_sig lines.

# Start an instance of a MACD object

FX_data_MACD = MACD(close = FX_data["Last"])

# Set up new columns in df to hold macd method outputs for macd line and the signal line

FX_data['MACD'] = FX_data_MACD.macd()
FX_data['MACD_sig'] = FX_data_MACD.macd_signal()

# Run the macd line and signal line though the cross-over trigger function

MACD_crossover_signal = MACD_crossover_trigger(FX_data.Last, FX_data['MACD'], FX_data['MACD_sig'])

MACD_buy_sig = MACD_crossover_signal[0]
MACD_sell_sig = MACD_crossover_signal[1]

length = len(MACD_buy_sig)

for i in range(0, length):

    if str(MACD_buy_sig[i]) == 'nan':
        MACD_buy_sig[i] = 0
    else: