tsm9_2Momentum_Oscillators_TSI_MFI_HPI_adx_psar_Rounded Tops_TRIX_Double Triple Smooth_macd_diverge

文章探讨了双平滑动量概念,特别是TrueStrengthIndex(TSI)作为动力指标在捕捉市场价格动态方面的应用。TSI通过价格变化的双平滑处理减少噪音,有效追踪价格走势,适用于期货和期权市场的趋势和反转预测。同时,介绍了HerrickPayoffIndex,结合价格、成交量和未平仓兴趣分析市场心理和资金流动,以及动量背离和速率、加速度概念在技术分析中的运用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Double-Smoothing Momentum

     Important contributions to the study of momentum have been made by William Blau. In addition to creating new momentum indicators, he has added substantial value to the old ones. Also refer to his work on double smoothing of momentum in Chapter 7.

(TSI:momentum ocillator)True Strength Index

     the True Strength Index (TSI) is a momentum ocillator based on a double smoothing of price changes. Even though several steps are needed for calculation, the indicator is actually pretty straightforward. By smoothing price changes, TSI captures the ebbs and flows兴衰,起伏,潮的涨落 of price action with a steadier line(EMA(EMA(...),...)) that filters out the noise. As with most momentum oscillators, chartists can derive signals from overbought/oversold readings, centerline crossovers, bullish/bearish divergences and signal line crossovers

     Much of Blau’s work combines double smoothing of momentum values (1-period price differences) which has surprisingly little calculation lag given the amount of smoothing. By using the first differences, he has based the calculations on values more sensitive than price and then slowed them down by smoothing. In effect, he speeds up the price movement before slowing it down. The net result is that the final index value has less lag than we would normally expect, and the index line is much smoother than a standard moving average. Blau refers to this as using momentum as a proxy for price. One of Blau’s most popular indicators is the True Strength Index (TSI) which combines these features: 

  • c0 = today's closing price
    m = c0 − c1 = momentum (difference between today's and yesterday's close)
    EMA(m,n) = exponential moving average of m over n periods, that is,
    EMA(m_0,n) = m_0
    EMA(m_t, n) = \frac{2}{n+1}[m_t - EMA(m_{t-1},n)] + EMA(m_{t-1},n)
    EMA(m_t, n) = (1- \frac{2}{n+1} ) EMA(m_{t-1},n) + \frac{2}{n+1}m_t
    adjust=False and ignore_na=False
  • Momentum(Price change represents momentum in its truest form) :


                                                 

                                                                  
                                                                   
    The 1-day differences(Price Change) are first smoothed over the period r=25, and then the result is smoothed over the period s=13.
  • Absolute Momentum :


                                                                    
                                                                    

                                                                    
                                                                    

  • The first part, which is the double smoothed price change, sets the positive or negative tone for TSI.
         The indicator is negative when the double smoothed price change is negative and positive when it is positive.
         The double smoothed absolute price change normalizes the indicator and limits the range of the ensuing oscillator.双重平滑的绝对价格变化使指标正常化并限制了随后的震荡指标的范围 
         In other words, this indicator measures the double smoothed price change relative to the double smoothed absolute price change.该指标衡量的是相对于双重平滑绝对价格变化的双重平滑价格变化
         A string of large positive price changes results in relatively high positive readings, signaling strong upside momentum.
         A string of large negative price changes pushes TSI deep into negative territory.
  • TSI signal line is a  n-period EMA of TSI
    \mathbf{TSI_{signal} = EMA(TSI, n=13)}

pandas-ta/tsi.py at 084dbe1c4b76082f383fa3029270ea9ac35e4dc7 · twopirllc/pandas-ta · GitHubpandas-ta/ema.py at 084dbe1c4b76082f383fa3029270ea9ac35e4dc7 · twopirllc/pandas-ta · GitHubpandas-ta/_core.py at main · twopirllc/pandas-ta · GitHub 

import pandas as pd

def get_tsi(df, columnName='Close', fast_period=13, slow_period=25, signal_period=13,
            diff_drift=1, scalar=100, tsi_offset=0, mamode=None, **kwargs
           ):
    
    """Indicator: True Strength Index (TSI)"""
    # Validate Arguments
    fast_period = int(fast_period) if fast_period and fast_period > 0 else 13
    slow_period = int(slow_period) if slow_period and slow_period > 0 else 25
    
    diff_drift =  int(diff_drift) if isinstance(diff_drift, int) and diff_drift != 0 else 1
    scalar = float(scalar) if scalar else 100.
    
    signal_period = int(signal_period) if signal_period and signal_period > 0 else 13
    tsi_offset = int(tsi_offset) if isinstance(tsi_offset, int) else 0
    # if slow_period < fast_period:
    #     fast, slow = slow_period, fast_period

    # Calculate Result
    df['Momentum'] = df[columnName].diff(diff_drift) # df['Close'] - df['Close'].shift(diff_drift)
    
    # https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ewm.html
    adjust = kwargs.pop("adjust", False)#if 'adjust' not exist,return default False
    
    df[f'{slow_period}_ema'] = df['Momentum'].ewm( span=slow_period, # or alpha=2/(slow_period+1)
                                                   min_periods=slow_period,
                                                   ignore_na=False,
                                                   adjust=adjust
                                                 ).mean()
    df[f'{fast_period}_ema'] = df[f'{slow_period}_ema'].ewm( span=fast_period,
                                                             min_periods=fast_period,
                                                             ignore_na=False,
                                                             adjust=adjust
                                                           ).mean()

    df['Absolute Momentum'] = df['Momentum'].abs()
    df[f'abs_{slow_period}_ema'] = df['Absolute Momentum'].ewm( span=slow_period,
                                                                min_periods=slow_period,
                                                                ignore_na=False,
                                                                adjust=adjust
                                                              ).mean()
    df[f'abs_{fast_period}_ema'] = df[f'abs_{slow_period}_ema'].ewm( span=fast_period,
                                                                     min_periods=fast_period,
                                                                     ignore_na=False,
                                                                     adjust=adjust
                                                                   ).mean()

    df["tsi_{}_{}".format(fast_period,
                          slow_period,
                          signal_period,
                         )
      ] = scalar * df[f'{fast_period}_ema'].divide( df[f'abs_{fast_period}_ema'])
    
    df["tsi_{}_{}_signal_{}".format(fast_period,
                                    slow_period,
                                    signal_period
                                   )
      ] = df[f"tsi_{fast_period}_{slow_period}"].ewm( span=signal_period,
                                                      min_periods=signal_period,
                                                      ignore_na=False,
                                                      adjust=adjust
                                                    ).mean()
    # Offset
    if tsi_offset != 0:
        tsi = tsi.shift(tsi_offset)
        tsi_signal = tsi_signal.shift(tsi_offset)

    # Handle fills
    if "fillna" in kwargs:
        tsi.fillna(kwargs["fillna"], inplace=True)
        tsi_signal.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        tsi.fillna(method=kwargs["fill_method"], inplace=True)
        tsi_signal.fillna(method=kwargs["fill_method"], inplace=True)
    
    df.drop(columns=['Momentum', f'{slow_period}_ema', f'{fast_period}_ema',
                     'Absolute Momentum', f'abs_{slow_period}_ema', f'abs_{fast_period}_ema'
                    ],
            inplace=True)

    return df

fast_period=13 
slow_period=25
signal_period=13
columnName='Close'

spx = yf.download( '^GSPC', start='2010-09-01', end='2012-09-01')
spx_tsi=get_tsi( spx.loc[:,[columnName]],columnName, fast_period,  slow_period)
spx_tsi.iloc[:fast_period+slow_period+signal_period]#['2012-07-19':'2012-08-29']

aapl = yf.download( 'aapl', start='2012-01-01', end='2018-12-31')
aapl_tsi=get_tsi( aapl.loc[:,[columnName]],columnName, fast_period,  slow_period)
aapl_tsi['2013-01-01':'2013-02-01']

Interpretation

     The True Strength Index (TSI) is an oscillator that fluctuates between positive and negative territory. As with many momentum oscillators, the centerline defines the overall bias. The bulls have the momentum edge when TSI is positive and the bears have the edge when it's negative. As with MACD, a signal line can be applied to identify upturns and downturns. Signal line crossovers are, however, quite frequent and require further filtering with other techniques. Chartists can also look for bullish and bearish divergences to anticipate trend reversals; however, keep in mind that divergences can be misleading in a strong trend.

     TSI is somewhat unique because it tracks the underlying price quite well. In other words, the oscillator can capture a sustained move in one direction or the other. The peaks and troughs in the oscillator often match the peaks and troughs in price. In this regard, chartists can draw trend lines and mark support/resistance levels using TSI. Line breaks can then be used to generate signals. 图表师可以使用 TSI 绘制趋势线并标记支撑/阻力位。 然后可以使用换行符来生成信号。

  • The TSI fluctuates between positive and negative territory.
    • Positive territory means the bulls are more in control of the asset.
    • Negative territory means the bears are more in control.
  • When the indicator divergences with price, the TSI may be signaling the price trend is weakening and may reverse.
  • A signal line can be applied to the TSI indicator.
    • When the TSI crosses above the signal line it can be used as a buy signal, and
    • when it crosses below, a sell signal.
    • Such crossovers occur frequently, so use with caution.此类交叉经常发生,因此请谨慎使用。
      • when TSI is in positive territory, A bullish signal is triggered when TSI crosses above its signal line.
      • where TSI is in negative territory, A bearish signal is triggered when TSI crosses below its signal line.

  • Overbought and oversold levels will vary by the asset being traded.
    超买和超卖水平将因交易的资产而异。
    • 由于 TSI 基于价格变动,超卖和超买水平将因交易资产而异。 一些股票可能会在出现价格反转之前达到 +30 和 -30,而另一只股票可能会在 +20 和 -20 附近反转。
    • 在交易的资产上标记极端 TSI 水平,以查看超买和超卖的位置。 超卖并不一定意味着是时候买入,当资产超买时并不一定意味着是时候卖出。 交易者通常会观察其他信号以触发交易决策。 例如,他们可能会等待价格或 TSI 开始下跌,然后在超买区域卖出。 或者,他们可以等待信号线交叉。

Center Line Crossover

     The centerline crossover is the purest signal.

  • The double smoothed momentum of price changes is positive when TSI is above zero and negative when below zero.
    当指标高于零时价格动量为正,低于零时为负。
    一些交易者使用中心线作为方向偏差。 例如,如果指标高于其中心线,交易者可能决定只建立多头头寸。 相反,如果指标值低于零,交易者将看跌并且只考虑空头头寸
  • Prices are generally rising when TSI is positive and falling when TSI is negative.

The chat shows Nike (NKE) turning bullish in September 2011 as TSI moved into positive territory (green line). The stock remained bullish as the uptrend extended into the spring of 2012. Nike turned bearish when TSI turned negative and the stock broke support.

Trend Lines

     TSI often produces support and resistance levels that chartists can use to identify breakouts or breakdowns. The chart shows Citigroup (C) with TSI establishing support in March. The indicator broke support in early April and this breakdown foreshadowed a significant decline into May. TSI then rebounded in June and formed a flat consolidation into July. This consolidation resembled a falling flag and TSI broke above the trend line in late July. This breakout preceded further strength into August

Overbought/Oversold

     Overbought and oversold levels for the True Strength Index vary according to a security's volatility and the period settings for the indicator.

  • The TSI range will be smaller for stocks with low volatility, such as utilities公用事业.
  • The TSI range will be larger for stocks with high volatility, such as biotechs生物技术.
  • Using shorter time periods for the smoothing will result in a wider range and choppier更震荡 indicator line.
  • Longer time periods will result in a smaller range and smoother line.
  • It is the classic technical analysis tradeoff:
    • chartists get quicker signals and less lag with shorter periods, but this comes at the cost of more whipsaws and false signals.
    • Longer periods reduce the whipsaws, but these signals come with more lag and a poorer reward-to-risk ratio

The chart above shows the Nasdaq 100 ETF (QQQ) with TSI using two different timeframes.

  • The upper indicator window shows TSI (40,20,7) fluctuating between -20 and +44 with 20/-20 marking overbought/oversold.
  • The lower window shows TSI (13,7,7) fluctuating between +78 and -69 with 50/-50 marking overbought/oversold.
  • Notice how TSI in the lower window is much more volatile than TSI in the upper window. Also, notice that the more sensitive TSI produced two oversold readings and four overbought readings (blue arrows).
  • Overbought and oversold are not signals of an impending reversal.超买和超卖并不是即将发生逆转的信号 They simply suggest that prices have come too far too fast. Chartists must wait for a confirming signal to suggest an actual reversal.
  • The blue lines mark support and resistance using trend lines, peaks or troughs. Once an overbought or oversold reading occurs, chartists can use these lines to define a price reversal. This will not illuminate whipsaws, but it will reduce bad signals.
    交易者可以使用 TSI 创建的支撑位阻力位识别突破和价格动能变化。 例如,如果指标跌破趋势线,价格可能会继续抛售。
  • 背离是 TSI 提供的另一种工具。 如果资产价格走高而 TSI 下降,则称为看跌背离,可能导致价格下行。 相反,如果 TSI 在价格下跌时上涨,则可能预示着价格会上涨。 这称为看涨背离。

    背离是一个糟糕的时机信号,因此它只能与 TSI 或其他技术指标生成的其他信号结合使用

