示例#1
0
文件: trend.py 项目: wheng3/ta
 def test_macd_signal(self):
     target = 'MACD_signal'
     result = macd_signal(close=self._df['Close'],
                          n_slow=12,
                          n_fast=26,
                          n_sign=9,
                          fillna=False)
     pd.testing.assert_series_equal(self._df[target].tail(),
                                    result.tail(),
                                    check_names=False)
示例#2
0
def MACD(df, col_name, intervals):
    """
        Moving Average Convergence/divergence
        Reference: https://www.investopedia.com/terms/m/macd.asp
    """
    from ta.trend import macd_signal, macd
    from tqdm.auto import tqdm

    for interval in tqdm(intervals):
        df['macd_' + str(interval)] = macd_signal(df[col_name],
                                                  n_fast=min(intervals),
                                                  n_slow=max(intervals),
                                                  n_sign=interval)
示例#3
0
def MACD(df0):
    df = df0
    df['macd'] = macd(df['close'], n_slow=26, n_fast=12, fillna=False)
    df['macd_signal'] = macd_signal(df['close'],
                                    n_slow=26,
                                    n_fast=12,
                                    n_sign=9,
                                    fillna=False)
    df['macd_hist'] = macd_diff(df['close'],
                                n_slow=26,
                                n_fast=12,
                                n_sign=9,
                                fillna=False)
    return df