Signal Line Crossovers

     The last parameter in the TSI setting is the signal line\mathbf{TSI_{signal} = EMA(TSI, n=13)}, which is simply an exponential moving average of TSI. Signal line crossovers are by far the most common signals, meaning there will be good, bad and ugly signals.In an effort to reduce signals and noise, chartists should consider increasing the settings for TSI or the price chart settings.

  • The TSI has a signal line, which is usually a 7- to 12-period EMA of the TSI line
  • when TSI is in positive territory, A bullish signal is triggered when TSI crosses above its signal line.
  • where TSI is in negative territory, A bearish signal is triggered when TSI crosses below its signal line.

The example above shows TSI(40,20,10) using a weekly chart. This means the signal line is a 10-period EMA of TSI. There was no shortage of signals on this chart as TSI crossed the signal line at least 12 times from April 2007 to July 2012. 

Limitations of the True Strength Index (TSI)

     Many of the signals provided by the TSI will be false signals. That means the price action will be different than expected following a trade signal. For example, during an uptrend, the TSI may cross below the centerline several times, but then the price proceeds higher even though the TSI indicates momentum has shifted down.在上升趋势中,TSI 可能多次下穿中线,但随后价格继续走高,即使 TSI 表明动能已经向下移动

Signal line crossovers also occur so frequently that they may not provide a lot of trading benefit. Such signals need to be heavily filtered based on other elements of the indicator or through other forms of analysis. The TSI will also sometimes change direction without the price changing direction, resulting in trade signals that look good on the TSI but continue to lose money based on price.TSI 有时也会在价格没有改变方向的情况下改变方向,导致交易信号在 TSI 上看起来不错,但根据价格继续亏损。

Divergence, too, tends to be unreliable on the indicator. Divergence can last so long that it provides little insight into when a reversal will actually occur. Also, divergence isn't always present when price reversals actually do occur.背离在指标上也往往是不可靠的。 背离可以持续很长时间,以至于几乎无法洞察何时会真正发生逆转。 此外,当价格反转确实发生时,分歧并不总是存在。

Additional Smoothing without Adding Lag不增加滞后的额外平滑

     In creating the TSI, Blau missed an opportunity to improve the smoothing with only a minor increase in the lag. Instead of taking the 1-day differences, substitute the n-day differences in the first step. This smoothes the trendline even more at the cost of a slight additional lag这以轻微的额外滞后为代价使趋势线更加平滑。. Figure 9.20 shows the TSI with a 10-day difference followed by two 20-day exponential smoothings in the bottom panel.FIGURE 9.20 Comparing the TSI with 10-20-20 smoothing (bottom这以轻微的额外滞后为代价使趋势线更加平滑,)

  • to a standard 20-period momentum (second panel : has the typical erratic pattern of prices典型的不稳定价格模式, and a slight lead identifying the peaks识别峰值的轻微领先 )
  • TSI with 1-20-20 smoothing (third panel,TSI 更加平滑,波峰和波谷略微滞后于价格)

using INTC from January 2001 through March 2002. 

Anticipating the Turn期待转机

     When working with trendlines that are very smooth, such as the 10-20-20 TSI, you can anticipate the change in the trend direction most of the time. Instead of waiting for the smoothed trendline to change from up to down, you can sell when it gets to a “near-zero slope” and is continuing to flatten. This anticipation can greatly reduce the lag and improve performance even at the cost of a few false signals. 当使用非常平滑的趋势线时,例如 10-20-20 TSI,您可以在大多数时间预测趋势方向的变化。与其等待平滑的趋势线从上升到下降,不如在它达到“接近零的斜率”并继续趋于平缓时卖出。 即使以一些错误信号为代价,这种预期也可以大大减少延迟并提高性能       

Conclusion

     The True Strength Index (TSI) is a unique indicator based on double smoothed price changes. Price change represents momentum in its truest form. The double smoothing with two exponential moving averages reduces the noise and produces an oscillator that tracks price quite well. In addition to the usual oscillator signals, chartists can often draw trend lines, support lines and resistance lines directly on TSI. These can then be used to generate signals based on breakouts and breakdowns. As with all indicators, TSI signals should be confirmed with other indicators and analysis techniques. 

Double-Smoothed Stochastics双平滑随机指标

     Because of Blau’s great interest in double smoothing, he defi nes the general form of a double-smoothed stochastic as: 

Where

TRIX:momentum oscillator) Triple Exponentially Smoothed Moving Average

     Similar to Blau’s double smoothing is TRIX, a triple-smoothed exponential that is most often used as an oscillator. Introduced by Jack Hutson,(Referenced in Robert W. Colby, The Encyclopedia of Technical Market Indicators (New York: McGraw-Hill, 2003) as “Good Trix” by Jack K. Hutson, Technical Analysis of Stocks & Commodities 1, no. 5.) it is created using steps similar to Blau except that there are three exponential smoothings and the differencing is done at the end. Typically, the same smoothing constants (calculation periods) are used for each smoothing. This method has been applied to daily, hourly, or even 1-minute price data. TRIX 具有三重平滑功能旨在过滤掉微不足道的价格变动。 图表师可以使用 TRIX 生成类似于 MACD 的信号。 可以应用信号线来寻找信号线交叉方向偏差可以用绝对水平来确定看涨和看跌背离可用于预测逆转

     TRIX is the 1-period percentage rate-of-change for a triple smoothed exponential moving average (EMA), which is an EMA of an EMA of an EMA. Here is a breakdown of the steps involved for a 15 period TRIX

  1. Calculate the natural log (ln) of the closing prices (daily or intraday bars). This implicitly corrects for price volatility; however, it is commonly omitted from the calculation because back-adjusted data in futures will cause errors.计算收盘价(每日或盘中柱)的自然对数 (ln)。 这隐含地纠正了价格波动; 然而,它通常在计算中被忽略,因为期货中的反向调整数据会导致错误。

  2. Calculate the N-period exponential smoothing of the closing prices, or the log (ln) of the closing prices, to get trend 1.
    Single-Smoothed 

  3. Calculate the p-period exponential smoothing of trend 1 to get trend 2.
    Double-Smoothed

  4. Calculate the q-period exponential smoothing of trend 2 to get trend 3.

  5. Get the 1-period differences of trend 3 by subtracting each value from the previous value. As with the added smoothing of the TSI
    , the 1-period differences can be replaced with the s-period differences.
    TRIX = 1-period percent change in Triple-Smoothed EMA

  6. Scale the results by multiplying by 10,000(or 100). This is an attempt to get TRIX scaled to a positive integer value for charting and may also be omitted.
    通过乘以 10,000 来缩放结果。 这是为了将 TRIX 缩放为正整数值以用于制图的尝试,也可以省略。

  7. Most traders prefer to plot a 9-period Moving Average of the TRIX to create a "signal" line or 9-period EMA of the TRIX
    \mathbf{TRIX_{signal} = EMA(TRIX, signal_{period=9})}OR\mathbf{TRIX_{signal} = SMA(TRIX, signal_{period=9})}

def get_trix( df, columnName='Close', smoothing_period=15, 
              signal_period=9, smoothing_signal='ma',
              scalar=100, diff_drift=1, hist_multiplier=0,
              trix_offset=0, **kwargs
           ):
    """ Triple Exponential Average
    https://www.investopedia.com/articles/technical/02/092402.asp
    :param column: the column to calculate
    :param windows: range
    :return: result series
    """
    # Validate Arguments
    smoothing_period = int(smoothing_period) if smoothing_period and smoothing_period > 0 else 15
    signal_period = int(signal_period) if signal_period and signal_period > 0 else 0
    
    scalar = float(scalar) if scalar else 100
    
    diff_drift =  int(diff_drift) if isinstance(diff_drift, int) and diff_drift != 0 else 1
    trix_offset = int(trix_offset) if isinstance(trix_offset, int) else 0
    hist_multiplier = int(hist_multiplier) if hist_multiplier and  hist_multiplier > 0 else 0

    # https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ewm.html
    adjust = kwargs.pop("adjust", False)#if 'adjust' not exist,return default False
    
    df['single_ema'] = df[columnName].ewm( span=smoothing_period, # or alpha=2/(slow_period+1)
                                           min_periods=smoothing_period,
                                           ignore_na=False,
                                           adjust=True
                                         ).mean()
    df['double_ema'] = df['single_ema'].ewm( span=smoothing_period,
                                             min_periods=smoothing_period,
                                             ignore_na=False,
                                             adjust=True
                                           ).mean()
    df['triple_ema'] = df['double_ema'].ewm( span=smoothing_period,
                                             min_periods=smoothing_period,
                                             ignore_na=False,
                                             adjust=adjust
                                           ).mean()
    df[f'trix_{smoothing_period}']=scalar * df['triple_ema'].pct_change(periods=diff_drift) # Periods to shift for forming percent change.
    #df[f'trix_{smoothing_period}']=scalar *df['triple_ema'].diff(diff_drift)/df['triple_ema'].shift(diff_drift)
    
    if signal_period>0:
        if signal_period and smoothing_signal=='ma' or smoothing_signal=='sma':
            df['trix_{}_signal_{}'.format(smoothing_period,
                                          signal_period
                                         )
              ] = df[f'trix_{smoothing_period}'].rolling(signal_period).mean()
        
        elif smoothing_signal=='ema' or smoothing_signal=='exponential':
            df['trix_{}_signal_{}'.format(smoothing_period,
                                          signal_period
                                         )
              ] = df[f'trix_{smoothing_period}'].ewm( span=signal_period,
                                                      min_periods=signal_period,
                                                      ignore_na=False,
                                                      adjust=adjust
                                                    ).mean()  
        # Offset
        if trix_offset != 0:
            df[f'trix_{smoothing_period}'] = df[f'trix_{smoothing_period}'].shift(trix_offset)
            df['trix_{}_signal_{}'.format(smoothing_period,
                                          signal_period
                                         )
              ] = df['trix_{}_signal_{}'.format(smoothing_period,
                                                signal_period
                                               )
                    ].shift(trix_offset)
    
        if hist_multiplier>0 :
            df['trix_{}_signal_{}_hist_{}'.format( smoothing_period,
                                                   signal_period,
                                                   hist_multiplier,
                                                 )
              ] = hist_multiplier * (df[f'trix_{smoothing_period}']-df[f'trix_{smoothing_period}_signal_{signal_period}'] )
    return df

smoothing_period=15 
signal_period=9
columnName='Close'
diff_drift=1
hist_multiplier=2
scalar=10000
smoothing_signal='ema'

flnc = yf.download( 'flnc', start='2010-10-30',end='2023-05-30' )
flnc_trix=get_trix( flnc.loc[:,[columnName]],columnName, 
                    smoothing_period, 
                    signal_period, smoothing_signal,
                    scalar, diff_drift, hist_multiplier
                  )
flnc_trix

 

smoothing_period=15
columnName='Close'
diff_drift=1
signal_period=0
scalar=100
smoothing_signal='ma'

spy = yf.download( 'spy', start='2009-06-30',end='2010-08-30' )
spy_trix=get_trix( spy.loc[:,[columnName]], columnName, 
                   smoothing_period,
                   signal_period, smoothing_signal,
                   scalar, diff_drift,
                 )
spy_trix['2010-06-30':'2010-08-11']

 round==>yahoo finance

smoothing_period=15
columnName='Close'
diff_drift=1
signal_period=9
scalar=100
smoothing_signal='sma'
trix_offset=1

spy = yf.download( 'spy')
spy_trix=get_trix( spy.loc[:,[columnName]],columnName, 
                   smoothing_period, 
                   signal_period-1, smoothing_signal,
                   scalar, diff_drift, trix_offset=trix_offset
                 )
spy_trix

 
Be careful with stock charts

import matplotlib.pyplot as plt

from matplotlib.dates import DateFormatter, DayLocator  
from matplotlib.ticker import MaxNLocator, FormatStrFormatter

fig, ax = plt.subplots(figsize=(10,6) )

ax.plot(  spy_trix['2010-07-05':'2010-08-16'].index,
          spy_trix['2010-07-05':'2010-08-16']['Close'],
          color='b',
          label='Price'
        )
ax.plot( spy_trix['2010-07-05':'2010-08-16'].index,
          spy_trix['2010-07-05':'2010-08-16']['single_ema'],
          color='black',
          label=f'{smoothing_period}-day EMA',
        )
ax.plot( spy_trix['2010-07-05':'2010-08-16'].index,
          spy_trix['2010-07-05':'2010-08-16']['double_ema'],
          color='orange',
          label='Double Smooth'
       )
ax.plot( spy_trix['2010-07-05':'2010-08-16'].index,
          spy_trix['2010-07-05':'2010-08-16']['triple_ema'],
          color='purple',
          label='Triple Smooth'
       )

ax.set_xlabel('Date')
ax.set_ylabel('SPDR S&P 500 ETF (SPY)')

#ax.xaxis.set_minor_locator( DayLocator() ) 
ax.xaxis.set_major_locator(MaxNLocator(len(spy_trix['2010-06-30':'2010-08-11'].index)))
# https://blog.youkuaiyun.com/Linli522362242/article/details/128760927
# https://blog.youkuaiyun.com/Linli522362242/article/details/121172551 
ax.xaxis.set_major_formatter(DateFormatter('%d-%b-%y'))
leg = ax.legend( ncols=4, frameon=False, loc='lower center', handletextpad=0.2)
#Bbox=leg.get_window_extent()
#print(Bbox)
ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))

plt.setp( ax.get_xticklabels(), rotation=90, horizontalalignment='center' )#right

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

ax.autoscale(enable=True, axis='x', tight=True)
ax.grid(axis='y')