示例#4
0
        def macd_cb_pressed(stock_analysis_tool: QMainWindow,
                            cb: QCheckBox) -> None:
            """

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    if Indicators.FORCE_INDEX in indicators:
        Logger.console_log(message="Calculating " +
                           Indicators.FORCE_INDEX.value + " for stock " +
                           ticker,
                           status=Logger.LogStatus.EMPHASIS)
        df[Indicators.FORCE_INDEX.value] = force_index(close=df['close'],
                                                       volume=df['volume'],
                                                       n=force_index_n)
示例#6
0
 def test_macd_signal(self):
     target = 'MACD_signal'
     result = macd_signal(**self._params)
     pd.testing.assert_series_equal(self._df[target].tail(),
                                    result.tail(),
                                    check_names=False)
示例#7
0
def calculate_Trend_Indicators():
    JSON_sent = request.get_json()
    if len(JSON_sent[0]) > 0:
        df = pd.DataFrame(JSON_sent[0])

        _, sma, ema, macdDict, macdSignal, adxDict, adxPos, adxNeg, VIpos, VIneg, trixDict, mi, dpoDict = JSON_sent

        if sma['displaySMA']:
            indicator_sma = sma_indicator(close=df['close'], n=sma['nForSMA'])
            df['sma'] = indicator_sma

        if ema['displayEMA']:
            indicator_ema = ema_indicator(close=df['close'], n=ema['nForEMA'])
            df['ema'] = indicator_ema

        if macdDict['displayMACD']:
            indicator_macd = macd(close=df['close'],
                                  n_slow=macdDict['nSlowForMACD'],
                                  n_fast=macdDict['nFastForMACD'])
            df['macd'] = indicator_macd

        if macdSignal['displayMACDsignal']:
            indicator_macdSignal = macd_signal(
                close=df['close'],
                n_slow=macdSignal['nSlowForMACDsignal'],
                n_fast=macdSignal['nFastForMACDsignal'],
                n_sign=macdSignal['nSignForMACDsignal'])
            df['macds'] = indicator_macdSignal

        if adxDict['displayADX']:
            indicator_ADX = adx(high=df['high'],
                                low=df['low'],
                                close=df['close'],
                                n=adxDict['nForADX'])
            df['adx'] = indicator_ADX

        if adxPos['displayADXP']:
            indicator_ADXpositive = adx_pos(high=df['high'],
                                            low=df['low'],
                                            close=df['close'],
                                            n=adxPos['nForADXP'])
            df['adxp'] = indicator_ADXpositive

        if adxNeg['displayADXN']:
            indicator_ADXnegative = adx_neg(high=df['high'],
                                            low=df['low'],
                                            close=df['close'],
                                            n=adxNeg['nForADXN'])
            df['adxn'] = indicator_ADXnegative

        if VIpos['displayVIPOS']:
            indicator_VIpositive = vortex_indicator_pos(high=df['high'],
                                                        low=df['low'],
                                                        close=df['close'],
                                                        n=VIpos['nForVIPOS'])
            df['vipos'] = indicator_VIpositive

        if VIneg['displayVINEG']:
            indicator_VInegative = vortex_indicator_neg(high=df['high'],
                                                        low=df['low'],
                                                        close=df['close'],
                                                        n=VIneg['nForVINEG'])
            df['vineg'] = indicator_VInegative

        if trixDict['displayTRIX']:
            indicator_TRIX = trix(close=df['close'], n=trixDict['nForTRIX'])
            df['trix'] = indicator_TRIX

        if mi['displayMI']:
            indicator_MassIndex = mass_index(high=df['high'],
                                             low=df['low'],
                                             n=mi['nForMI'],
                                             n2=mi['n2ForMI'])
            df['mi'] = indicator_MassIndex

        if dpoDict['displayDPO']:
            indicator_dpo = dpo(close=df['close'], n=dpoDict['nForDPO'])
            df['dpo'] = indicator_dpo

        df.fillna(0, inplace=True)

        return (json.dumps(df.to_dict('records')))
    else:
        df = pd.DataFrame([])
        return (json.dumps(df.to_dict('records')))
示例#8
0
def scan(stock_detail,stock_budget):

    # scan the macd on the stock
    stock_macd = {}
    stock_macd_signal = {}
    stock_macd_diff = {}
    stock_sma = {}

    # get the macd of all the stocks
    for sym in stock_detail: 
        # perform a macd on the aggregated data
        stock_macd[sym] = macd(
            close = stock_detail[sym]['close'].dropna(),
        )
        stock_macd_signal[sym] = macd_signal(
            close = stock_detail[sym]['close'].dropna(),
        )
        stock_macd_diff[sym] = macd_diff(
            close = stock_detail[sym]['close'].dropna(),
        )

        # get 200 day sma
        stock_sma[sym] = sma_indicator(
            close = stock_detail[sym]['close'].dropna(),
            n = 200
        )

    for sym in stock_macd: 
        curr_price = currentClosePrice(sym,'day')

        print('PRICE: ' + str(curr_price))
        print("MACD: "+ str(stock_macd[sym][-1]))
        print("MACD SIGNAL: " + str(stock_macd_signal[sym][-1]))
        print("MACD DIFF:" + str(stock_macd_diff[sym][-1]))
        print("SMA: " + str(stock_sma[sym][-1])+'\n')


        # Buy Signal
        if ((stock_macd[sym][-1]<stock_macd_diff[sym][-1] and stock_macd_signal[sym][-1]<stock_macd_diff[sym][-1]) and #check for macd and signal neg ovr hist
            not(stock_macd_diff[sym][-3]>0 and stock_macd_diff[sym][-2]>0 and stock_macd_diff[sym][-1]>0) and #hist is not going neg
            (curr_price<stock_macd[sym][-1])):  #close price below 200 moving average

            # check how many share that the budget can afford
            shares = determineShare(sym, stock_budget[sym])

            # so macd looks good, so maybe want to buy?
            if shares>0 and clock.is_open():
                stock_shares[sym] = shares #update the shares about to buy
                api.submit_order(sym,shares,'buy','market','day')
                print("Buying Stock {symbol}".format(symbol=sym))

        # Sell Signal
        elif((stock_macd[sym][-1]>stock_macd_diff[sym][-1] and stock_macd_signal[sym][-1]>stock_macd_diff[sym][-1]) and #check for macd and signal pos ovr hist
            not(stock_macd_diff[sym][-3]<0 and stock_macd_diff[sym][-2]<0 and stock_macd_diff[sym][-1]<0) and #hist is not going pos
            (curr_price>stock_macd[sym][-1])):  #close price above 200 moving average

            # check if we have any shares of this stock
            if stock_shares[sym]>0 and clock.is_open():  
                print(stock_shares[sym])
                # sell all the shares
                api.submit_order(sym,stock_budget[sym],'sell','market','day')
                stock_shares[sym] = 0 #update the shares dictionary to 0, b/c sold all
                print("Selling Stock {symbol}".format(symbol=sym))