plt.show()

  • The blue line is the price plot for SPY. It is clearly the most jagged (volatile) of the four lines.
  • The black line is the 15-day EMA, which follows the price plot the closest.
  • The Orange line is the double-smoothed EMA and the purple line is the triple-smoothed EMA. Notice how these two lines turn flatter as the lag increases.请注意这两条线如何随着滞后增加而变得更平坦。

TRIX is negative as long as the triple-smoothed 15-day EMA is moving lower. TRIX turns positive when the triple-smoothed 15-day EMA turns up. The extra smoothing
(
1-period differences of trend 3 or 1-period percent change in Triple-Smoothed EMA) ensures that upturns and downturns are kept to a minimum. In other words, it takes more than a one-day advance to reverse a downtrend扭转下降趋势需要不止一天的上涨. 

Interpretation

     TRIX (15,9) is quite similar to MACD (12,26,9). Both are momentum oscillators that fluctuate above and below the zero line. Both have signal lines based on a 9-day EMA. Most notably, both lines have similar shapes, signal line crossovers, and centerline crosses. The biggest difference between TRIX and MACD is that TRIX is the smoother of the two; TRIX lines are less jagged and tend to turn a bit later(TRIX 线的锯齿较少,而且转弯的时间会稍晚一些). With the similarities outweighing the differences, signals applicable to MACD are also applicable to TRIX. There are three main signals to watch for.

  • First, signal line crossovers are the most common signals. These indicate a change in direction for TRIX and price momentum.
    • A cross above the signal line is the first bullish indication,
    • while a cross below is the first negative implication.
  • Second, centerline crossovers provide chartists with a general momentum bias.
    • The triple-smoothed moving average is rising when TRIX is positive and falling when negative.
    • Similarly, momentum favors the bulls when TRIX is positive and the bears when negative.
  • Third, bullish and bearish divergences can alert chartists of a possible trend reversal.

Signal Line Crossovers

     Signal line crossovers are the most common TRIX signals. The signal line is a 9-day EMA of the TRIX\mathbf{TRIX_{signal} = EMA(TRIX, signal_{period=9})}. As a moving average of the indicator, it trails/treɪlz/ TRIX and makes it easier to spot turns它落后于 TRIX 并且更容易发现转向.

  • A bullish crossover occurs when TRIX turns up and crosses above the signal line.
  • A bearish crossover occurs when TRIX turns down and crosses below the signal line.
  • Crossovers can last a few days or a few weeks, depending on the strength of the move. Due diligence尽职调查 is required before relying on these frequent signals. Volatility in the underlying security can also increase the number of crossovers

The chart above shows Intel (INTC) and TRIX with six signal line crosses in a seven-month period. That is almost one per month. There were three good signals and three bad signals resulting in whipsaws (yellow area).

  • The bullish crossover in June occurred near the top,
    the bearish crossover in late June occurred near the low and
    the bullish crossover in July occurred near the top.
    In the absence of a strong move, the lag from the triple-smoothed EMA results in late signals that produce losses.在没有强势走势的情况下,三重平滑 EMA 的滞后会导致产生损失的延迟信号 
  • The bearish signal line cross in August foreshadowed a sharp decline and
    the bullish signal line cross in mid-September foreshadowed a strong advance.

Centerline Crossovers 

     The centerline crossover indicates when the cup is half full (bullish) or half empty (bearish) 在杯子半满的上方时是看涨偏见(超过半个杯子),在半空的下方时是看跌偏见(低于半个杯子). Think of the centerline as the 50-yard line in a football game. The offense has the edge after crossing the 50 (midpoint), while the defense has the edge as long as the ball remains beyond the 50. As with signal line crossovers, these centerline crossovers produce both good signals and bad signals. The key, as always, is to minimize losses on the bad signals and maximize gains with the good signals.The chart above shows Raytheon (RTN) with five signals over a 16 month period. The first three were bad because the stock changed direction soon after the signals. In other words, a trend failed to take hold. The fourth signal (November 2009) coincided with a resistance breakout and foreshadowed a 20% advance. Great signal! This is also a classic example of combining indicator signals with chart signals for reinforcement这也是将指标信号与图表信号相结合进行强化的经典示例。. The resistance breakout on the price chart and the centerline cross for the TRIX reinforced each other.价格图表上的阻力突破和 TRIX 的中心线交叉相互加强。 TRIX produced a nice bearish signal in May 2010 as RTN subsequently declined around 20%.

Divergences

     Bullish and bearish divergences form when the security and the indicator do not confirm one another.

  • A bullish divergence forms when the security forges a lower low, but the indicator forms a higher low. This higher low shows less downside momentum这一更高的低点显示下行势头减弱 that may foreshadow a bullish reversal.
  • A bearish divergence forms when the security forges a higher low, but the indicator forms a lower high. This lower high shows waning/ weɪnɪŋ / upside momentum这个较低的高点显示上行势头减弱 that can sometimes foreshadow a bearish reversal.

Before looking at a successful divergence, note the BHP Billiton (BHP) chart with several unsuccessful divergences. 

  • Bearish divergences do not work well in strong uptrends. Even though momentum seems to be waning because the indicator is producing lower highs,
    • momentum still has a bullish bias as long as the indicator is above its centerline只要该指标高于其中心线,动能仍然看涨.
    • Upward momentum may be less positive, but it is still positive as long as the cup is half full向上的势头可能不太积极,但只要杯子是半满的,它仍然是积极的.
    • The rise is just not as fast as before.
  • The opposite is true for bullish divergences. These do not work well in strong downtrends. Even though the indicator shows less downside momentum with higher lows,
    • downward momentum is still stronger than upward momentum as long as the indicator remains below its centerline. 尽管该指标显示下行势头较小低点较高,但只要指标保持在中线下方,下行势头仍强于上行势头。

When bullish and bearish divergences work, they really work. The trick is separating the bad signals from the good signals. The chart below shows eBay (EBAY) with a successful bullish divergence. The stock moved to a lower low in early July, but TRIX held well above its prior low(higher low) and formed a bullish divergence.

  • The first potential confirmation came when TRIX moved above its signal line. However, there were no confirmations on the chart at the time. These came a little later.
  • The green arrows show EBAY breaking chart resistance with good volume and TRIX moving into positive territory. Even though confirmation occurred well off the low, there were enough signs of strength to validate the breakout. 尽管确认发生在低点之外,但有足够的力量迹象来验证突破。

Advantages of TRIX

Two main advantages of TRIX over other trend-following indicators are its excellent filtration of market noise对市场噪音的过滤比较出色 and its tendency to be a leading than lagging indicator它倾向于成为领先指标而不是滞后指标. It filters out market noise using the triple exponential average calculation, thus eliminating minor short-term cycles that indicate a change in market direction从而消除表明市场方向发生变化次要短期周期. It has the ability to lead a market because it measures the difference between each bar's "smoothed" version of the price information因为它衡量的是每根柱线的“平滑”价格信息 版本之间的差异. When interpreted as a leading indicator, TRIX is best used in conjunction with another market-timing indicator—this minimizes false indications. 

Conclusion

     TRIX is an indicator that combines trend with momentum. The triple smoothed moving average covers the trend, while the 1-period percentage change measures momentum. In this regard, TRIX is similar to MACD and PPO. The standard setting for TRIX is 15 for the triple smoothed EMA and 9 for the signal line. Chartists looking for more sensitivity should try a shorter timeframe (5 versus 15). This will make the indicator more volatile and better suited for centerline crossovers. Chartists looking for less sensitivity should try a longer timeframe (45 versus 15). This will smooth the indicator and make it better suited for signal line crossovers. As with all indicators, TRIX should be used in conjunction with other aspects of technical analysis, such as chart patterns

Changing the Divisor

     All return calculations divide the price change from yesterday to today by the starting value, yesterday’s price. There is no rule that says that you cannot divide the change by the current pricer_t = \frac{Close_t - Close_{t-1}}{Close_t} -1

     While this would result in only small changes, the cumulative effect is said to add stability to an indicator that is based on returns. 虽然这只会导致很小的变化,但据说累积效应会增加基于回报的指标的稳定性

An Oscillator to Distinguish between Trending and Sideways Markets区分趋势市场和横盘市场的振荡器 

     The lack of predictability of trending markets is the greatest problem for the analyst. The work found under the topics “Ranking of Markets for Selection” and “Directional Movement” in Chapter 23 discusses that issue. Based on the idea that the trend component is stronger when price is further from fair value, and the noise (sideways movement) is greater when price is near value, an oscillator can be created to show the strength of the trend component based on this concept,
 Strength \; Oscillator_t = \frac{Average(Close_t - Close_{t-1}, n)}{Average(High_t - Low_t, n)}
if denom !=0 then TSMStrengthOsc = num / denom;

     As the trend increases, the average change in closing prices becomes larger relative to the high-low range for the day.

  • During an unusual period, when the market gaps open, it would be possible for the differences in the closing prices to become larger than the daily range.
  • In a sideways market, both the change in the closes and daily range will get smaller, but the net price change over period n should be close to zero.

This oscillator can be smoothed by taking the change in price over two or three days (for example, Close_t - Close_{t-3} ), rather the most recent day, as well as taking the high-low range over the same number of days

Adding Volume to Momentum

     A momentum indicator can also incorporate volume by multiplying the price change over n periods by the total volume over that same period. The use of the cumulative volume over the period, or even better, the average volume, will help to stabilize the volume有助于稳定交易量, which is often erratic when seen as only one day’s activity. The average volume will appear to be the same magnitude as the volume and can be plotted along with it on a chart. That gives the Momentum-Volume indicator (MV), shown mathematically and in programming notation: 
OR      
     Alternately, the price change over n periods could have been divided by n to give a per unit value. The following sections will include those techniques that combine price change and volume or open interest; for methods that use volume but not price, see Chapter 12.  

Scaling by a Percentage or Volatility按百分比或波动率缩放

     The same conversions can be applied to momentum with and without volume. Using a percentage rather than price will add some robustness over long test periods. Because volatility often increases faster than a fixed percentage of the price when prices rise, momentum can be scaled according to a shorter measure of true range. If the true range is averaged over 20 to 65 days, approximately one month to one quarter, then the 1-day change in price will become a relative momentum value. By using a much longer period for averaging the true range, you can create a stable profile of the volatility changes in the underlying market. 

  • Momentum : {\color{Blue} M}omentum = {\color{Blue} p_t - p_{t-n}}
  • Momentum as a PercentageOne \; day \; momentum \; in \; percent = \frac{p_t - p_{t-1}}{p_{t-1}} = \frac{p_t }{p_{t-1}}-1                                                  1-day momentum is equivalent to the 1-day return                   
     
    the n-day Momentum as a percentage is Mom(n) = \frac{p_t}{p_{t-n}} -1  
  • Percentage momentum with volume \large %MV = \frac{(Close - Close_n) }{Close_n} * average(Volume, n)
  • Momentum with volume scaled by true range

    交易量按真实范围缩放 的动量

    TRMV = \frac{(Close - Close_n)}{average(True Range, p)} * average(Volume,n)
                   = (Close - Close_n) * \frac{average(Volume,n)}{average(True Range, p)}
     
    where TrueRange is always calculated for the most recent period (e.g., 1 day), and the
    average of the 1-day true ranges for the past p days is average(TrueRange,p).

(MFI)Money Flow Index : Volume-Weighted RSI(RSI:Momentum)

     In the same way that the RSI\large \textbf{RSI} = 100 - \left [ 100 \div (1+\frac{Average \; price \; change \; on \; up \; days}{Average \; price \; change \; on \; down \; days}) \right ] accumulates the price changes for positive days and divides by the sum of the negative changes, it is possible to weight each day by its volume to add another factor, called Money Flow, to the calculation.

  • A positive or upwards day is when the average of today’s high, low, and close is greater than the previous average.
  • Each average is then multiplied by the Volume, giving the daily money flow, and a ratio of the past 14 days is used to create Money Ratio and finally a Money Flow Index, both steps similar to Wilder’s RSI.
    • Money Flow Indexmpf11_3_status_plotly Align dual Yaxis_animation_button_MFI_Williams %Rsi_AO Co_VWAP_MAcd_BollingerB_LIQING LIN的博客-优快云博客
       
      • Typical Price =(High  + Low + Close)/3
         Typical \; Price_t = \frac{High_t + Low_t + Close_t}{3}
        For each period, mark whether the Typical Price was higher or lower than the prior period. This will tell you whether Raw Money Flow is positive or negative.
      • Raw Money FlowTypical Price x Volume
        MoneyFlow_t = \frac{(High_t + Low_t + Close_t)}{3} \times Volume_t
      • Money Flow Ratio = (14-period Positive Money Flow)/(14-period Negative Money Flow)
        MoneyRatio_t = \frac{\sum_{i=t-13}^{t} MoneyFlow_i \; , if>0}{\sum_{i=t-13}^{t} MoneyFlow_i \; , if<0}
      • Money flow index
        MoneyFlowIndex_t = \frac{100}{1+MoneyRatio_t}
        OR
         MoneyFlowIndex_t = 100 - \frac{100}{1+MoneyRatio_t}
    • def get_mfi(df, window=14):
          """ get money flow index
          The definition of money flow index is available at:
          https://www.investopedia.com/terms/m/mfi.asp
          :param window: number of periods relevant for the indicator
          :return: None
          """
          column_name = 'mfi_{}'.format(window)
          
          # Typical Price
          middle = (df['Close'] + df['High'] + df['Low']).divide(3.0)
          
          # Raw Money Flow
          money_flow = (middle * df['Volume']).fillna(0.0)
          
          # Money Flow Ratio
          shifted = middle.shift(-1) # backward
          delta = (middle - shifted).fillna(0)
          pos_flow = money_flow.mask(delta < 0, 0)
          neg_flow = money_flow.mask(delta >= 0, 0)
          rolling_pos_flow = pos_flow.rolling(min_periods=1, window=window, center=False).sum()
          rolling_neg_flow = neg_flow.rolling(min_periods=1, window=window, center=False).sum()
          money_flow_ratio = rolling_pos_flow / (rolling_neg_flow + 1e-12)
          
          # mfi = (1.0 - 1.0 / (1 + money_flow_ratio))     # mfi = (100 - 100 / (1 + money_flow_ratio)) 
          mfi = 100 / (1 + money_flow_ratio)# yahoo finance
          mfi.iloc[:window] = 0 # 0.5                      # 50
          df[column_name] = mfi
          
          return df

(HPI)Herrick Payoff Index赫里克支付指数

     Using the change in the underlying value of the futures contract, rather than only the change in price, the Herrick Payoff Index 17 (HPI) combines volume and open interest持仓量/未平仓合约 to generate an indicator that is not bounded as is the basic momentum calculation. The daily value is:
HP_t = cf \times V_t \times ( 1 + \frac{M_t - M_{t-1}}{|M_t - M_{t-1}|}) (\frac{2 \times |OI_t - OI_{t-1}| }{min(OI_t, OI_{t-1})})
HPI = ( smoothedAverage(HP,19 )
Where

  • t = today
  • t−1 = the previous day
  • cf = the Conversion Factor (value of a one big point move)
  • Vt = today’s volume
  • (M_t - M_{t-1}) = the difference in the mean values, M=(high + low)/2,
    |M_t - M_{t-1}| where vertical bars denote absolute value
  • |OI_t - OI_{t-1}| = the absolute value of the change in open interest (for futures)
  • min(OI_t , OI_{t-1}) = the smaller of the open interest for today or the previous day

     The expression that divides the change in mean prices by the absolute value of the same change is used to create a value of +1 or −1. The index HP_t is then scaled down to a manageable value and smoothed using a 0.10 smoothing factor, s (about 19 days). 

     Most analysts who use the Herrick Payoff Index divide the HPI by 100,000 to scale the value to a more usable level (in the example below it is scaled by 1,000,000). The final series, when seen along with prices, may appear volatile and require interpretation, often using trendlines. This is due to the fluctuations in volume and open interest这是由于交易量和未平仓合约的波动, which are smoothed over 20 days, rather than a longer period. The Herrick Payoff Index may be helpful, despite its volatility, because it is a combination of factors not included in most other indexes因为它是大多数其他指数中未包含的因素的组合. It has patterns that appear to lead price change to compensate for its noisy behavior它的模式似乎会导致价格变化,以补偿其嘈杂的行为. 

 FIGURE 9.22 The Herrick Payoff Index applied to the DAX, 2000 through February 2011.

     Figure 9.22 gives an idea of how the HPI reacts to prices, in this case using the German DAX from 2000 through February 2011. It shows higher volatility at the turning points and very low volatility during the upwards trends from 2004 to 2006 and again in 2010. It turns out that volume is a good surrogate for volatility and might actually be a good forecaster of volatility.成交量是波动率的一个很好的替代指标,实际上可能是波动率的一个很好的预测指标 This is discussed in Chapter 12

     The Herrick Payoff Index is a technical analysis tool that tracks price, volume, and open interest
(未平仓合约是未结算的衍生品合约的总数,例如尚未为资产结算的期权或期货。 未平仓合约跟踪特定合约中的每个 未平仓头寸open position,而不是跟踪其中的总交易量,其中可能还包括 净额结算netting 或 平仓头寸closing positions
因此,未平仓合约可以更准确地描述合约的流动性liquidity和利息,确定流入合约的 资金是增加 还是减少
)
to identify potential trends and reversals in futures and options markets. Traders often use the indicator as a measure of crowd psychology and to follow money flows in order to make forward-looking decisions交易者经常使用该指标来衡量人群心理并跟踪资金流向以做出前瞻性决策.

  • The Herrick Payoff is a tool used to confirm price trends or reversals in derivatives markets using price and volume information to track money flows.
  • One advantage of the Herrick Payoff Index is that it can produce signals even in the midst of a trending market.
  • However, because it is forward-looking, the Index can also produce False Positives
    (False Positive (FP): Prediction is +ve(diabetic) and X is healthy,
    false alarm, bad:False Positive is a healthy person(Not target) incorrectly predicted as diabetic(+ve, target) 
    https://blog.youkuaiyun.com/Linli522362242/article/details/103786116
    ), and so should be used in combination with other technical indicators.

Understanding the Herrick Payoff Index

      The Herrick Payoff Index takes account of a derivative contract's price, volume, and open interest to generate bullish and bearish signals. Since open interest is used in the calculation, the technical indicator can only be used in options and futures markets. Most traders use the Herrick Payoff Index to measure crowd psychology in the futures and options markets. In those markets, there is less liquidity than the equity markets and more potential for volatility over time在这些市场中,流动性低于股票市场,但随着时间的推移波动的可能性更大。.

  • Bullish continuation signals are generated when prices and open interest rise since traders are increasingly buying into the contract.
    • In addition, a contract may be poised for a bullish reversal when prices and open interest are falling at the same time because selling pressure is declining as prices are becoming increasingly attractive(fall)
  • Bearish continuation signals are generated when prices are falling, and open interest is rising, since traders are increasingly placing bearish bets.
    • Also, a contract may be poised for a bearish reversal when prices are rising, and open interest is falling, which indicates that bullish traders are losing momentum.

In general, bullish traders are in control when the indicator is above the centerline, and bearish traders are in control when the indicator is below the centerline. However, traders should use the indicator in conjunction with other technical indicators or chart patterns to maximize their odds of placing successful trades.

Benefits of the Herrick Payoff Index

     One feature of the Herrick Payoff Index is the ability to generate exit signals when trends are still underway. As open interest falls, the Herrick Payoff Index indicates that the ongoing price trend is likely to reverse随着未平仓合约的减少,Herrick 支付指数表明当前的价格趋势可能会逆转. With this indicator, traders have the potential to get out before the price even starts to decline. That is very different from many other technical signals, which are lagging indicators. Most notably, any indicator based on moving averages, such as the MACD, will always lag price action in the market最值得注意的是,任何基于移动平均线的指标,例如 MACD,总是会滞后于市场的价格走势. 

     Exiting a trade before a price drop by using the Herrick Payoff Index yields even larger benefits because its home is in the highly volatile futures and options markets. Since these derivatives use such high degrees of leverage, even a small drop in the underlying security price can easily cause significant losses. For example, a stock price decrease of just 5% can lead to a loss of more than 25% for a call option.

Downsides of the Herrick Payoff Index

     The Herrick Payoff Index is, however, often a less reliable guide for entering trades because of the forward-looking nature of its reversal signals. Suppose prices are still declining, but open interest is also falling, as shown by the Herrick Payoff Index. While that may indicate the downward pressure is slowing, it does not mean a rally is imminent/ˈɪmɪnənt/即将发生的. The asset could instead stabilize in price and stay there for a long time相反,该资产可以稳定价格并长期保持不变. Famous trader Jesse Livermore called such securities "listless drifters," and he actually disliked them more than outright losses that he would typically sell right away.

     然而,普通交易者通常更害怕损失,而当基于赫里克支付指数进行交易时,损失才是真正的可能性。 在价格仍在下跌时购买证券违背了投机者的常识,即不应试图抓住掉落的匕首。 事实上,价值投资者经常尝试这样做。 然而,价值投资者很少使用像赫里克收益指数这样的技术指标。

     即使有退出信号,Herrick 收益指数也存在过早移动的风险。 当滞后指标发出错误信号时,他们的追随者至少可以从止损中得到安慰。 由于赫里克支付指数在价格仍在上涨时发出退出信号,因此兴趣可能会恢复,证券可能会继续畅通无阻地上涨。 放弃这样一颗冉冉升起的新星会让许多交易者感到沮丧,尤其是那些经验有限的交易者。

Comments on the Use of Volume

     Volume is an important piece of information, but it can be difficult to interpret. It fluctuates in a much larger range than price, and may be 50% higher or lower from day to day. While it indicates market interest and potential volatility, there are many days for which a high or low volume does not have a consistent reaction高成交量或低成交量并没有一致的反应.

     In general, adding volume to an indicator results in a more volatile, erratic series. Therefore, the first steps in using volume are:

  • 1. Create a long-term, smoothed volume series.
  • 2. Locate days with extremely high volatility to identify only those exceptional days where continued high volatility should follow.
    2. 找出波动性极高的日子,以仅识别那些 应该持续高波动性的特殊日子。
  • 3. Low volume should not be determined by a single day, but by either a few unusually low days clustered together or by a decay in the smoothed volume over a modest time period.
    3. 低成交量不应由某一天决定,而应由 聚集在一起的几个异常低的日子 或由 平滑成交量在适度时间段内的衰减决定

     Using volume to enhance trend signals as well as identifying important volume patterns is discussed in Chapter 12.

Velocity and Acceleration

     In physics, momentum(动量 =质量x速度 when 质量=1 is called speed or ovelocity. It is the amount of change measured over a specific period of time. It is also called rate of change and with regression analysis it is slope, discussed in detail in Chapter 6.

Slope_t = \frac{p_t - p_{t-n}}{x_t - x_{t-n}}
     where the numerator is the change in price and the denominator is the change in the x-axis, which is normally the time, or simply n, elapsed units. For example, when traveling in a car, your speed might be 30 miles per hour. When prices are moving higher, they may be averaging a gain of $1 per week.

     There are two types of velocity: average and instantaneous平均速度和瞬时速度. The average velocity is simply calculated as the mean velocity over a fixed distance and for a fixed time interval. In working with stock and futures prices, the time interval used is days and the distance is measured in points or unit value; if IBM moved $5 in six days, its average velocity is

In general, the average velocity is expressed 
where D = the total elapsed distance over the time interval T

     Velocity is the same as the simple measurement of momentum. For a geometric interpretation of momentum, the change in price, D, can be related to the length of the momentum span, T, giving the same results for average velocity as for slope. Physicists prefer to draw velocity (the average over period T) and instantaneous velocity (the speed at exactly one point) in their own way, shown in Figure 9.23. 
FIGURE 9.23 (a) Average velocity. (b) Instantaneous velocity.

     The instantaneous velocity, v, which is the velocity calculated at a specific point in time, may be different from velocity. In order to determine the instantaneous velocity, a mathematical technique called differentiation is used. It effectively looks at smaller and smaller time intervals and consequently smaller distances on the price curve until the slope calculation is reduced to a single point. The result of the process of differentiation is called the derivative and is expressed v_t = \lim_{\bigtriangleup_{t \rightarrow 0} }\frac{\bigtriangleup D}{\bigtriangleup t} = \frac{dD}{dt}

     This shows that the velocity taken at any point is the result of the time interval (t) becoming progressively smaller without actually reaching zero. The symbol delta (∆) represents the change in price (∆D) and the corresponding change in time (∆t). The rules for differentiation can be found in any advanced mathematics book. Only the results are presented here. The velocity v_t represents the speed or momentum of the price at the point in time t. If v gets larger for t_0 , t_1, t_2 , . . ., then the velocity is increasing; if v gets smaller, the velocity is decreasing. Because the velocity also denotes direction, it can be both positive and negative in value and appear similar to a momentum indicator.

     Acceleration is the change in velocity. In the same way that we find the change in price D over time period t, we can find the change in velocity over time period t. Therefore, if you are driving at 30 miles per hour when you enter the acceleration ramp of the motorway, and after one minute you are driving 60 miles per hour, you have changed speed, or accelerated, at the rate of 30 miles per hour per minute. Fortunately, we do not need to be concerned about the units of time when we apply these techniques to prices. The units are always the same, whatever they are. When S&P prices have been moving higher at an average speed of 10 points per week and then begin posting increases of 15 points per week, then 20 points per week, prices are accelerating at the rate of 5 points per week. Mathematically, velocity can be substituted for price in the equation for v_t to get acceleration, a_t.
a_t = \lim_{\bigtriangleup_{t \rightarrow 0} }\frac{\bigtriangleup V}{\bigtriangleup t} = \frac{dV}{dt} 

     The short-cut to finding velocity and acceleration is to take the first and second differences, each step removing first the trend, then the speed, leaving the more sensitive components plus noise每一步首先去除趋势,然后去除速度留下更敏感的成分加上噪声.

Finding the Velocity and Acceleration of Different Techniques

     Differentiation can be applied to many different formulas that have been discussed previously, including those that represent a straight line, curved lines, and various other trendlines. The result of the first differentiation gives you the component that represents velocityv_t = \lim_{\bigtriangleup_{t \rightarrow 0} }\frac{\bigtriangleup D}{\bigtriangleup t} = \frac{dD}{dt}, and the result of the second differentiation is the component of accelerationa_t = \lim_{\bigtriangleup_{t \rightarrow 0} }\frac{\bigtriangleup V}{\bigtriangleup t} = \frac{dV}{dt}. Of course, some of the basic equations have constant velocity and cannot be used for a velocity trading plan because the values never change. The straight line, simple and weighted moving averages, and exponential smoothing all have constant velocities. Only those equations with second-order smoothing will work. Table 9.4 gives basic equations along with their first and second derivatives.
 

Basic EquationVelocity at X_t^*Acceleration at X_t ^*
Straight Liney_t = a + bx_tv_t = ba_t =0
Curvilineary_t = a + bx_t + cx_t^2v_t = b + 2cx_ta_t =2c
Logarithmic
(base a)
y_t = log_a x_tv_t = \frac{log_a e}{x_t} or v_t = \frac{log_e e}{x_t log_e a}=\frac{1}{x_t ln a}a_t = \frac{0 -(x_t)'}{x_t^2}*\frac{1}{lna}
a_t =\frac{ -1}{x_t^2 lna}
Logarithmic
(natural log)
y_t = ln x_tv_t = \frac{1}{x_t}a_t = \frac{0-x_t'}{x_t^2}
a_t = \frac{1}{x_t^2}
Exponentialy_t = e^{ax_t}v_t = ae^{ax_t}a_t = a^2 e^{ax_t}
Moving Averagey_t = \frac{x_t + x_{t-1} + ... + x_{t-n+1}}{n}v_t = 1a_t =0
Weighted Moving Averagey_t = \frac{a_1 x_t + a_2 x_{t-1} + ... + a_n x_{t-n+1}}{n}v_t = \frac{a_1 + a_2 + ... + a_n}{n}a_t = 0
Exponential Smoothingy_t = y_{t-1} + c(x_t -y_{t-1})v_t = ca_t = 0

     Because velocity and acceleration are time derivatives, all equations implicitly include the factoras part of the right member.

     Let’s assume that the velocity and acceleration have been calculated as in Table 9.4. The following are the possible combinations that can occur:

VelocityAccelerationPrice Movement
++Price is moving up at an increasing rate
+0Price is moving up at a constant rate
+-Price is moving up at a decreasing rate
00Price is static
-+Price is moving down at a decreasing rate
-0Price is moving down at a constant rate
--Price is moving down at an increasing rate

     Using acceleration, a change of velocity (or momentum) can be detected or the strength of a current price move can be confirmed.

Using Velocity and Acceleration to Identify a Sideways Market使用速度和加速度来识别横向市场

     The combination of velocity and acceleration can give a good indication of whether prices are moving in a directional or sideways pattern. When velocity is near zero, the average speed of price movement is near zero. It is also the same as saying that prices have netted no movement over the time interval . However, that is not enough. 

     During the interval T, prices may have moved sharply higher then sharply lower. By chance, they are unchanged after time T although they are still moving lower quickly. The acceleration will tell you that prices are moving even though they are at the same level as periods ago. To identify a sideways pattern, both the velocity and acceleration must be near zero.

Quick Calculation of Velocity and Acceleration

     A less precise but very convenient way of isolating velocity and acceleration is the calculation of first and second differences. The purpose of these values is to find more sensitive indicators of price change, and most traders find this quick calculation satisfactory. The results can be used in exactly the same way as the formal mathematical results. Consider the following two examples:

  • 1. A price series 10, 20, 30, 40, . . . is moving higher by a constant value each day. The first differences are 10, 10, 10, . . ., showing a consistent velocity of 10. The second differences, formed by subtracting sequential values in the first-difference series, are 0, 0, 0, . . ., showing that there is no change in speed; therefore the acceleration is zero.
  • 2. Another price series is shown with its first and second differences as
    Time123456789101112
    Series101520304550453525202540
    Velocity+5+5+10+15+5-5-10-10-5+5+15
    Acceleration0+5+5-10-10-50+5+10+10
         where velocity values are the first differences, and acceleration the second differences. The original series has two turns in the trend direction clearly shown by the velocity and acceleration as changes in the sign of the numbers. The velocity continues to be positive through the sixth value as the underlying price moves from 10 to 50.
    • Whenever prices change direction, the velocity changes sign.
    • The basic upward trend can be associated with a positive velocity and
    • a downward trend with a negative one.

     The acceleration shows the change in speed. At the sixth item, the acceleration becomes negative, even though the velocity was positive, because prices moved higher at a slower rate. They had been gaining by 5, 10, and 15 points each day, but on day 6 the gain was only 5 points. This reversal in acceleration was a leading indicator of a trend change. A similar situation occurred on day 8, when the acceleration slowed and reversed on day 10, one day ahead of the actual price reversal(on day 11, on day 7)

Hybrid Momentum Techniques

Combining a Trend and an Oscillator

Directional Parabolic System

     The Directional Parabolic System is a combination of two of Wilder’s well-known techniques, Directional Movement and the Parabolic Time/Price System. Directional Movement is covered fully in Chapter 23. It gained popularity as a method of selecting the futures markets that were most likely candidates for trend-following systems. The Parabolic Time/Price System is covered in Chapter 17. Although a full reading of both techniques is necessary, the essence of the combined systems may be understood with the following definitions:

  • +DM14
    • The 14-day upward Directional Movement, the sum of the current high prices minus the previous high prices.
    • +DM = Current High − Previous High
  • −DM14
    • The 14-day downward Directional Movement, the sum of the previous low prices minus the current low prices.
    • −DM = Previous Low−Current Low
  • Use +DM when current high - previous high > previous low - current low.
    UpMove = Current High − Previous High
    DownMove = Previous Low−Current Low

    if UpMove > DownMove and UpMove > 0,
       then +DM = UpMove
    else
       +DM = 0   #A negative value would simply be entered as zero

    Use -DM when previous low - current low > current high - previous high.
    if DownMove > UpMove and DownMove > 0,
       then -DM = DownMove,
    else
       -DM = 0   #A negative value would simply be entered as zero

  • ADX The Average Directional Movement Index, calculated by smoothing the Ratio of the net of +DM14 and −DM14 by the sum of the same values.
    • TR is the greater of the current high - current low, current high - previous close, or current low - previous close

      • Smooth the 14-period averages of +DM, -DM, and TR—the TR formula is below. Insert the -DM and +DM values to calculate the smoothed averages of those.
        Smooth the 14-period averages of TR

        • First TR14 = sum of first 14 TR
        • Second TR14 = First TR14 - (First TR14/14) + Current TR1

        • Subsequent Values = Prior TR14 - (Prior TR14 /14) + Current TR1

    • Next, divide the smoothed +DM value by the smoothed TR value to get +DI. Multiply by 100.

    • Divide the smoothed -DM value by the smoothed TR value to get -DI. Multiply by 100.

    • The directional movement index (DMI) is

      • +DI minus -DI, divided by the sum of +DI and -DI (all absolute values). Multiply by 100.

    • To get the ADX, continue to calculate DX values for at least 14 periods. Then, smooth the results to get ADX.
      Average Directional Index

      • First ADX14 = 14 period Average of DX = sum( 14 periods of DX )/ 14

      • Second ADX14 = ( (First ADX14 * 13) + Current DX Value )/14 

      • Subsequent ADX14 = ( (Prior ADX14 x 13) + Current DX Value )/14

  • def get_adx(df, window=14):
            """ get the default setting for Average Directional Index(Average Directional Movement Index)
            """
            # +DM = current high - previous high
            # -DM = previous low - current low
            dm = pd.DataFrame( dict(enumerate([ df['High'] - df['High'].shift(1, fill_value=np.nan), 
                                                df['Low'].shift(1,fill_value=np.nan) - df['Low']
                                              ])
                                   )
                             )
            #                             +DM>0      +DM > -DM
            df['+dm'] = dm.apply( lambda m: max(m[0],0) if m[0]>m[1] else 0, axis=1)
            #                             -DM>0      -DM > +DM
            df['-dm'] = dm.apply( lambda m: max(m[1],0) if m[1]>m[0] else 0, axis=1)        
            
            df['tr']=pd.DataFrame(dict(enumerate([df['High']-df['Low'],
                                                  abs( df['High']-df['Close'].shift(1) ),
                                                  abs( df['Low']-df['Close'].shift(1) )
                                                 ])
                                      )
                                 ).apply(max,axis=1)
            df.loc[df.index[0],['+dm', '-dm', 'tr']]=np.nan # for window
            def smooth(col):
     
                sm=col.rolling(window).sum()   
                for i in list( range( window+1,len(col) ) ):
                    #sm.iloc[i]=sm.iloc[i-1]-(1.0*sm.iloc[i-1]/window)+col.iloc[i]
                    sm.iloc[i]=col.iloc[i] + (1.0-1.0/window)*sm.iloc[i-1]
     
                return sm
                
            def smooth2(col):
                sm=col.rolling(window).mean()
                for i in list( range( window*2,len(col) ) ):
                    #sm.iloc[i]=((sm.iloc[i-1]*(window-1))+col[i])/window
                    sm.iloc[i]=(1.0/window)*col.iloc[i] + (1-1.0/window)*sm.iloc[i-1]
     
                return sm
            
            df['smoothed +dm'] = df.loc[:,['+dm']].apply(smooth)
            df['smoothed -dm'] = df.loc[:,['-dm']].apply(smooth)
            df['smoothed tr'] = df.loc[:,['tr']].apply(smooth)
     
            df['+di_{}'.format(window)] = 100.0 * df['smoothed +dm'] / df['smoothed tr']
            df['-di_{}'.format(window)] = 100.0 * df['smoothed -dm'] / df['smoothed tr']
            
            df['di_{}_diff'.format(window)]=(df['+di_{}'.format(window)] - df['-di_{}'.format(window)])
            
            df['dx_{}'.format(window)] = 100.0 *abs( df['di_{}_diff'.format(window)] ) /\
                                                ( df['+di_{}'.format(window)] + df['-di_{}'.format(window)] )
            
            df['adx_{}'.format(window)] = df.loc[:,['dx_{}'.format(window)]].apply(smooth2)
     
            df.drop(columns=['smoothed +dm', 'smoothed -dm', 'smoothed tr',
                             '+dm', '-dm', 'tr',
                             'dx_{}'.format(window)
                             ], 
                    inplace=True
                   )
            return df

    mpf11_6_plotly update xaxis w dropdown menu_justify_Parabolic SAR_ADX smoothed TR/DM_Multicollineari_LIQING LIN的博客-优快云博客

  • DPS
    The Directional Parabolic stop-loss定向抛物线止损
    • The parabolic SAR(Stop And Reverse) is used to gauge a stock's direction and for placing stop-loss orders. The indicator tends to produce good results in a trending .

      There are lots of things to track when using the parabolic stop and reverse indicator. One thing to constantly keep in mind is that if the SAR is initially rising, and the price has a close below the rising SAR value, then the trend is now down and the falling SAR formula will be used. If the price rises above the falling SAR value, then switch to the rising formula.
      要始终记住的一件事是,如果 SAR 最初是上升的,并且价格 收盘价 低于当前上升的 SAR 值,那么趋势现在是下降的,将使用下降的 SAR 公式。 如果价格上涨超过下跌的 SAR 值,则切换到上涨公式
          rising_i, ep_i, af_i = True, max(high[0:start]), af
          sar = [min(low[0:start])]*start
          bull_sar = [np.nan]*start
          bear_sar = [min(low[0:start])]*start
          #OR
      #     rising_i, ep_i, af_i = False, min(low[0:start]), af
      #     sar = [max(high[0:start])]*start
      #     bull_sar = [max(high[0:start])]*start
      #     bear_sar = [np.nan]*start
       
      • 1. Monitor price for at least five periods or more, recording the high and low (EPs).
        至少监控五个周期或更多周期的价格,记录最高价和最低价 (EP : Extreme Point)
        ep_i = max(high[0:start]) if rising_i==True
        OR
        ep_i = min(low[0:start]) if rising_i==False    default
      • 2. If the price is rising(rising_i==True), use the lowest low of those five periods(start=5) as the prior SAR value in the formula. default
        sar = [min(low[0:start])]*start
      • 3. If the price is falling(rising_i==False), use the highest high of those periods as the initial prior SAR value.
        sar = [max(high[0:start])]*start                        default
      • 4. Use an AF of 0.02 initially, and increase by 0.02 for each new extreme high (rising) or low (falling). The maximum AF value is 0.2
      • 5. reversal:
        if prior_rising==True:
                                 ==>rising_i = False
        elif prior_rising=False:
                                  ==>rising_i=True  
            for i in range(start, len(df)):
                prior_rising, prior_ep, prior_af = rising_i, ep_i, af_i # from last step
                # Current Rising SAR = Prior SAR + Prior AF * (Prior EP - Prior SAR)
                # Current Falling SAR = Prior SAR - Prior AF * (Prior SAR - Prior EP)
                # ==> Current SAR = Prior SAR + Prior AF * (Prior EP - Prior SAR)
                sar_i = sar[-1] + (prior_ep - sar[-1])*prior_af
                
                min_low = min(low[i - 1], low[i])
                max_high = max(high[i - 1], high[i])
                
                # same trend and trend switch
                if prior_rising: # Rising==True
                    # rising_i=True : Continue to be bullish
                    # (sar[-1]>=low[i]) ==>rising_i=False : trend switch
                    rising_i = (low[i] > sar[-1]) or (low[i] > sar_i) # rising_i==True :the price is continue to rising, False : trend switch
                    ep_i = max(max_high, prior_ep)
                    
                else: # Falling==False
                    # rising_i=True : trend switch, 
                    # (sar[-1]>=high[i])==> rising_i=False : Continue to be bearish
                    rising_i = (high[i] > sar[-1]) or (high[i] > sar_i)
                    ep_i = min(min_low, prior_ep)
    • Rising SAR

      • Prior SAR:
                        The SAR value for the previous period

      • Extreme Point (EP):
                        The highest high of the current uptrend.
        # ep_i = max(max_high, prior_ep)

      • Acceleration Factor (AF):
                        Starting at .02, AF increases by .02 each time the Extreme Point makes a new high.
        AF can reach a maximum of .20, no matter how long the uptrend extends. 

      • Current SAR = Prior SAR + Prior AF * (Prior EP - Prior SAR)
        13-Apr-10 SAR =  48.13 + .14*(49.20 - 48.13) = 48.2798

      • The Acceleration Factor is multiplied by the difference between the Extreme Point and the Prior period's SAR. This is then added to the Prior period's SAR.

      • Note however that SAR can never be above the prior two periods' lows. Should SAR be above one of those lows, use the lowest of the two for SAR.如果 SAR 高于这些低点之一,则使用两者中的最低值作为 SAR。

    • Falling SAR
      • ​​​​​​Prior SAR:
      •                 The SAR value for the previous period

      • Extreme Point (EP):
                        The lowest low of the current downtrend.
        #  ep_i = min(min_low, prior_ep)

      • Acceleration Factor (AF):
                        Starting at .02, AF increases by .02 each time the Extreme Point makes a new low.
        AF can reach a maximum of .20, no matter how long the downtrend extends. 

      • Current SAR = Prior SAR - Prior AF * (Prior SAR - Prior EP)9-Feb-10 SAR  = 43.84 - .16*(43.84 - 42.07) = 43.56

      • The Acceleration Factor is multiplied by the difference between the Extreme Point and the Prior period's SAR. This is then subtracted from the Prior period's SAR.

      • Note however that SAR can never be below the prior two periods' highs. Should SAR be below one of those highs, use the highest of the two for SAR. 如果 SAR 低于其中一个高点,则使用两者中的最高点作为 SAR.

    • import numpy as np
       
      def get_SAR(df, af=0.02, af_max=0.2, af_increment=None, start=5):
          # af : Acceleration Factor(AF), the default parameters are 0.02 for the Starting Step
          # af_max : AF can reach a maximum of .20
          # af_increment : set the increment amount
          # start : Monitor price for at least five periods or more, recording the high and low
          # ep : Extreme Point (EP) of the current trend
          high = df['High'].values
          low = df['Low'].values
          
          # Starting values
          if af_increment==None:
              af_increment=af
              
          rising_i, ep_i, af_i = True, max(high[0:start]), af
          sar = [min(low[0:start])]*start
          bull_sar = [np.nan]*start
          bear_sar = [min(low[0:start])]*start 
          #OR
      #     rising_i, ep_i, af_i = False, min(low[0:start]), af
      #     sar = [max(high[0:start])]*start
      #     bull_sar = [max(high[0:start])]*start
      #     bear_sar = [np.nan]*start
          psar_signal = [np.nan]*start
          
          for i in range(start, len(df)):
              prior_rising, prior_ep, prior_af = rising_i, ep_i, af_i # from last step
              # Current Rising SAR = Prior SAR + Prior AF * (Prior EP - Prior SAR)
              # Current Falling SAR = Prior SAR - Prior AF * (Prior SAR - Prior EP)
              # ==> Current SAR = Prior SAR + Prior AF * (Prior EP - Prior SAR)
              sar_i = sar[-1] + (prior_ep - sar[-1])*prior_af
              
              min_low = min(low[i - 1], low[i])
              max_high = max(high[i - 1], high[i])
              
              # same trend and tren switch
              if prior_rising: # Rising==True
                  # rising_i==True : Continue to be bullish, (sar[-1]>=low[i])False : trend switch
                  rising_i = (low[i] > sar[-1]) or (low[i] > sar_i) # rising_i==True :the price is continue to rising, False : trend switch
                  ep_i = max(max_high, prior_ep)
                  
              else: # Falling==Fals
                  # rising_i==True : trend switch, (sar[-1]>=high[i])False : Continue to be bearish
                  rising_i = (high[i] > sar[-1]) or (high[i] > sar_i)
                  ep_i = min(min_low, prior_ep)
                  
              if rising_i == prior_rising: # same trend 
                  # for next step
                  # AF can reach a maximum of .20
                  af_i = min(af_max, prior_af + af_increment) # af_increment = .02
       
                  if rising_i:# rising sar
                      # AF increases by .02 each time the extreme point(ep) makes a new high
                      af_i = af_i if ep_i > prior_ep else prior_af
                      # Note : SAR can never be above the prior two periods' lows
                      # SAR can never be above the prior two periods' lows
                      sar_i = min(sar_i, min(low[i-2:i]) )#min(low[i-2:i-1])
                      bull_sar.append(sar_i)
                      bear_sar.append(np.nan)
                  else: # Falling SAR
                      # AF increases by .02 each time the extreme point(ep) makes a new low
                      af_i = af_i if ep_i < prior_ep else prior_af
                      # Note : SAR can never be below the prior two periods' highs.
                      # SAR can never be below the prior two periods' highs
                      sar_i = max(sar_i, max(high[i-2:i]) )
                      bull_sar.append(np.nan)
                      bear_sar.append(sar_i)
                  psar_signal.append(np.nan)
              else: # a trend switch
                  # the first SAR value for this new trend is set to the last EP recorded on the prior trend
                  sar_i = ep_i
                  # the acceleration factor is reset to its initial value of 0.02
                  af_i = af
                  
                  if prior_rising: # Rising
                      ep_i = min(min_low, prior_ep) # EP is then reset accordingly to this period's minimum     
                      bull_sar.append(np.nan)
                      bear_sar.append(sar_i)
                      psar_signal.append('sell')
                  else: # Falling
                      ep_i = max(max_high, prior_ep) # EP is then reset accordingly to this period's maximum              
                      bull_sar.append(sar_i)
                      bear_sar.append(np.nan)
                      psar_signal.append('buy')
              sar.append( sar_i )
          
          #df['sar']=sar
          df['bear_sar']=bear_sar
          df['bull_sar']=bull_sar
          df['psar_signal']=psar_signal
          sar=None
          return df

Although shown as SmoothedDM14, the downward Directional Movement is a positive number
(dm
= pd.DataFrame( dict(enumerate([ df['High'] - df['High'].shift(1, fill_value=np.nan)
                                                               df['Low'].shift(1,fill_value=np.nan) - df['Low']
                                          ])
                               )
                         )
df['-dm'] = dm.apply( lambda m: max(m[1],0) if m[1]>m[0] else 0, axis=1)
)
based on the sum of those days that closed lower
(

        def smooth(col):
 
            sm=col.rolling(window).sum()   
            for i in list( range( window+1,len(col) ) ):
                #sm.iloc[i]=sm.iloc[i-1]-(1.0*sm.iloc[i-1]/window)+col.iloc[i]
                sm.iloc[i]=col.iloc[i] + (1.0-1.0/window)*sm.iloc[i-1]
 
            return sm




ADX=\frac{ADX_{previous}*(14 -1)+DX_{current}}{14}
). The ADX ADX=\frac{ADX_{previous}*(14 -1)+DX_{current}}{14} representing the positive direction of the index. Therefore, the ADX is an oscillator such that, when its value is greater than 50, it means that price movement is upwards. Directional Movement is combined with the Parabolic Time/Price System according to the following rules:

  • 1. If the ADX is up, take only long Parabolic System trades;
    • if the ADX is down, take only short trades.
  • 2. If the two systems conflict, no trade is entered. A trade may be entered at the time they agree.
  • 3. If a position is held, the Parabolic Stop is used. (The stop is now called the DPS instead of the SAR because it no longer requires a reversal of position.)
    3. 如果持仓,则使用抛物线止损。 (该止损现在称为 DPS 而不是 SAR,因为它不再需要反转头寸。)
  • 4. If no position is held, the Directional Movement equilibrium point is used (the high or low of the day on which the +DM14 crosses the −DM14).
    4. 如果没有持仓,则使用方向运动平衡点(+DI 与-DI 交叉的当天的高点或低点)。

     In 1980, the entry rules were revised to include an added use of the ADX when it is greater than the +DM14or the -DM14. Because the ADX is an oscillator and indicates turning points in the trend,

  • when the ADX exceeds the magnitude of the current +DM14 or −DM14 and reverses, the current position should be closed out.
  • If the ADX re- mains above both the +DM14 and −DM14, the market is extremely strong, and liquidation should stop.
  • The ADX is intended to be a leading indicator for liquidation only.
  • Reversal of the current position only occurs when the DPS has been penetrated and the new trade agrees with the direction of the Parabolic System

     The addition of an oscillator to a trend-following system allows trades to be closed out at more favorable prices than the usual trend exits. If the new direction carries through and the position is reversed, the added feature has worked perfectly; however, if prices turn back in the original direction, a re-entry may not be possible. The revised rules are unclear concerning re-entry into a position if prices fail to penetrate the DPS and signal a reversal. A re-entry might occur if the ADX falls below both the +DM14 and −DM14, indicating that prices are no longer extreme, then turns back in the trend direction. Once re-established, the DPS can be used and additional exits using the revised rules would apply.

Oscillator Method with ADX Filter

     A simple variation from Lars Kestner creates an oscillator from two moving averages, then uses the ADX to show a lack of trend. The rules are

Osc = average(close,10) – average(close,50)
If osc < osc[1] and ADX(14) < 30 
    then sell next open
If osc > osc[1] and ADX(14) < 30 
    then buy next open
If osc > osc[1] 
    then buy to cover next open
If osc < osc[1] 
    then sell next open

     Buy to cover refers to a buy order made on a stock or other listed security to close out an existing short position. A short sale involves selling shares of a company that an investor does not own, as the shares are borrowed from a broker but need to be repaid at some point.

Using a Oscillator as Timing for a Trend System使用振荡器作为趋势系统的时间

      One point of irritation/ˌɪrɪˈteɪʃ(ə)n/恼怒,生气 is that trend entries always seem to be poorly timed似乎总是不合时宜. Traders would prefer to wait for pullback after a buy or sell signal to enter at a better price. This can be done using an oscillator of a much shorter calculation period than the trend. One choice would be

1. Calculate a 40-day moving average
2. Calculate a 5-day stochastic indicator
3. Buy when the 40-day trend is up and the 5-day stochastic < 20
4. Sell when the 40-day trend is down and the 5-day stochastic > 80

     It may also be better to enter trades using this timing method but exit immediately when the trend changes. Waiting for just the right point to exit may result in very high risk if the market is moving the wrong way. In order to avoid missing a trade entirely, a rule can be added that forces entry after n days following the initial signal. 

Cambridge Hook

     An indicator that combines Wilder’s RSI with other basic indicators is the Cambridge Hook. It is intended to identify an early reversal of the current trend by combining 3 indicators. The following conditions must occur in an existing upwards trend:

  • • An outside reversal day (a higher high followed by a lower close).
  • • Wilder’s RSI must exceed 60% (moderately overbought适度超买).
  • Volume and open interest must be increasing
    avgVolume_t > avgVolume_{t-1}
    avgOpenInterest_t > avgOpenInterest_{t-1}

     The result is a high likelihood of a downward trend reversal (the opposite applies to upward trend reversals). Protective stops are placed above the high of the hook on the day that signaled a downward reversal. The program function TSMCambridgeHook, available on the Companion Website, returns a “1” when an upwards hook occurs and a “–1” when a downwards hook occurs. These events should be filtered with a trend direction

Input: InputName(NumericSimple);

 Where:

InputName - an expression specifying the input name. The input name can consist of letters, underscore characters, numbers, and periods. The input name cannot begin with a number or a period and is not case-sensitive.

Declare Length as a Numerical Simple function input: 

Input: Length(NumericSimple);
  inputs: length(numericsimple), vlength(numericsimple);
  vars:   avgv(0), avgoi(0);

  TSMCambridgeHook = 0;
  if vlength < 2 
     then begin
			avgv = volume;
			avgoi = openinterest;
		  end
     else begin
			avgv = average(volume,vlength);     
			avgoi = average(openinterest,vlength);
	      end;
 if high > high[1] and close < close[1] and 
    RSI(close,length) > 60 and avgv > avgv[1] and avgoi > avgoi[1]
        then TSMCambridgeHook = -1
 else if low < low[1] and close > close[1] and 
    RSI(close,length) < 40 and avgv > avgv[1] and avgoi > avgoi[1]
        then TSMCambridgeHook = 1;

     Note that using the open interest may be a problem. While volume is available through the day for most futures markets, open interest is not as easily available. Because of that, the program TSM Cambridge Hook, on the Companion Website, has the option of not using open interest.

Momentum Divergence动量背离

     Divergence occurs when two price series move apart.

  • The Dow Jones Industrials道琼斯工业指数 and Dow Jones Utilities道琼斯公用事业指数 are diverging if the Industrials are rising while the Utilities are falling.
    • This divergence between these two markets has always been considered a leading indicator of a downturn in the economy.
  • The S&P 500 is also watched in relationship to the 10-year Treasury note 10 年期美国国债, the benchmark long-term rate.
    • Notes usually counterbalance moves in the stock market.
    • When the S&P rallies/ ˈræliz /价格回升 at a fast pace, the price of notesfalls to reflect the anticipation of an increase in interest rates needed to dampen/ ˈdæmpən /抑制 growth.
    • When the S&P and the price of notes both rise, or both fall, something special is happening.  
  • When prices diverge with respect to a technical indicator, such as an unsmoothed momentum or the MACD, the direction of prices is expected to follow the direction of momentum.
    • You can visualize the price chart needed for divergence as the rising part of a rounded top. Prices are still going up but at a slower and slower rate.您可以将背离所需的价格图表可视化为圆顶的上升部分。 价格仍在上涨,但速度越来越慢。

     Momentum divergence is measured by comparing the direction of prices with the direction of a momentum indicator over the same time interval. Most often, this is done by connecting the peaks of the price movement when prices are rising (or the valleys of the price declines). Connecting only the peaks and valleys of both prices and momentum avoids the problems associated with erratic data. Figure 9.24 shows three examples of a 20-day momentum divergence for Intel. FIGURE 9.24 Momentum divergence.

     A bearish divergence is one that anticipates a downturn in prices. Because momentum is a leading indicator, a bearish divergence occurs when prices are rising and the momentum values are falling.

  • This can be seen in the middle of Figure 9.24 where line 2 (top panel) shows sharply rising prices at the same time that line B (bottom panel) shows clearly falling momentum values. Price follows momentum, and a sharp decline lasts for all of December 2002. 

     A bullish divergence is formed when prices are declining while momentum values are rising.

  • Two examples of a bullish divergence can be seen in Figure 9.24 marked with 1 and 3 on the price chart and A and B on the momentum indicator

The important points to remember about a divergence are:

  • Prices and momentum must be moving in opposite directions. It is not correct to say there is a bullish divergence when momentum is rising quicklywhile prices are moving sideways or slightly higher. They must be moving in opposite directions.
  • • The greater the divergence, the more likely prices will change direction soon. That is,
    • when pricesare moving up very sharply and momentum is clearly moving lower,
    • then the likelihood of an immediate change of direction for prices is much greater than
    • if priceswere gradually rising while the momentum was slowly falling.
  • • A bearish divergence can be interpreted as a market that is rising slower and slower. Each successive peak makes a smaller advance, and each successive peak occurs after more and more time has elapsed. This may appear similar to a rounded top before prices start down.
    看跌背离可以解释为市场上涨越来越慢。 每个连续的峰值都会有一个较小的前进,并且每个连续的峰值都会在越来越多的时间过去后出现。 这可能看起来类似于价格开始下跌之前的圆形顶部。
  • Divergence that occurs over a longer time period (for example, months) will forecast a larger price reversal than a divergence formed over hours or days.

Divergence is best when the momentum indicator begins at an extreme high or low level, indicating that the price move is extended. It is particularly good if the divergence signal occurs while momentum is still well above or below the midpoint of the indicator values, either 50 or 0. That assures us that a price correction can occur before the indicator returns to neutral.

股市调整(stock market correction)是指市场或个股短暂下跌 10% 至 20%以纠正人为抬高的股价和不可持续的增长。 它们通常会持续几个月,但有些只会持续几天。 股市调整可能由于多种原因而发生. 之所以称为修正,是因为从历史上看,下跌通常会“修正”并将价格恢复到长期趋势

An Amazon.com Example Using Momentum Peaks

FIGURE 9.25 An example of divergence in Amazon.com.

     Momentum divergence is an important concept. The following example, applied to Amazon.com in Figure 9.25, uses the method of momentum peaks with MACD, plus an additional rule. Use the following steps: 

  • 1. Find the swing highs on the chart. This can be done simply by looking at the highest peaks. In Figure 9.25 there are two significant peaks, one in January 1999 and the other at the end of April 1999.
    • There is a peak slightly earlier in April; however, that is part of the price move that ends with a rally to 11 0.
  • 2. Draw a line connecting the January and April peaks.
  • 3. There will be two corresponding peaks in the MACD lines directly below the price chart. Connect the two peaks in the MACD line.
  • 4. The line drawn across the price highs is clearly rising. The line across the MACD peaks is clearly falling; therefore, the pattern indicates a bearish divergence.
  • a Prices confirm the divergence by dropping from 110 to 70 in less than two weeks, and then below 50 in the same move

     There is also an unmarked bullish divergence on the chart图表上也存在不明显的看涨背离. Prices bottom in June and August with clearly rising lows in the MACD occurring at the same time. The August price low marks the bottom of the move and a rally/ ˈræli /(价格)回升 follows

Trading Rules for Divergence

     There are a number of alternative rules for trading a momentum divergence, each differing in the amount of anticipation.

MACD Divergence

     The simplest rules are based on using the MACD as the indicator to create a bearish divergence. Once the second rising price peak is identified, along with the corresponding MACD peak, the divergence sell signal comes when the MACD line crosses the MACD signal line as it moves lower. This is seen in Figure 9.25 at the end of April. The trade is exited when the MACD value becomes 0, or if a price objective is reached, based on a top formation. It is possible to extend the trade by waiting for the MACD line to cross back over the signal line before exiting. The same rules apply to a bullish divergence.

     信号线交叉是最常见的 MACD 信号。 信号线是 MACD 线的 9 天 EMA。 作为指标的移动平均线,它落后于 MACD 并且更容易发现 MACD 转向。

  • MACD 向上并穿过信号线时,出现bullish crossover
  • MACD 向下并穿过信号线下方时,出现bearish crossover
  • 交叉可以持续几天或几周,具体取决于移动的强度。
  • The chart shows IBM with its 12-day EMA (green), 26-day EMA (red) and the 12,26,9 MACD in the indicator window. There were 8 signal line crossovers in six months: four up and four down. There were some good signals and some bad signals.
    • The yellow area highlights a period when the MACD line surged above 2 to reach a positive extreme(应谨慎查看正极端或负极端的信号线交叉。 尽管 MACD 没有上限和下限,但图表师可以通过简单的视觉评估来估计历史极值).
    • There were 2 bearish signal line crossovers in April and May, but IBM continued trending higher. Even though upward momentum slowed after the surge, it was still stronger than downside momentum in April-May.
    • The third bearish signal line crossover in Jun resulted in a good signal.

Centerline crossovers are the next most common MACD signals.

  • A bullish centerline crossover occurs when the MACD line moves above the zero line to turn positive. This happens when the 12-day EMA of the underlying security moves above the 26-day EMA.
  • A bearish centerline crossover occurs when the MACD line moves below the zero line to turn negative. This happens when the 12-day EMA moves below the 26-day EMA
  • Centerline crossovers can last a few days or a few months, depending on the strength of the trend.
  • The MACD will remain positive as long as there is a sustained uptrend.
  • The MACD will remain negative when there is a sustained downtrend
  • The chart shows 3M (MMM) with a bullish centerline crossover in late March 2009 and a bearish centerline crossover in early February 2010. This signal lasted 10 months. In other words, the 12-day EMA was above the 26-day EMA for 10 months. The resulting signal worked well since the strong trend
  • The chart of Cummins Inc (CMI) with seven centerline crossovers in five months. But, these signals would have resulted in numerous whipsaws because strong trends did not materialize after the crossovers.这些信号会导致大量洗盘,因为在交叉之后没有出现强劲趋势

     Divergences form when the MACD diverges from the price action of the underlying security. A bullish divergence forms when a security records a lower low and the MACD forms a higher low. The lower low in the security affirms the current downtrend, but the higher low in the MACD shows less downside momentum. Despite decreasing, downside momentum is still outpacing upside momentum as long as the MACD remains in negative territory尽管下降,但只要 MACD 仍处于负区域下行势头仍超过上行势头. Slowing downside momentum can sometimes foreshadow a trend reversal or a sizable rally下行势头放缓有时预示着趋势逆转或大幅反弹.

The chart shows Google (GOOG) with a bullish divergence in October-November 2008.

  • First, notice that we are using closing prices to identify the divergence. The MACD's moving averages are based on closing prices and we should consider closing prices in the security as well.
  • Second, notice that there were clear reaction lows (troughs) as both Google and its MACD line bounced in October and late November.
  • Third, notice that the MACD formed a higher low as Google formed a lower low in November.
    The MACD turned up with a bullish divergence and the subsequent signal line crossover in early DecemberGoogle confirmed a reversal with a resistance breakout.

A bearish divergence forms when a security records a higher high and the MACD line forms a lower high. The higher high in the security is normal for an uptrend, but the lower high in the MACD shows less upside momentum. Even though upside momentum may be less, upside momentum is still outpacing downside momentum as long as the MACD is positive.尽管上行势头可能减弱,但只要 MACD 为正上行势头仍超过下行势头。 Waning upward momentum can sometimes foreshadow a trend reversal or sizable decline.  上升势头减弱有时预示着趋势逆转或大幅下跌we see Gamestop (GME) with a large bearish divergence from August to October.

  • The stock forged a higher high above $28, but the MACD line fell short of its prior high and formed a lower high.
    The subsequent signal line crossover and support break in the MACD were bearish.
  • On the price chart, notice how broken support turned into resistance on the throwback bounce in November (red dotted line). This throwback provided a second chance to sell or sell short.

移动平均线背离的主要问题之一是它通常可以发出可能的逆转信号但实际上并没有发生逆转——它会产生误报。 另一个问题是背离并不能预测所有的逆转。 换句话说,它预测了太多没有发生的反转,并且没有足够的实际价格反转。  

这表明应通过 趋势跟踪指标 寻求确认,例如方向运动指数 (DMI) 系统及其关键组成部分平均方向指数 (ADX)。 

General Rules for Trading Momentum Divergence交易动量背离的一般规则

  • 1. Enter a short position when the bearish divergence is identified, provided prices have not already reached the correction level or profit target.

         Bearish divergence is recognized after the second momentum peak has crested/ˈkrestɪd/到达洪峰,达到顶点; therefore, it is possible that the momentum value will be near neutral (the midpoint value) if the first momentum peak was not an extreme. The neutral momentum is the normal profit target because we cannot expect high momentum to alternate with low momentum, but we can expect high or low momentum to correct to neutral, or zero. Waiting until the divergence is extremely clear is often too late.中性动量是正常的利润目标,因为我们不能期望高动量与低动量交替出现,但我们可以期望高动量或低动量修正为中性或零等到背离非常明显时往往为时已晚Momentum will have achieved most of its correction. An alternative is discussed in the following section, “Anticipating the Divergence.”
     
  • 2. Enter a short position when the MACD line crosses below the signal line after the bearish divergence formation is recognized.

         MACD offers a clear signal: the crossing of the faster MACD line with the slower signal line. This is a basic buy or sell signal and applies equally to divergence patterns.
     
  • 3. Exit the short position when the current momentum moves above the last momentum peak.

         A new momentum high after a divergence signal indicates that the divergence has disappeared and there is no basis for this trade. The exact price at which this occurs may be calculated one day in advance for most momentum indicators.对于大多数动量指标,可以提前一天计算出发生这种情况的确切价格
     
  • 4. Exit the short position when the market has corrected or an objective has been reached.

        
    Once the momentum has declined to the midpoint level of 50 for the RSI and stochastic, or zero for the MACD or simple momentum, it should be considered neutral and cannot be expected to continue into negative values.

    A price objective can also be set using volatility or support levels.
     
  • 5. Exit the MACD short divergence when the MACD crosses the signal line moving higher.

         MACD provides a signal that may allow the divergence trade to be held longer, or exited quickly. In Figure 9.25 the MACD line gives a sell signal at the beginning of May and does not give another buy signal to close out the trade, until mid-June. This adds considerable profit to the trade.
     
  • 6. Allow the short divergence position to convert to a short trend position.

         If the MACD is not used, then a simple trend, such as a moving average, can be substituted. A short divergence signal can be converted to a short trend signal using, for example, one of the two trends used to create the MACD.

Anticipating the Divergence预测背离 

     Divergence signals are often seen too late. When the second momentum peak is recognized, especially when the divergence is severe, the momentum values are already near their neutral level, 50 or zero. Anticipating the divergence signal can be a more successful approach to trading.预测背离信号可能是一种更成功的交易方法

     Bearish divergence can be anticipated at the point where prices move above their previous resistance level. This is shown in Figure 9.25 with the line market horizontal resistance. Once prices move higher, there is always a potential divergence.

  • If the current value of momentum is lower than the value of momentum at the previous price peak, an anticipated divergence sell signal exists.

    The short sale is now entered as prices are rising as long as the current momentum value is below the last peak momentum value.

    For Amazon.com, that means holding a short position while prices continue higher.
     
  • The trade is exited if the momentum value continues higher and exceeds the previous peak momentum value, in which case there can be no divergence pattern.
     
  • This method offers the best opportunity for profiting from the entire downward reversal, but at higher risk.

A less risky alternative would be to divide trading capital into 3 parts, then

  • Sell the first third(first \frac{1}{3}) when prices make a new high and the MACD value is much lower.
  • Sell the second part(second \frac{1}{3}) when the MACD value moves to within 15–20% of the previous MACD high.
  • Sell the third part(third \frac{1}{3}) when the MACD value crosses the signal line heading down.

     If there is only one choice, it is better to take the second signal. If there are two choices, take the first and second. If you only take the third sell signal, when the MACD crossed the signal line, prices will have already dropped significantly, and you will be disappointed with your entry price and the lack of profi t opportunity. 如果只有一个选择,不如取第二个信号。 如果有两个选择,取第一个和第二个。 如果你只接受第三个卖出信号,当 MACD 穿过信号线时,价格已经大幅下跌,你会对你的入场价和缺乏获利机会感到失望

Single, Double, and Triple Divergences

     In fewer cases, double and triple bearish divergences will occur. A double bearish divergence is one in which 3 momentum peaks are declining with prices rising at each corresponding momentum peak. Most often, the second momentum peak is only slightly lower than the fi rst, and the last peak drops off noticeably, indicating that a drop in price is soon to follow大多数情况下,第二个动量峰值仅略低于第一个,而最后一个峰值明显下降,表明价格很快就会下跌. Multiple divergences are expected to be more reliable than single divergences, and represent a prolonged/ prəˈlɔːŋd /长期的, 持续很久的 period in which prices are rising at a slower and slower rate, in the manner of a rounded top

Rounded Tops

     When prices change direction over a longer time period they can create a rounded top or bottom pattern. A rounded top reflects a gradual change in market forces from buyers to sellers. In the stock market it is also called distribution. It is a clear sign that any attempt to move prices higher has been abandoned. Rounded tops often lead to faster and faster price drops as more investors liquidate their long positions or initiate shorts.FIGURE 3.29 Two rounded tops in the German DAX stock index.

     In Figure 3.29 we see two classic rounded tops in the German DAX stock index. The first is an example of gathering downside momentum as more investors become aware of the decline. Prices drop faster after a break of the double bottom. The rounded top offers a rare opportunity to accumulate a short position with relatively low volatility

Alternating Divergence Peaks交替背离波峰

     A common bearish pattern is where a lower momentum peak falls between two declining peaks. For example, the first momentum peak is at 90, the next at 60, and the last at 75. When studying the price and momentum charts, most analysts will ignore the lower peak in the middle and consider only the 90–75 divergence. In the following section, this combination can be automated by looking at the most recent momentum peak, i, and the previous two momentum peaks, i − 1 and i − 2, along with their corresponding prices可以通过查看最近的动量峰值 i 和前两个动量峰值 i − 1 和 i − 2 及其相应的价格来自动执行此组合.

Programming Divergence程序化背离

     Before explaining the technique used in the divergence program, it should be clear that there is no simple solution. There are many choices to be made in order to recognize a divergence pattern, and it will be difficult to find them all. What we can see on a chart is not always easy to program into a computer. A TradeStation program, TSM Divergence, is available on the Companion Website; it gives the user a number of choices for entries and exit, including multiple divergences, or simply a starting point for writing your own program. The inputs are

  • 1. Diverge : 1 = single divergence, 2 = double divergence
  • 2. Swing : the percentage price swing to find price extremes (normally 2% to 5%)
  • 3. Strength : the minimum percentage decline from the indicator high that will trigger a signal (normally 5%)
  • 4. Length : the calculation period for the stochastic (normally 5 to 10)
  • 5. Type : 0 for normal prices, 1 to change short rates into yields, and 2 to approximate the yield of a bond.
  • 6. Exit : the percent added or subtracted from 50 for the momentum exit (slow K) criterion (if exit = 10 then exit at 60, normally 0)
  • 7. FastX : exit level for fast stochastic X (fast K) (normally 20)

     The first decision is whether the pattern keys off the momentum indicator or the price pattern. This program uses the price peaks, which are identified using the swing technique explained in Chapter 5, with the Minimum Swing Value
(     
A price swing is a sustained price movement of a predetermined size. An upwards swing ends with a swing high, or peak, and a downward swing ends with a swing low, or valley. The distance from a peak to a valley is the swing. A swing can be small or large, depending on the sensitivity of the swing criterion. A swing is easily seen on a chart. You can choose to plot only the major price moves, or you can fill the chart with the smallest of price reversals. The only requirement is that each swing be greater than a threshold value, expressed in cents or dollars, or as a percentage of the current price of the stock or commodity. This minimum value, called the swing filter, determines the frequency of the swings and therefore the sensitivity of the chart.FIGURE 5.1 A bar chart of gold futures with p=5% swing points marked.

     Figure 5.1 shows a bar chart of gold futures with points above and below the bars representing the swing highs and lows based on a p=5% minimum move from highs to low.
FIGURE 5.2 Corresponding swing chart of gold using a p=5% swing filter.

 and the swing filter, expressed as a percentage p,
price_t :
 average close price over a period t( such as daily, monthly or yearly)

  • Fixed swing filter The average price of the stock will always be $18, we select a swing filter of 75¢, about p=4%.
    • Using a fixed value for finding the swing highs and lows will cause the swing chart to be insensitive to price movement at low prices and to show frequent changes in swings at higher prices.
  • Variable swing filter (relatively fixed swing filter during the period t and the average price price_t): 
         
    the swing filter, expressed as a percentage p
    • The swing filter, which determines the swing high and low points, can be more robust if it is expressed as a percentage of price rather than as a fixed dollar per share or point value. Many stocks have doubled in value—or halved—or both—over the past 10 years.

     This variable swing filter helps to keep the sensitivity of the swings the same over a long period t, which is very helpful for backtesting of results and for more consistent trading signals. The only complication is that the Minimum Swing Value may change daily, although gradually, and that requires you to be aware of the new value. It is always best to use the previous day’s value, MSV_{t-1}, rather than today’s value, in order to be sure that you are not cheating by looking ahead one day.
) given in the parameter swing p. For the momentum indicator, the stochastic is used instead of either a simple momentum or the MACD. Momentum values are then chosen corresponding to those price extremes. The momentum value at the second swing high must be less than the one at the first swing high by the amount specified by the strength parameter
(
3. Strength : the minimum percentage decline from the indicator high that will trigger a signal (normally 5%)
), typically 5 (for a bearish divergence).

  • There is no test to see if momentum dropped further between the two price peaks.
  • All other momentum values are ignored for the purpose of deciding on the entry signal.
  • If the momentum peaks are declining and the price peaks are rising, there is a bearish divergence.​​​​​​​
    • bear set-up occurs when the security forms a higher low更高的波谷, but the Stochastic Oscillator forms a lower low更低的波谷.
      尽管该股保持在先前的低点之上,但随机震荡指标的较低低点显示下行势头在增加. The next advance is expected to result in an important peak预计下一个上涨将导致一个重要的可交易的高峰.
      Notice that the Stochastic Oscillator
      • did not make it back above 80 and
      • turned down below its signal line in mid-December(actual signal takes place).​​​​​​​
    • bearish divergence : The stock moved to higher highs​更高的波峰, but the Stochastic Oscillator formed lower highs​更低的波峰
      •  A bearish divergence can be confirmed with
      • signal line(black line in the chart,  %K-slow) crosses and moves below 80\large \blacktriangledown​(might not provide good early signals if stock price peak kept moving higher)
      • a Stochastic Oscillator break below 50\large \blacktriangledown​, which is the centerline.(second signal)
        or a support break on the price chart(third signal)
  • If momentum peaks are rising and the price peaks are falling, there is a bullish divergence.
    • bull set-up is basically the inverse of a bullish divergence
      The underlying security forms a lower high 更 低的波峰, but the Stochastic Oscillator forms a higher high  更高的波峰.
      尽管该股未能超过其先前的高点,但随机震荡指标较高的高点显示上行势头增强 The next decline is then expected to result in a tradable bottom预计下一次下跌将导致可交易的低谷

      This higher high shows strength in upside momentum. Remember that this is a set-up, not a signal. The set-up foreshadows a tradable low in the near future.

      NTAP declined below its June low and the Stochastic Oscillator moved below 20 to become oversoldTraders could have acted
      • ​​​​​​​​​​​​​​when the Stochastic Oscillator moved
        • above its signal line(actual signal takes place),
        • above 20
        • or above 50,
        • or after NTAP broke resistance with a strong move. 
    • ​​​​​​​bullish divergence:
      stock moved to lower low 更低的波谷, but the Stochastic Oscillator formed a higher low 更高的波谷(This shows less downside momentum下行势头减弱 that could foreshadow a bullish reversal)
      ​ 
      • A bullish divergence can be confirmed with
        • signal line(black line in the chart,  %K-slow) cross and/or move back above 20\large \blacktriangle​编辑​编辑​编辑(might not provide good early signals if stock price trough kept moving lower)
          signal line cross occurs when %K-slow (black) crosses %D-slow(). This provides the earliest entry possible.
        • a Stochastic Oscillator break above 50\large \blacktriangle
          or a resistance break on the price chart.  
  • By not looking for the momentum peaks, it is possible that some of the patterns may not be timed correctly


     A bearish divergence exits

  • when the smoothed fast stochastic (%D or ) reaches 50.
    • ​​​​​​​ 



  • If the input parameter Exit 
    (
         6. Exit : the percent added or subtracted from 50 for the momentum exit (slow K) criterion (if exit = 10 then exit at 60, normally 0)
    )
    is set to +10 or –10 the trade exits when the momentum reaches 60 or 40, respectively.
  • Alternatively, if the momentum drops quickly, the parameter FastX will trigger an exit when the raw stochastic, Fast K, touches 20.

     In addition to the standard single divergence, the program recognizes a double divergence, the combination of 3 rising price peaks and 3 declining momentum peaks

     It is easier to find divergence by looking at a chart on a quote screen than to program it into a computer. Translating what you see into a systematic analysis of divergence signals is very difficult. You will find that this program does not always find the divergence that seems obvious to the eye. A divergence may be missed when there is a steady rise in prices that do not create swing highs, even though there is a corresponding steady decline in momentum. This situation is addressed using slope divergence

Slope Divergence

     One of the problems in using peak prices and peak momentum values is that some of the most obvious divergence situations are missed. Prices can move higher or lower steadilywithout large swings, while momentum moves the other way. This will happen during a very orderly rounded top or rounded bottom formation. Without peaks that can be identified using a swing analysis, this pattern is missed.

     An alternative technique is to analyze the slope of both the price movement and the momentum indicator over the same time interval. This can be done using a spreadsheet function, slope, or the program function LinearRegSlope, over a specified time interval. Because momentum is a way of detrending the price series, the period used for the calculation should not be too long; otherwise the slope values of the momentum will tend towards zero.

     A more interesting but complicated method is to record the point of the last momentum peak, m. As we move forward in time to day t, find the slope of the momentum from m to t and the corresponding slope in the price over the same period.

  • If the slope of the momentum is negative(for example: two peak momentum values) and the slope of the prices is positive(for example: two peak prices), then there is a bearish divergence.
  • As t gets larger, we have more confidence in the bearish divergence.
  • If the slope of the prices on day t is less than the slope on day t−1(price rises slower), but still positive, we have a sell signal.

     Divergence can be any combination of conflicting directions between the slope of price and the slope of momentum, including prices rising faster than momentum, momentum rising faster than prices, or the opposite. However, classic analysis has focused on momentum as a leading indicator of a change in the price direction, which limits the combinations to:

  • Prices rising and momentum falling (a bearish divergence).
  • Prices fallingand momentum rising (a bullish divergence).

     The strength of a bearish divergence, which is helpful when selecting which situations are best for trading, can be determined primarily by the momentum slope, but can also be assessed as the net difference between the rising slope of prices and the falling slope of momentum. When comparing the two slopes, care must be taken because the angle of price movement can be far greater than the angle of momentum movement

Slope Divergence Using Double Smoothing

     Double smoothing, discussed earlier in this chapter, is a tool that represents the trend of momentum but may not show many momentum peaks; therefore, it becomes an alternate method for slope divergence. In Figure 9.26 there is a long upwards move in the NASDAQ 100 throughout 1999. The price swings are relatively small and may not be picked up using a swing value that worked during prior years长期的缓慢的上行趋势, 价格波动相对较小, 使用前几年有效的波动值可能无法捕捉到. At the same time there is a steady decline in momentum, represented by a double smoothing of 20-20-20 (a 20-day momentum
, smoothed twice using 20-day exponentials
###

TSI, we used 1-day momentum, first smoothing period r=25, then second smoothing period s=13

###
). Lines are drawn through both prices and momentum to show the slope of the corresponding movement.​​​​​​​FIGURE 9.26 Slope divergence of NASDAQ 100 using double smoothing.


     One way to produce a trading signal for the two slope calculations is to monitor their relative movement. While they remain constant or are moving apart(缓慢diverge, see FIGURE 9.26), no action is taken.

  • Once the slope values begin to converge beyond a threshold value representing normal variance, a short sale signal is produced. After that, normal price targets apply.(价格趋势反转下降,收敛度超过阀值,目标价卖出)
    • If the price slope continues to decline, the trade should be held.
  • If the momentum slope rises above its value at the time of the short sale signal, the trade should be exited(想象一下, 如果原先动量2个波峰连线是下降的,现在第1个与第3个波峰连线的斜率突然上升,预测趋势上涨),
  • or if the two slopes begin to diverge significantly, the trade should also be exited(价格趋势即将反转下降,).

SOME FINAL COMMENTS ON MOMENTUM

     Because momentum and oscillators are very different from either a charting technique or moving averages, they have become important in technical analysis. However, when the time interval for calculation is small, these indicators can be highly unstable, jumping from frequent overbought signals to just as frequent oversold ones. All momentum indicators, when used to enter contrary to the direction of price movement, exhibit high risk.

     Momentum indicators are most often used as a timing tool within another more conservative strategy, such as trend following. The calculation period is then tuned to allow the momentum values to reach extremes with a certain frequency. Momentum values that are not extremes give us very little useful information. Consider a trending strategy where each trade is held for an average of 20 days. A fast oscillator can be created to provide entry timing. If you are willing to wait up to two days to enter a trade after the trend signal has been given, then construct a 10-period oscillator of 1-hour bars, or a 3-period oscillator of daily bars. Test the oscillator to see if it generates at least one, but preferably two, oversold signals during each 2-day period. If so, use it to time your entry and you are likely to be buying dips rather than rallies. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LIQING LIN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值