App-Chart

 view release on metacpan or  search on metacpan

doc/chart.texi  view on Meta::CPAN

* Triangular Moving Average::
* Variable Index Dynamic Average::
* Volume Weighted Moving Average::
* Zero-Lag Exponential Moving Average::
@end menu


@c ---------------------------------------------------------------------------
@node Simple Moving Average, Exponential Moving Average, Averages, Averages
@section Simple Moving Average
@cindex Simple moving average
@cindex SMA
@cindex Average, simple
@cindex Moving average, simple

An N-day simple moving average is the unweighted average (mean) of the past N
days.  So if @ms{p,1} is today's closing price, @ms{p,2} yesterday's, etc,
then the SMA for today is

@tex
$$ SMA = { { p_1 + p_2 + \dots + p_N } \over N } $$
@end tex
@ifnottex
@example
      p1 + p2 + ... + pN
SMA = ------------------
              N
@end example
@end ifnottex

Because old prices have the same weighting in the average as recent prices,
the SMA can be rising merely because old lower prices are dropping out of the
window.  The weighting of past days also makes it seem to lag behind recent
action.  The EMA (@pxref{Exponential Moving Average}) and WMA (@pxref{Weighted
Moving Average}) approaches address that sort of lag.

See also @ref{Momentum and Rate of Change}, which show the slope of the SMA.


@c ---------------------------------------------------------------------------
@node Exponential Moving Average, Weighted Moving Average, Simple Moving Average, Averages
@section Exponential Moving Average
@cindex Exponential moving average
@cindex EMA
@cindex Average, exponential
@cindex Moving average, exponential

An N-day exponential moving average (EMA) is a weighted average of today's
close and the preceding EMA value.  The weight for today's close is a
smoothing factor alpha, where @m{\alpha={2\over{N+1}},alpha=2/(N+1)}.

@tex
$$ EMA_{today} = \alpha \times close + (1-\alpha) \times EMA_{yesterday} $$
@end tex
@ifnottex
@example
EMA[today] = alpha * close + (1-alpha) * EMA[yesterday]
@end example
@end ifnottex

The formula can also be written as follows, showing how the average moves
towards today's close by an @alph{} fraction of the distance from the old EMA
to the new close.

@tex
$$ EMA_{today} = EMA_{yesterday} + \alpha \times (close - EMA_{yesterday}) $$
@end tex
@ifnottex
@example
EMA[today] = EMA[yesterday] + alpha * (close + EMA[yesterday])
@end example
@end ifnottex

Expanding out gives a power series with successively decreasing weight for
each day's price.  Writing @math{f=1-@alph{}} and with @ms{p,1} today's
closing price, @ms{p,2} yesterday's, etc, then

@tex
$$ EMA = { { p_1 + p_2f + p_3f^2 + p_4f^3 \dots }
           \over { 1 + f + f^2 + f^3 \dots } }
$$
@end tex
@ifnottex
@example
      p1 + p2*f + p3*(f^2) + p4*(f^3) + ...
EMA = -------------------------------------
       1 +   f  +    f^2   +    f^3   + ...
@end example
@end ifnottex

This is an infinite sum, but @math{f} is less than 1 so each successive weight
@math{f^k} is smaller and smaller, soon becoming negligible.  The most recent
@math{N} days make up about 86.5% of the total.  The following graph shows how
the weights decrease for @math{N=10}.

@myimage{chart-ema-weights, EMA weights graph}

Because recent prices have a higher weighting that past prices, the EMA
responds more quickly and tracks recent prices more closely than a simple
moving average (@pxref{Simple Moving Average}).

@cindex EMA period by Wilder
@cindex Wilder EMA period
@cindex Wilder, J. Welles
@anchor{Wilder EMA period}
@subsection J.@: Welles Wilder

When working with N-day periods, it should be noted that J.@: Welles Wilder
uses a different reckoning of the decrease factor for EMAs.  For example for a
14-day EMA he writes

@tex
$$ EMA_{today} =   {  1 \over 14 } \times close
                 + { 13 \over 14 } \times EMA_{yesterday} $$
@end tex
@ifnottex
@example
              1           13
EMA[today] = -- * close + -- * EMA[yesterday]
             14           14
@end example
@end ifnottex

@c  The equivalence is from the coefficient of the first term
@c
@c      (1-f) = 1/W
@c
@c  or the same on the EMA[yesterday] term
@c
@c      f = 1-1/W
@c
@c  so
@c      1-2/(N+1) = 1-1/W
@c      2/(N+1) = 1/W
@c      W = (N+1)/2      or N = 2W-1
@c
This is the same as the formula above, just a different @math{f} factor.  When
Wilder gives ``W'' days, the equivalent ``N'' above is @m{2W-1,2*W-1}, so say
14 becomes 27.  This is also sometimes called a ``modified moving average''.

In the indicators designed by Wilder, Chart uses his reckoning, so that for
instance a 14-day RSI is entered at 14.  This applies to ATR, DMI (and ADX)
and RSI (@pxref{Average True Range}, @ref{Directional Movement Index}, and
@ref{Relative Strength Index}).


@c ---------------------------------------------------------------------------
@node Weighted Moving Average, Double and Triple Exponential Moving Average, Exponential Moving Average, Averages
@section Weighted Moving Average
@cindex Weighted moving average
@cindex WMA
@cindex Average, weighted
@cindex Moving average, weighted

An N-day weighted moving average is an average of today's close and preceding
closes, with weighting factor N for today, @math{N-1} for yesterday,
@math{N-2} for the day before, etc.  The influence of past data thereby
decreases with its age, down to nothing beyond N days.

The formula is as follows, with @ms{p,1} for today's closing price, @ms{p,2}
yesterday's, etc.

@tex
$$ WMA = { { N p_1 + (N-1) p_2 + (N-2) p_3 + \cdots + 2 p_{N-1} + p_N }
           \over { N + (N-1) + (N-2) + \cdots + 2 + 1 } }
$$
@end tex
@ifnottex
@example
      N * p1 + (N-1) * p2 + (N-2) * p3 + ... + 2 * p[N-1] + pN
WMA = --------------------------------------------------------
        N    +    N-1     +     N-2    + ... +    2       + 1
@end example
@end ifnottex

Like the EMA (@pxref{Exponential Moving Average}), the WMA gives a higher
weighting to recent prices than past prices, so it tracks those recent prices
more closely than a simple moving average (@pxref{Simple Moving Average}).
The following graph shows how the weights decrease for @math{N=15}.

@myimage{chart-wma-weights, WMA weights graph}


@c ---------------------------------------------------------------------------
@node Double and Triple Exponential Moving Average, Endpoint Moving Average, Weighted Moving Average, Averages
@section Double and Triple Exponential Moving Average
@cindex Double exponential moving average
@cindex Average, double exponential
@cindex Moving average, double exponential
@cindex DEMA
@cindex Triple exponential moving average
@cindex Average, triple exponential
@cindex Moving average, triple exponential
@cindex TEMA

The double exponential moving average (DEMA) and triple exponential moving
average (TEMA) are combination EMAs (@pxref{Exponential Moving Average}) by
Patrick Mulloy, designed to track recent prices even more closely than the
plain EMA@.  The calculation for DEMA is

@tex
$$ DEMA = 2 \times EMA[N] - EMAofEMA[N] $$
@end tex
@ifnottex
@example
DEMA = 2*EMA[N] - EMAofEMA[N]
@end example
@end ifnottex

and for TEMA,

@tex
$$ TEMA = 3 \times EMA[N] - 3 \times EMAofEMA[N] + EMAofEMAofEMA[N] $$
@end tex
@ifnottex
@example
TEMA = 3*EMA[N] - 3*EMAofEMA[N] + EMAofEMAofEMA[N]
@end example
@end ifnottex

Both are ``overweight'' on recent points so the moving average can actually
get ahead of recent prices in some unusual price patterns.  The following
graph shows the DEMA weights for @math{N=15}.

@myimage{chart-dema-weights, DEMA weights graph}

And the following is TEMA for the same @math{N=15}.

@myimage{chart-tema-weights, TEMA weights graph}


@c ---------------------------------------------------------------------------
@node Endpoint Moving Average, Fractal Adaptive Moving Average, Double and Triple Exponential Moving Average, Averages
@section Endpoint Moving Average
@cindex Endpoint moving average
@cindex EPMA
@cindex Least squares moving average
@cindex LSQMA
@cindex Average, endpoint
@cindex Average, least squares
@cindex Moving average, endpoint
@cindex Moving average, least squares
@cindex Time series forecast
@cindex TSF
@cindex Sharp, Joe
@cindex Average, modified
@cindex Moving average, modified
@cindex Modified moving average

The endpoint moving average (EPMA) establishes an average price by fitting a
least squares straight line (@pxref{Linear Regression}) through the past N
days closing prices and taking the endpoint of the line (ie.@: the line as at
the last day) as the average.

This calculation goes by a number of other names, including least squares
moving average (LSQMA), moving linear regression, and time series forecast
(TSF).  Joe Sharp's ``modified moving average'' is the same thing too.

The formula ends up being a straightforward weighted average of past N prices,
with weights going from @m{2N-1,2*N-1} down to @math{-N+2}.  This is easily
derived from the least squares formulas, but just looking at the weightings
the connection to least squares is not at all obvious.  If @ms{p,1} is today's
close, @ms{p,2} yesterdays, etc, then

@tex
$$ EPMA = { (2N-1) \times p_1 + (2N-4) \times p_1 + \cdots (-N+2) \times p_N
            \over (2N-1) + (2N-4) + \cdots + (-N+2) } $$
@end tex
@ifnottex
@example
       (2*N-1)*p[1] + (2*N-4)*p[2] + ... + (-N+2)*p[N]
EPMA = -----------------------------------------------
        2*N-1       +  2*N-4       + ... +  -N+2
@end example
@end ifnottex

The weights decrease by 3 for each older day, and go negative for the oldest
third of the N days.  The following graph shows that for @math{N=15}.

@myimage{chart-epma-weights, Endpoint MA weights graph}

The negatives mean the average is ``overweight'' on recent prices and can
overshoot price action after a sudden jump.  In general however because the
fitted line deliberately goes through the middle of recent prices the EPMA
tends to be in the middle of recent prices, or a projection of where they
seemed to be trending.

It's interesting to compare the EPMA with a plain SMA (@pxref{Simple Moving
Average}).  An SMA effectively draws a horizontal line through the past N days
prices (their mean), whereas the EPMA draws a sloping line.

The inertia indicator (@pxref{Inertia}) uses the EPMA.

@c @subsection Additional Resources
@c @itemize
@c @item
@c @uref{...} -- ...
@c @end itemize.


@c ---------------------------------------------------------------------------
@node Fractal Adaptive Moving Average, Guppy Multiple Moving Average, Endpoint Moving Average, Averages
@section Fractal Adaptive Moving Average
@cindex Fractal adaptive moving average
@cindex FRAMA
@cindex Average, fractal adaptive
@cindex Moving average, fractal adaptive

@uref{http://www.mesasoftware.com/technicalpapers.htm} @*
@uref{http://www.mesasoftware.com/Papers/FRAMA.pdf}

@cindex Ehlers, John
The fractal adaptive moving average (FRAMA) by John Ehlers is an exponential
style moving average (@pxref{Exponential Moving Average}) with an alpha
smoothing factor that varies according to a fractal dimension calculated over
the past N day's prices.

The dimension is calculated by looking at the N days in two halves, the
immediately preceding N/2 days and the N/2 preceding that.  The trading ranges
in those halves are compared to the total range and an alpha factor for the
EMA generated.  The calculation is slightly tricky but in essence the amount
of overlap between the ranges is measured.  The alpha factor is small and the
EMA slow when the halves overlap.  The alpha is large and the EMA fast when
the halves don't overlap but add up to make the overall N day range.

The FRAMA alpha factor and the fractal dimension value are available in the
lower indicator window, to see where they're big or small, under ``Low
Priority'' near the end of the indicators lists.

@subsection Additional Resources
@itemize
@item
@uref{http://www.traders.com/Documentation/FEEDbk_docs/Archive/102005/TradersTips/TradersTips.html}
-- TASC Oct 2005 Traders' Tips various formulas [possibly gone].
@end itemize


@c ---------------------------------------------------------------------------
@node Guppy Multiple Moving Average, Hull Moving Average, Fractal Adaptive Moving Average, Averages
@section Guppy Multiple Moving Average
@cindex Guppy multiple moving average
@cindex GMMA
@cindex Average, Guppy multiple
@cindex Moving average, Guppy multiple

@uref{http://www.guppytraders.com/gup329.shtml} (summary at Darryl Guppy's web
site)
@c
@c This one gone, apparently
@c @*
@c @uref{http://www.chartfilter.com/articles/technicalanalysis/movingaverage.htm}
@c (2004 article by Darryl Guppy)

@cindex Darryl Guppy
The Guppy multiple moving average (GMMA) by Darryl Guppy is a set of six short
term and six long term exponential moving averages (@pxref{Exponential Moving
Average}), all drawn on the one chart.

His standard periods are 3, 5, 8, 10, 12 and 15 days for the short averages,
and 30, 35, 40, 45, 50 and 60 days for the long averages.  These periods are
parameters in Chart to allow experimentation.  A value of 0 suppresses an
entry if less than twelve lines are desired.

Guppy's approach is look for compression of the averages (the lines coming
together) in each group as signalling a likely trend change; and for steady
parallel or expanding lines as a continuing trend.  He emphasises that the
idea is not a moving average crossover system.

@subsection Additional Resources

@itemize
@item
@uref{http://www.incrediblecharts.com/technical/multiple_moving_averages.htm}
-- sample graph of @samp{ASX.AX} from 1999.
@end itemize


@c ---------------------------------------------------------------------------
@node Hull Moving Average, Kaufman Adaptive Moving Average, Guppy Multiple Moving Average, Averages
@section Hull Moving Average
@cindex Hull moving average
@cindex HMA

@uref{http://www.alanhull.com/} @*
@uref{http://www.justdata.com.au/Journals/AlanHull/hull_ma.htm}

The Hull moving average (HMA) by Alan Hull is a combination of weighted moving
averages (@pxref{Weighted Moving Average}) with a momentum component, designed
to have low lag.

@tex
$$ HMA = WMA \left\lfloor \sqrt{N} \right\rfloor \; of \;
           ( 2 \times WMA 
\left\lfloor { N \over 2 } \right\rfloor

doc/chart.texi  view on Meta::CPAN

variable @alph{} factor which is based on how well the filter is tracking a
past N days prices.  The effect is to follow sustained moves quite closely,
but to change little when prices chop back and forwards in a range.

The raw alpha values can be viewed as ``Adaptive Laguerre Alpha'' in the lower
indicator window, under ``Low Priority'' near the end of the indicator lists.
High values mean closely tracking prices, low values mean only slow response.


@c ---------------------------------------------------------------------------
@node Median-Average Adaptive Filter, Moving Median, Laguerre Filter, Averages
@section Median-Average Adaptive Filter
@cindex Median-average adaptive filter
@cindex Filter, Median-average

@uref{http://www.mesasoftware.com/technicalpapers.htm} @*
@uref{http://web.archive.org/web/20070720222047/http://www.mesasoftware.com/Papers/What%27s+the+Difference.exe}
(self-extracting zip file)

@cindex Ehlers, John
The median-average adaptive filter by John Elhers is an EMA (@pxref{Exponential
Moving Average}) with an alpha smoothing factor that varies according to how
close it is to a median.

The raw alpha values can be viewed as ``Median-Average Alpha'' in the lower
indicator window, under ``Low Priority'' in the indicator lists.  High values
are where the average is following recent prices closely.  The maximum is 0.5,
which corresponds to a 3-day EMA.


@c ---------------------------------------------------------------------------
@node Moving Median, Regularized Exponential Moving Average, Median-Average Adaptive Filter, Averages
@section Moving Median
@cindex Moving median
@cindex Median, moving

The moving median is simply the median of the past N days' closing prices.
This may be of limited interest and is thus under ``Low Priority'' in the
indicator lists.

For reference, a median is calculated by considering the prices sorted from
highest to lowest.  The middle one is the median, or if there's an even number
then the mean of the middle two.  So for example with 15 points the chosen
median point will have 7 others above it and 7 below it.  The effect when
plotted is a line that stays roughly in the middle of the past N days price
action.


@c ---------------------------------------------------------------------------
@node Regularized Exponential Moving Average, Sine Weighted Moving Average, Moving Median, Averages
@section Regularized Exponential Moving Average
@cindex Regularized exponential moving average
@cindex REMA
@cindex Average, regularized exponential
@cindex Moving average, regularized exponential
@cindex Exponential moving average, regularized

@cindex Satchwell, Chris
The regularized exponential moving average (REMA) by Chris Satchwell is a
variation on the EMA (@pxref{Exponential Moving Average}) designed to be
smoother but not introduce too much extra lag.  The formula can be given in a
number of forms, such as

@tex
$$ REMA = { Rp
            + \alpha \times (close - Rp)
            + \lambda \times (Rp + (Rp-Rpp))
          \over 1 + \lambda } $$
@end tex
@ifnottex
@example
       Rp + alpha*(close - Rp) + lambda*(Rp + (Rp-Rpp))
REMA = ---------------------------------------------
                 1             +      lambda
@end example
@end ifnottex
alpha = N-day smoothing per EMA @*
Rp = yesterday's REMA @*
Rpp = day before yesterday's REMA @*
@m{\lambda,Lambda} is a factor controlling the amount of ``regularization''.

This form shows how there's an @m{Rp + \alpha \times (close -
Rp),Rp+alpha*(close-Rp)} part like an EMA, and an @math{Rp+(Rp-Rpp)} part
which projects from yesterday's REMA according to whether it was rising or
falling relative to the REMA of the day before.  The two parts are averaged
with a weighting 1 for the EMA part and @m{\lambda,lambda} for the projection.

If @m{\lambda,lambda} is zero then REMA is the same as a plain EMA@.
Satchwell suggests fairly small values for @m{\lambda,lambda}, and the default
in Chart is 0.5.  John Ehlers noted that if @m{\lambda,lambda} is large REMA
becomes unstable.

In any case the result of the calculation is still an average of past prices
with a certain set of weights that progressively decrease for older data.  The
following is the weights for @math{N=15} and @m{\lambda=0.5,lambda=0.5},

@myimage{chart-rema-weights, Regularized EMA weights graph}

@subsection REMA Momentum
@anchor{REMA Momentum}
@cindex REMA Momentum
@cindex Regularized Momentum

A momentum indicator is formed from REMA as the slope of the line from
yesterday's REMA to today's.

@tex
$$ RegMom = { REMA - REMA_{prev} \over REMA_{prev} } $$
@end tex
@ifnottex
@example
         REMA - REMAprev
RegMom = ---------------
             REMAprev
@end example
@end ifnottex

This is like a Rate of Change (@pxref{Momentum and Rate of Change}), but on
just one day and as a fraction instead of a percentage.  A crossing through
zero of the RegMom is a peak or trough (and possibly just a flat spot before a
further rise or fall in the REMA line).

@subsection Additional Resources
@itemize
@item
@uref{http://www.traders.com/Documentation/FEEDbk_docs/Archive/072003/TradersTips/TradersTips.html}
-- TASC Traders' Tips, August 2003, REMA and REMA momentum formulas.
@end itemize


@c ---------------------------------------------------------------------------
@node Sine Weighted Moving Average, T3 Moving Average, Regularized Exponential Moving Average, Averages
@section Sine Weighted Moving Average
@cindex Sine weighted moving average
@cindex Sine-MA
@cindex Average, sine weighted
@cindex Moving average, sine weighted

A sine weighted moving average (Sine-MA) applies weights to each day in the
shape of the bulge in a sine curve from 0 to @m{\pi,pi}.  For an N-day average
the weightings are

@tex
$$ \sin {1 \over N+1} \pi, \;\;
   \sin {1 \over N+1} \pi, \;\; \dots, \;\;
   \sin {N \over N+1} \pi
$$
@end tex
@ifnottex
@example
     /  1      \         /  2      \             /  N      \
sin |  --- * pi |,  sin |  --- * pi |, ..., sin |  --- * pi |
     \ N+1     /         \ N+1     /             \ N+1     /
@end example
@end ifnottex

The effect is that middle prices have the greatest weight (much like the TMA,
@ref{Triangular Moving Average}).  The graph below shows the weights for
@math{N=10}.  In Chart SWMA is under ``Low Priority'' in the indicator lists.

@myimage{chart-sine-weights, Sine weights graph}


@c ---------------------------------------------------------------------------
@node T3 Moving Average, Triangular Moving Average, Sine Weighted Moving Average, Averages
@section T3 Moving Average
@cindex T3 moving average

The T3 moving average by Tim Tillson is a triple smoothed combination of the
DEMA (@pxref{Double and Triple Exponential Moving Average}) and a plain EMA
(@pxref{Exponential Moving Average}).

A given ``volume factor'' V (default 0.7) controls how much of the DEMA is
used.  The factor ranges from 0 which gives a plain EMA, up to 1 which gives a
full DEMA@.  Values in between are a combination.  The formula for this
``generalized DEMA'' is

@tex
$$ GD(N,v) = (1-v) \times EMA[N] + v \times DEMA[N] $$
@end tex
@ifnottex
@example
GD(N,v) = (1-v)*EMA[N] + v*DEMA[N]
@end example
@end ifnottex

@noindent
or equivalently as follows, emphasising how a portion of the momentum term
present in the DEMA is used,

@tex
$$ GD(N,v) = EMA[N] + v \times (EMA[N] - EMAofEMA[N]) $$
@end tex
@ifnottex
@example
GD(N,v) = EMA[N] + v * (EMA[N] - EMAofEMA[N])
@end example
@end ifnottex

T3 applies this three times,

@tex
$$ T3(N,v) = GD(N,v) \; of \; GD(N,v) \; of \; GD(N,v) $$
@end tex
@ifnottex
@example
T3(N,v) = GD(N,v) of GD(N,v) of GD(N,v)
@end example
@end ifnottex

The following graph shows the weightings that result from @math{N=10} and
@math{v=0.7}.

@myimage{chart-t3-weights, T3 weights graph}

At the lower @math{v=0} extreme T3 is simply a tripled EMA (@pxref{EMA of EMA
of EMA}).  At the upper @math{v=1} extreme T3 is a DEMA of DEMA of DEMA, and
the following is the weights for that (again @math{N=10}),

@myimage{chart-dema-3-weights, DEMA of DEMA of DEMA weights graph}


@c ---------------------------------------------------------------------------
@node Triangular Moving Average, Variable Index Dynamic Average, T3 Moving Average, Averages
@section Triangular Moving Average
@cindex Triangular moving average
@cindex TMA
@cindex Average, triangular
@cindex Moving average, triangular

A triangular moving average (TMA) applies weights to each day in a triangular
shape.  For example on a 7-day average the weights are 1, 2, 3, 4, 3, 2, 1, or
the following graph shows a 15-day average.  The middle prices in the period
have the greatest weight, and the oldest or newest only a small weight.

doc/chart.texi  view on Meta::CPAN

@ifnottex
@example
VIDYA = alpha * close + (1-alpha) * VIDYA[prev]
@end example
@end ifnottex

The alpha values can be viewed directly with ``VIDYA alpha'' in the lower
indicator window, under ``Low Priority'' in the indicator lists.  High values
show where the VIDYA is tracking recent prices closely, low values show where
it's responding only slowly.


@c ---------------------------------------------------------------------------
@node Volume Weighted Moving Average, Zero-Lag Exponential Moving Average, Variable Index Dynamic Average, Averages
@section Volume Weighted Moving Average
@cindex Volume weighted moving average
@cindex VWMA
@cindex Average, volume weighted
@cindex Moving average, volume weighted

An N-day volume weighted moving average (VWMA) is the average of the past N
days closing prices, each weighted in proportion to the volume on that day.
So if @ms{p,1} is today's closing price, @ms{p,2} yesterday's, etc, and
@ms{v,1}, @ms{v,2}, etc similarly the volumes, then the VWMA for today is

@tex
$$ VWMA = { v_1 \times p_1 + v_2 \times p_2 + \cdots + v_N \times p_N-1
            \over v_1 + v_2 + \cdots + v_N } $$
@end tex
@ifnottex
@example
       v1 * p1 + v2 * p2 + ... + vN * pN
VWMA = ---------------------------------
          v1   +    v2   + ... +    vN
@end example
@end ifnottex

The effect is to give greater significance to days with greater volume, making
the average tend towards those days' closing prices more.  If all volumes are
about the same then the VWMA becomes a simple moving average (@pxref{Simple
Moving Average}).

A true VWMA, the kind frequently specified for dividend reinvestment plans and
other things needing an average price around a particular period, takes every
price level and the volume transacted at that level.  Chart doesn't have the
data needed for that and the calculation above instead effectively attributes
all volume to the closing price.


@c ---------------------------------------------------------------------------
@node Zero-Lag Exponential Moving Average,  , Volume Weighted Moving Average, Averages
@section Zero-Lag Exponential Moving Average
@cindex zero-lag exponential moving average
@cindex Average, zero-lag exponential
@cindex Moving average, zero-lag exponential
@cindex ZLEMA

The zero-lag exponential moving average (ZLEMA) is a variation of the EMA
(@pxref{Exponential Moving Average}) which adds a momentum term aiming to
reduce lag in the average so as to track current prices more closely.  For a
given N-day period the formula is

@tex
$$ ZLEMA = EMA \; of \; (close + (close-close[lag])) $$
@end tex
@ifnottex
@example
ZLEMA = EMA of (close + (close-close[lag]))
@end example
@end ifnottex

Where the ``lag'' period is @math{(N-1)/2}.  A plain EMA applied to straight
line points ends up always being the close at @math{(N-1)/2} days ago.  So the
idea of adding in this difference ``close - close[lag]'' is to compensate for
that lag, to make the ZLEMA track a straight line exactly.  Of course real
data is rarely a straight line, but the principle is to push the ZLEMA towards
approximately the current close.

The calculation still ends up as various weights on each past price.  The
effect of the momentum term is to make recent prices ``over weight'' and thus
tracked closely, and with negative weights on past terms.  There's a sudden
jump in the weights at the momentum lag point.  For example the following
graph is the weights for @math{N=15} (lag point 7).

@myimage{chart-zlema-weights, Zero-lag EMA weights graph}

The EMA lag on a straight line can be calculated easily using the power
formula for the EMA (@pxref{Exponential Moving Average}), applied to an
infinite sequence of prices going downwards by 1 each day and reaching 0 at
today.  On non straight line sequences the lag is not a simple @math{(N-1)/2},
but will vary according to shape, period of cyclical components, etc.


@c ---------------------------------------------------------------------------
@node Channels and Boxes, Indicators, Averages, Top
@chapter Channels and Boxes
@cindex Channels
@cindex Boxes

@menu
* Bollinger Bands::
* Darvas Boxes::
* Donchian Channel::
* Ichimoku Kinko Hyo::
* Keltner Channel::
* Kirshenbaum Bands::
* Parabolic SAR::
@end menu


@c ---------------------------------------------------------------------------
@node Bollinger Bands, Darvas Boxes, Channels and Boxes, Channels and Boxes
@section Bollinger Bands
@cindex Bollinger bands
@cindex Average
@cindex Moving average
@cindex Variance
@cindex Deviation
@cindex Standard deviation

@uref{http://www.bollingerbands.com}

@cindex Bollinger, John
Bollinger bands by John Bollinger are an N-day simple moving average
(@pxref{Simple Moving Average}) with an upper and lower bands drawn at 1
standard deviation away from the average.  The distance multiple is
configurable.

Standard deviation (@pxref{Standard Deviation}) is a statistical measure of
how much the values in a data set (the N closing prices in this case) deviate
from their average (the mean).  When prices are not changing much the
deviation is small and the band lines are close to the average.  The bands are
further away when closing prices are more volatile.

See also @ref{Kirshenbaum Bands}, which are similar but with a channel width
based on standard error from a linear regression.


@c ---------------------------------------------------------------------------
@node Darvas Boxes, Donchian Channel, Bollinger Bands, Channels and Boxes
@section Darvas Boxes
@cindex Darvas boxes
@cindex Boxes, Darvas

@cindex Darvas, Nicholas
Darvas boxes by Nicholas Darvas are a system of drawing boxes on certain
trading ranges, with a view to trading breakouts up or down from them.

doc/chart.texi  view on Meta::CPAN

* Aroon::
* Average True Range::
* Centre of Gravity Oscillator::
* Chaikin Money Flow::
* Chaikin Oscillator::
* Chande Momentum Oscillator::
* Commodity Channel Index::
* Coppock Curve::
* Detrended Price Oscillator::
* Directional Movement Index::
* Ease of Movement::
* Elder Bull/Bear Power::
* Fisher Transform::
* Force Index::
* Forecast Oscillator::
* Gopalakrishnan Range Index::
* Intraday Momentum Index::
* Klinger Volume Oscillator::
* MACD::
* MASS Index::
* Momentum and Rate of Change::
* Money Flow Index::
* On-Balance Volume::
* Negative Volume Index::
* Polarized Fractal Efficiency::
* Pretty Good Oscillator::
* Price and Volume Trend::
* QStick::
* R-Squared Index::
* RAVI::
* Relative Strength Index::
* Relative Volatility Index::
* Random Walk Index::
* Stochastics::
* TD Range Expansion Index::
* Trend Intensity Index::
* Trendscore::
* True Strength Index::
* TRIX::
* Twiggs Money Flow::
* Ulcer Index::
* Ultimate Oscillator::
* Vertical Horizontal Filter::
* Volatility Ratio::
* Williams %R::
* Williams Accumulation/Distribution::
* Zig Zag Indicator::
@end menu


@c ---------------------------------------------------------------------------
@node Accumulation/Distribution, Accumulative Swing Index, Indicators, Indicators
@section Accumulation/Distribution
@cindex Accumulation/distribution
@cindex Index, accumulation/distribution

@cindex Chaikin, Marc
The Accumulation/Distribution index by Marc Chaikin is a cumulative total
volume, with volume each day added or subtracted in proportion to where the
close is between that day's high and low.  For @var{c}, @var{h}, @var{l},
@var{v} and with @ms{AD,prev} as yesterday's Acc/Dist the formula is

@tex
$$ AD = AD_{prev} + v \> \left( 2 \, {{c-l} \over {h-l}} - 1 \right) $$
@end tex
@ifnottex
@example
                       C - L
AD = ADprev + V * (2 * ----- - 1)
                       H - L
@end example
@end ifnottex

When the close is at the high the factor is @math{+1} and the full volume is
added in, when the close is at the low the factor is @math{-1} and the full
volume is subtracted.  In between is in proportion, so for instance a close at
75% of the range would be a factor @math{+0.5}, or a close midway would be a
factor 0 for no change to the Acc/Dist.

The starting point (ie.@: the zero point) for the running total is arbitrary.
In Chart it's merely the segment of data first displayed.

The name accumulation/distribution comes from the idea that during
accumulation buyers are in control and the price will be bid up through the
day, or will make a recovery after being sold down, in any case finishing near
the high.  Vice versa for distribution.

Acc/Dist is somewhat similar to On-Balance Volume (@pxref{On-Balance Volume}).
But Acc/Dist looks at close within that day's range, whereas OBV looks just at
close-to-close up or down.  An Acc/Dist calculation within an N-day window can
be made too, see @ref{Chaikin Money Flow}.


@c ---------------------------------------------------------------------------
@node Accumulative Swing Index, Aroon, Accumulation/Distribution, Indicators
@section Accumulative Swing Index
@cindex Accumulative swing index
@cindex ASI
@cindex Index, accumulative swing

@cindex Wilder, J. Welles
The accumulative swing index (ASI) by J.@: Welles Wilder forms a cumulative
total of certain swing index values which are a tricky weighted combination of
close-to-close, open-to-close, and high-to-low range amounts each day.

The close-to-close dominates the swing index, so the ASI broadly follows the
shape of the price curve.  Wilder recommended looking for trend lines and
breakouts in the ASI to confirm price trend lines.

The starting point (ie.@: the zero point) for the running total is arbitrary.
In Chart it's merely the segment of data first displayed.  Wilder's
calculation applied a scaling factor based on the daily limit move, but this
is not done in Chart.  The shape of the resulting curve is not changed by
that.

@anchor{Swing Index}The raw swing index values can be viewed with the ``Swing
Index'' (which is under ``Low Priority'' in the indicator lists because it's
of little direct use).


@c ---------------------------------------------------------------------------

doc/chart.texi  view on Meta::CPAN

@ifnottex
@example
ATR = EMA[N] of True Range
@end example
@end ifnottex

The default smoothing period is 14 days, as recommended by Wilder.  The period
is always by Wilder's reckoning of EMA smoothing period (@pxref{Wilder EMA
period}).

The idea behind ATR is that when traders are enthusiastic, either in an
uptrend or downtrend, the range will be higher as the stock or commodity is
bid up or sold down through the day.  A lesser range suggests waning interest.

When a data source doesn't provide high/low values (some indices for
instance), then just close-to-close changes are used.  This may be of limited
use.

@cindex Normalized ATR
@anchor{Normalized ATR}
@subsection Normalized ATR

@cindex Forman, John
The normalized ATR by John Forman
(@uref{http://www.theessentialsoftrading.com}) expresses the ATR as a
percentage of the current closing price.  This makes it possible to compare
ATR values over long periods where a share price level (and hence the typical
daily ranges) have changed greatly.

@tex
$$ NATR = 100 \times { ATR \over close } $$
@end tex
@ifnottex
@example
              ATR
NATR = 100 * -----
             close
@end example
@end ifnottex


@c ---------------------------------------------------------------------------
@node Centre of Gravity Oscillator, Chaikin Money Flow, Average True Range, Indicators
@section Centre of Gravity Oscillator
@cindex Centre of gravity oscillator
@cindex CG
@cindex COG

@uref{http://www.mesasoftware.com/technicalpapers.htm} @*
@uref{http://www.mesasoftware.com/Papers/The%20CG%20Oscillator.pdf}

@cindex Ehlers, John
The Centre of Gravity (CG) oscillator by John Ehlers is a comparison of recent
prices against older prices within a given past N days.

Prices from those N days are imagined as weights placed on a beam, equally
spaced, and the CG oscillator is then the balance point or centre of gravity
along that beam.
@c FIXME:
@c  The prices used are the midpoint of each day's high/low.
If @ms{p,1} is today's price, @ms{p,2} yesterday's, etc, then the formula is

@tex
$$ CG = - { 1 \times p_1 + 2 \times p_2 + \cdots N \times p_N
            \over p_1 + p_2 \cdots p_N } $$
@end tex
@ifnottex
@example
       1*p[1] + 2*p[2] + ... + N*p[N]
CG = - ------------------------------
        p[1] +   p[2] + ... +   p[N]
@end example
@end ifnottex

The ``@math{-}'' sign puts the CG on a scale of @math{-N} at the oldest end,
up to @math{-1} at the newest prices end.  But those extremes are not reached,
instead CG hovers around the midpoint @math{-(N-1)/2}.  The scale is not
important, only the shape of the curve, which rises if recent prices are
higher, and falls if recent prices are lower.

Ehlers suggests looking at a past 10 days, and that's the default.  He notes
that if N is very small the CG becomes quite noisy, and that if N is large it
tends to become very unresponsive.

@subsection Additional Resources

@itemize
@item
@uref{http://www.linnsoft.com/tour/techind/cog.htm} -- sample graph of Intel
(symbol @samp{INTC}) from 2001/2.
@item
@uref{http://www.working-money.com/Documentation/FEEDbk_docs/Archive/082002/TradersTips/TradersTips.html}
-- formulas in TASC Trader's tips August 2002 (for article from May 2002).
@end itemize


@c ---------------------------------------------------------------------------
@node Chaikin Money Flow, Chaikin Oscillator, Centre of Gravity Oscillator, Indicators
@section Chaikin Money Flow
@cindex Chaikin money flow
@cindex Money flow, Chaikin
@cindex Index, Chaikin money flow

@cindex Chaikin, Marc
The Chaikin money flow index by Marc Chaikin is based on the
Accumulation/Distribution index calculations
(@pxref{Accumulation/Distribution}), but just within a past N-day window.  The
formula is

@tex
$$
Chaikin\,MF = { {total N day \;\; volume *
                \left( 2 {{close - low} \over {high - low}} - 1 \right) }
               \over total N day \;\; volume }
$$
@end tex
@ifnottex
@example
                                     /      close - low     \
              total N-day  volume * |  2 *  ----------- - 1  |
                                     \      high - low      /
Chaikin MF = ------------------------------------------------
                         total N-day  volume
@end example
@end ifnottex

The Acc/Dist style volume values in the numerator range between @math{+volume}
and @math{-volume} according to ``closing location value''.  They're summed
and expressed as a fraction of the total volume in that period.  This fraction
therefore ranges from @math{-1} to @math{+1}, but in practice the extremes are
rarely reached (since it would require every day to be a close at the day's
high to get @math{+1}, or every day at the low to get @math{-1}).

The idea is that buying strength is indicated by a close near the top of the
day's range, suggesting buyers have bid it up through to course of the day or
recovered from pullbacks.  Conversely a close near the bottom of the range
suggests sellers in control.  The amount of volume this is done on is worked
in, as a measure of the significance of the action.  In any case positive
values are bullish and negative values are bearish in this interpretation,
though perhaps with large values representing extremes which are likely to
reverse.

This Chaikin money flow is is similar to the plain money flow index
(@pxref{Money Flow Index}), but the latter uses close-to-close up or down,
where Chaikin uses close within the day's range as a fraction, not just an
``all or nothing'' up or down.

High/low and volume data are required before Chaikin money flow can be drawn,
this may not be available for some data sources (some stock indices in
particular).

It should be noted that ``money flow'' here is a shorthand for the enthusiasm
of buyers (or, when negative, sellers).  It's common to speak informally of
money flowing into or out of a stock, but of course there's never actually any
net money in or out since for every buyer there's a seller of the same amount.


@c ---------------------------------------------------------------------------
@node Chaikin Oscillator, Chande Momentum Oscillator, Chaikin Money Flow, Indicators
@section Chaikin Oscillator
@cindex Chaikin oscillator
@cindex Chaikin A/D oscillator
@cindex Oscillator, Chaikin

@cindex Chaikin, Marc
The Chaikin oscillator, or Chaikin A/D oscillator, by Marc Chaikin is simply
the difference between a 3-day and 10-day exponential moving average (EMA,
@pxref{Exponential Moving Average}) of the Accumulation/Distribution index
(@pxref{Accumulation/Distribution}).

@tex
$$ Chaikin\,Osc = EMA[3]\,of\,A/D - EMA[10]\,of\,A/D $$
@end tex
@ifnottex
@example
Chaikin Osc = EMA[3] of A/D - EMA[10] of A/D
@end example
@end ifnottex

The periods 3 and 10 are configurable.


@c ---------------------------------------------------------------------------
@node Chande Momentum Oscillator, Commodity Channel Index, Chaikin Oscillator, Indicators
@section Chande Momentum Oscillator
@cindex Chande Momentum Oscillator
@cindex CMO

@cindex Chande, Tushar
The Chande Momentum Oscillator (CMO) by Tushar Chande is a variation on the
RSI (@pxref{Relative Strength Index}) using an SMA (@pxref{Simple Moving
Average}) and on a scale between @math{-100} and @math{+100}.

@tex
$$ CMO = { SMA[N] \; of \; (close - prev\;close)
     \over SMA[N] \; of \; \left| close - prev\;close \right| } $$
@end tex
@ifnottex
@example
            SMA[N] of   (close - prev close)
CMO = 100 * ---------------------------------
            SMA[N] of  abs(close - prev close)
@end example
@end ifnottex

The formula can also be written in the style of the RSI, with U=close-prev on
an up day, and D=prev-close on a down day.

@tex
$$ CMO = { SMA[N] \; of \; (close - prev\;close)
     \over SMA[N] \; of \; \left| close - prev\;close \right| } $$
@end tex
@ifnottex
@example
                          SMA[N] of U
CMO = -100 + 200 * -------------------------
                   SMA[N] of U + SMA[N] of D
@end example
@end ifnottex

See also TSI (@pxref{True Strength Index}), another different moving average
for an RSI.


@c ---------------------------------------------------------------------------
@node Commodity Channel Index, Coppock Curve, Chande Momentum Oscillator, Indicators
@section Commodity Channel Index
@cindex Commodity channel index
@cindex CCI
@cindex Index, commodity channel
@cindex Channel, commodity index

@cindex Lambert, Donald
The Commodity Channel Index by Donald Lambert is an oscillator designed to
identify overbought and oversold conditions in a ranging market.  It expresses
the difference between today's typical price and recent average as a fraction
of each day's mean deviation from that average.

@tex
$$ CCI = { tp_{today} - mean\;tp \over 0.015 \times meandev } $$
@end tex
@ifnottex
@example
      tp[today] - mean tp
CCI = -------------------
        0.015 * meandev
@end example
@end ifnottex

The @math{mean tp} is over a given past N days.  ``Typical price'' is the
average of high, low and close.  Chart uses just the close if there's no
high/low data from a particular data source.

@tex
$$ tp = {high + low + close \over 3} $$
@end tex
@ifnottex
@example
     high + low + close
tp = ------------------
             3
@end example
@end ifnottex

The mean deviation @math{meandev} is the mean difference between each of the N
days typical price and the mean tp.  The differences are taken as absolute

doc/chart.texi  view on Meta::CPAN

$$ raw = 2 \times { price - NdayLow \over NdayHigh - NdayLow} - 1 $$
@end tex
@ifnottex
@example
price = (high + low) / 2

            price - Ndaylow
raw = 2 * ------------------ - 1
          Ndayhigh - Ndaylow
@end example
@end ifnottex

This raw position is smoothed by a 5-day EMA (@pxref{Exponential Moving
Average}) then a log form which is the fisher transform, before a final
further 3-day EMA smoothing.

@tex
$$ smoothed = EMA[5] \; of \; raw $$
$$ fisher = EMA[3] \; of \; \log { 1 + smoothed \over 1 - smoothed } $$
@end tex
@ifnottex
@example
smoothed = EMA[5] of raw

                       1 + smoothed
fisher = EMA[3] of log ------------
                       1 - smoothed
@end example
@end ifnottex

The effect of the logarithm is to make ``smoothed'' values near 0 remain near
there, but values near 1 and @math{-1} grow greatly, thus highlighting
extremities.  A ``smoothed'' value of exactly @m{\pm 1, +/-1} would transform
to @m{\pm\inf, +/-infinity}, so a clamp of 0.999 is applied, effectively
limiting the final result to about @math{@pm{}7.5}.

@subsection Additional Resources

@itemize
@item
@uref{http://www.linnsoft.com/tour/techind/fish.htm} -- sample Nasdaq 100
symbol @samp{QQQ} from August 2002.  (For Chart use Yahoo symbol @samp{^IXIC}
to get that data).
@end itemize


@c ---------------------------------------------------------------------------
@node Force Index, Forecast Oscillator, Fisher Transform, Indicators
@section Force Index
@cindex Elder force index
@cindex Force index
@cindex Index, force
@cindex EFI
@cindex %F

@cindex Elder, Alexander
The force index by Dr.@: Alexander Elder shows daily close-to-close changes
multiplied by the volume traded, so that moves on greater volume are given
more significance.  The raw @m{change \times volume, change*volume} values are
smoothed slightly with a 2-day EMA (@pxref{Exponential Moving Average}), so
the formula is simply

@tex
$$ Force\,Index = EMA[2] \; of \; \left( volume \times (close - prev\,close)\right) $$
@end tex
@ifnottex
@example
Force Index = EMA[2] of (volume * (close - prev close))
@end example
@end ifnottex

An increasing force index indicates strong interest in an upward move, when it
falls back either price or volume or both have declined suggesting waning
interest.  Conversely for a negative and falling force index on the downside.
The smoothing period for the EMA is configurable.


@c ---------------------------------------------------------------------------
@node Forecast Oscillator, Gopalakrishnan Range Index, Force Index, Indicators
@section Forecast Oscillator
@cindex Forecast oscillator
@cindex Oscillator, forecast
@cindex FOSC
@cindex %F

@cindex Chande, Tushar
The %F forecast oscillator by Tushar Chande shows deviation between today's
closing price and an N-day linear regression forecast (@pxref{Linear
Regression}) of that close.  The deviation is expressed as a percentage of the
close, so the formula is

@tex
$$ \%F = { close - forecast \over close } \times 100 $$
$$ forecast = linear \; regression \; of \; previous \; N days,
              \; at \; today $$
@end tex
@ifnottex
@example
     close - forecast
%F = ---------------- * 100
          close

forecast = linear regression of previous N days, at today
@end example
@end ifnottex

The N days prices for the linear regression start from yesterday's close, and
the forecast value is the line extended out to today.  This forecast line is
like the EPMA (@pxref{Endpoint Moving Average}), but going out one day
further.  Chande suggests using a 5 day regression for short term trading, and
that's the default in Chart.


@c ---------------------------------------------------------------------------
@node Gopalakrishnan Range Index, Intraday Momentum Index, Forecast Oscillator, Indicators
@section Gopalakrishnan Range Index
@cindex Gopalakrishnan range index
@cindex Index, Gopalakrishnan range
@cindex GAPO

@cindex Gopalakrishnan, Jayanthi
The Gopalakrishnan Range Index (GAPO) by Jayanthi Gopalakrishnan quantifies
the variability in a stock, based on the logarithm of the trading range over
an N-day period (default 5 days).

@tex
$$ GAPO = { log(high_{Ndays} - low_{Ndays}]) \over log N } $$
@end tex
@ifnottex
@example
       log(high[Ndays] - low[Ndays])
GAPO = -----------------------------
                  log(N)
@end example
@end ifnottex

The idea is to identify markets which are more erratic than others.  It will
be noted though that there's no scaling to the overall price level.  In Chart
GAPO is  under ``Low Priority'' in the indicator lists.


@c ---------------------------------------------------------------------------
@node Intraday Momentum Index, Klinger Volume Oscillator, Gopalakrishnan Range Index, Indicators
@section Intraday Momentum Index
@cindex Intraday momentum index
@cindex Index, Intraday momentum
@cindex IMI

@cindex Chande, Tushar
The intraday momentum index (IMI) by Tushar Chande expresses upward

doc/chart.texi  view on Meta::CPAN

``Money flow'' on a given day is typical price multiplied by volume.  This is
the money that flowed, ie. an approximation to the dollar volume traded.

@tex
$$ money\ flow = typical\ price \times volume $$
@end tex
@ifnottex
@example
money flow = typical price * volume
@end example
@end ifnottex

Across the N-day period two totals are formed.  ``Positive money flow'' is the
money flow on days where the typical price is higher the previous day's
typical price, and ``negative money flow'' when below.  Days when typical
price is unchanged are ignored.  The MFI is then

@tex
$$ MFI = 100 \times {positive\ money\ flow \over
               positive\ money\ flow + negative\ money\ flow} $$
@end tex
@ifnottex
@example
                      positive money flow
MFI = 100 * -----------------------------------------
            positive money flow + negative money flow
@end example
@end ifnottex

Generally an MFI level of 80 is considered overbought, and 20 considered
oversold.  Those levels are shown as shown as dashed lines.

MFI is similar to RSI (@pxref{Relative Strength Index}) in its construction
and use.  Both are looking at up days versus totalled up and down days, but
the RSI scales by price change amounts where MFI scales on dollar volume (or
an approximation to that).

It should be noted ``money flow'' refers to dollar volume, ie. the total value
of shares traded.  Sometimes finance commentators speak of money ``flowing
into'' a stock, but that expression only means buyers are enthusiastic.
Obviously there's never any net money in or out, because for every buyer
there's a seller of the same amount.

For the purposes of the MFI, ``money flow'', ie. dollar volume, on an up day
is taken to represent the enthusiasm of buyers, and on a down day to
represent the enthusiasm of sellers.  An excessive proportion in one direction
or the other is interpreted as an extreme, likely to result in a price
reversal.


@c ---------------------------------------------------------------------------
@node On-Balance Volume, Negative Volume Index, Money Flow Index, Indicators
@section On-Balance Volume
@cindex On-balance volume
@cindex OBV
@cindex Volume, on-balance

On-balance volume (OBV) is a running total of daily volume, with volume on an
up day added and volume on a down day subtracted.  An up day is a close higher
than the previous day's close, and vice versa a down day.  So if @ms{p,1} is
today's close and @ms{p,2} is yesterday's, the formula is simply

@tex
$$ OBV = OBV_{prev} + \left\{ \matrix{  v_1 & \mathop{\rm if} \; p_1 > p_2 \cr
                                          0 & \mathop{\rm if} \; p_1 = p_2 \cr
                                       -v_1 & \mathop{\rm if} \; p_1 < p_2 \cr
   } \right. $$
@end tex
@ifnottex
@example
                 /  v1     if p1 > p2
                |
OBV = OBVprev + |   0      if p1 = p2
                |
                 \  - v1   if p1 > p2
@end example
@end ifnottex

The starting point (ie.@: the zero point) for the running total is arbitrary.
In Chart it's merely the segment of data first displayed.

See also @ref{Price and Volume Trend}, and @ref{Accumulation/Distribution},
which accumulate volume in similar ways.


@c ---------------------------------------------------------------------------
@node Negative Volume Index, Polarized Fractal Efficiency, On-Balance Volume, Indicators
@section Negative Volume Index
@cindex Negative volume index
@cindex NVI
@cindex Index, negative volume

@cindex Fosback, Norman
The Negative Volume Index (NVI) and Positive Volume Index (PVI) by Norman
Fosback (@uref{http://www.fosback.com}) track price changes according to
changes in volume.  The NVI tracks closing price changes that occur on days
with lower volume than yesterday, and the PVI conversely tracks those with
higher volume than yesterday.

@tex
$$ NVI = NVI_{prev} \times \left\{ \matrix{
  close \over close_{prev} & \mathop{\rm if} \; vol < vol_{prev} \cr
  1                        & \mathop{\rm if} \; vol \ge vol_{prev} \cr
} \right. $$
@end tex
@ifnottex
@example
                   /   close
                  |  -----------    if vol < vol[prev]
NVI = NVI[prev] * |  close[prev]
                  |
                   \     1          if vol >= vol[prev]

@end example
@end ifnottex

@tex
$$ PVI = PVI_{prev} \times \left\{ \matrix{
  close \over close_{prev} & \mathop{\rm if} \; vol > vol_{prev} \cr
  1                        & \mathop{\rm if} \; vol \le vol_{prev} \cr
} \right. $$
@end tex
@ifnottex
@example
                   /   close
                  |  -----------    if vol > vol[prev]
PVI = PVI[prev] * |  close[prev]
                  |
                   \     1          if vol <= vol[prev]

@end example
@end ifnottex

The fraction @m{close/close_{prev}, close/close[prev]} means that the indices
follow percentage daily changes in the closing prices, but only changes on the
selected lower or higher volume days are used.  The starting point for the
changes is arbitrary, only the shape of the resulting line matters.  In Chart
the start is 100 for the first data portion displayed.

The principle behind the NVI is that on high volume days an uninformed crowd
is dominating, whereas on quieter days ``smart money'' is establishing
positions.  Fosback holds there's a 95% probability of a bull market when the
NVI rises above its one-year moving average.
@c FIXME   Such an average can be viewed in
@c Chart by selecting an SMA (@pxref{Simple Moving Average}) of 260 days (one
@c year's worth of weekdays).


@c ---------------------------------------------------------------------------
@node Polarized Fractal Efficiency, Pretty Good Oscillator, Negative Volume Index, Indicators
@section Polarized Fractal Efficiency
@cindex Polarized fractal efficiency
@cindex PFE
@cindex Fractal, polarized efficiency indicator

The Polarized Fractal Efficiency indicator by Hans Hannula shows how
efficient, meaning how much like a straight line, the price movement has been
over the past N days.

The net distance travelled over the past N days is expressed as a percentage
of the total of each day's distance travelled.  Distance is measured in
two-dimensions, like a ruler on the plotted graph.  Rise (or fall) is
expressed as a percentage, and each day counts as 1 unit across.  So the
formula, on closing prices @ms{p,1} (today) to @ms{p,N} is

@tex
$$ PFE = { \mathop{\rm Hypot} (N-1, \; \mathop{\rm Pchg}(p_1,p_N))
       \over { \mathop{\rm Hypot} (1, \; \mathop{\rm Pchg}(p_1,p_2))
             + \cdots
             + \mathop{\rm Hypot} (1, \; \mathop{\rm Pchg}(p_{N-1},p_N)) }} $$
$$ \mathop{\rm Sign}(x) = 1 \; if \; X>0; \; or \; -1 \; if \; X<0 $$
$$ \mathop{\rm Pchg}(new,old) = 100 \times { new - old \over old } $$
$$ \mathop{\rm Hypot}(x,y) = \sqrt{x^2 + y^2} $$
@end tex
@ifnottex
@example
                   Sign(p1-pN) * Hypot(N-1, Pchg(p1,pN))
PFE = 100 * -------------------------------------------------------
            Hypot(1, Pchg(p1,p2)) + ... + Hypot(1, Pchg(p[N-1],pN))

Sign(X) = 1 if X>0, or -1 if X<0

                      new - old
Pchg(new,old) = 100 * ---------
                         old

Hypot(x,y) = sqrt (x^2 + y^2)
@end example
@end ifnottex

Here ``Pchg'' is a percentage change up or down from ``new'' to ``old'' price,
and ``Hypot'' is the distance (the hypotenuse) for a move of X horizontally
and Y vertically.  ``Sign'' means that PFE is positive or negative according
to whether the change over the past N days is up or down.

At the extremes of 100 or -100, price movement is at maximum efficiency, with
the past N days making a perfectly straight line.  An almost straight line is
generally very close to 100 too.  A midpoint of 0 means there's been no net
change over the past N days.

Hannula looked at price changes over 10 day period (horizontal distance of 9),
and this is the default in Chart.  A smoothing parameter is provided too; it
applies an exponential moving average (@pxref{Exponential Moving Average}) to
the PFE@.  The default is 5 days smoothing, a value of 0 means no smoothing
(to see the raw values).

@subsection Additional Resources
@itemize
@item
@uref{http://www.traderslog.com/polarized-fractal-efficiency.htm} -- sample
chart of IBM, year not shown but data is 2002.
@item
@uref{http://transcripts.fxstreet.com/2005/09/polarized_fract.html} --
presentation on PFE by Erik Long.
@end itemize


@c ---------------------------------------------------------------------------
@node Pretty Good Oscillator, Price and Volume Trend, Polarized Fractal Efficiency, Indicators
@section Pretty Good Oscillator
@cindex Pretty good oscillator
@cindex PGO
@cindex Oscillator, pretty good

The ``Pretty Good Oscillator'' (PGO) by Mark Johnson measures the distance of
the current close from its N-day simple moving average (@pxref{Simple Moving
Average}), expressed in terms of an average true range (@pxref{Average True
Range}) over a similar period.

@tex
$$ PGO = { close - SMA[N]\,of\,close \over EMA[N] of true range }$$
@end tex
@ifnottex
@example
      close - SMA[N] of closes
PGO = ------------------------
        EMA[N] of true range
@end example
@end ifnottex

So for instance a PGO value of +2.5 would mean the current close is 2.5
average days' range above the SMA.

Johnson's approach was to use it as a breakout system for longer term trades.
If the PGO rises above 3.0 then go long, or below -3.0 then go short, and in
both cases exit on returning to zero (which is a close back at the SMA).

@subsection Additional Resources
@itemize
@item
@uref{http://trader.online.pl/MSZ/e-w-Pretty_Good_Oscillator.html} -- formula,
and sample chart of Cisco (@samp{CSCO}) from 2003.
@end itemize


@c ---------------------------------------------------------------------------
@node Price and Volume Trend, QStick, Pretty Good Oscillator, Indicators
@section Price and Volume Trend
@cindex Price and volume trend
@cindex PVT
@cindex Volume, price trend

Price and Volume Trend (PVT) is a running total of daily volume, with each
day's volume added or subtracted according to the percentage change in the
today's closing price over yesterday's.

@tex
$$ PVT = PVT_{prev} + volume \times
  { close_{today} - close_{prev} \over close_{prev} } $$
@end tex
@ifnottex
@example
                         close[today] - close[yesterday]
PVT = PVTprev + volume * -------------------------------
                                 close[yesterday]
@end example
@end ifnottex

The starting point (ie.@: the zero point) for the running total is arbitrary.
In Chart it's merely the segment of data first displayed.

PVT is similar to On-balance volume (@pxref{On-Balance Volume}), but
accumulating a portion of the volume.  And see also
@ref{Accumulation/Distribution}, which also accumulates volume.


@c ---------------------------------------------------------------------------
@node QStick, R-Squared Index, Price and Volume Trend, Indicators
@section QStick
@cindex QStick

The QStick indicator shows the dominance of black (down) or white (up)
candlesticks, which are red and green in Chart, as represented by the average
open to close change for each of past N days.

@tex
$$ QStick = (close_1 - open_1) + \cdots + (close_N - open_N) \over N $$
@end tex
@ifnottex
@example
         close[1]-open[1] + ... + close[N]-open[N]
QStick = -----------------------------------------
                             N
@end example
@end ifnottex

Days which are up have positive amounts for @math{close-open}, days which are
down have negative amounts.  In adding them up they cancel out until the
dominance of one over the other results.


@c ---------------------------------------------------------------------------
@node R-Squared Index, RAVI, QStick, Indicators
@section R-Squared Index
@cindex R-squared index
@cindex Index, R-Squared

@cindex Chande, Tushar
@cindex Kroll, Stanley
@cindex Correlation coefficient
@cindex Coefficient, correlation
@cindex Coefficient of determination
The R-squared indicator by Tushar Chande and Stanley Kroll is a measure of how
closely the past N days resemble a straight line, ie.@: a trend.  It
calculates what is called in statistics the @dfn{coefficient of determination}
of the prices versus a straight line.  This coefficient is written @math{r^2},
hence the name of the indicator.

For reference, the formulas are as follows, where X values are the closing
prices and Y values are a straight line 1,2,@dots{},N@.  Variance is the
square of standard deviation (@pxref{Standard Deviation}).

@tex
$$ r^2 = { (\mathop{Covariance} X,Y)^2
           \over (\mathop{Variance} X) (\mathop{Variance} Y) } $$
$$ \mathop{Covariance} X,Y = \mathop{Mean} (XY)
                             - (\mathop{Mean} X) (\mathop{Mean} Y) $$
$$ \mathop{Variance} X = \mathop{Mean} (X^2) - (\mathop{Mean} X)^2 $$
@end tex
@ifnottex
@example
         (Covariance X,Y)^2
r^2 = -----------------------
      Variance X * Variance Y

Covariance X,Y = Mean (X*Y) - (Mean X) * (Mean Y)

Variance X = Mean(X^2) - (Mean X)^2
@end example
@end ifnottex

The R-squared indicator ranges from 0 meaning no apparent correlation to the
straight line, up to 1 for perfect correlation.  The slope of the closing
prices line doesn't matter, nor does the absolute price level, only how well
they make a straight line.

Chande and Kroll suggested using a 14-day period, and that's the default in
Chart.
@c FIXME
@c   They also described a 14-day simple moving average (@pxref{Simple
@c Moving Average}) on the raw values, and that can be shown in Chart the same as
@c any average on an indicator (@pxref{View Style}).


@c ---------------------------------------------------------------------------
@node RAVI, Relative Strength Index, R-Squared Index, Indicators
@section RAVI
@cindex RAVI

RAVI is a simple indicator showing whether a stock is trending.  It calculates
the percentage difference between current prices and older prices.  Current
prices are represented by a short SMA and the longer time frame by a long SMA
(@pxref{Simple Moving Average}).  The defaults are 7 days and 65 days.

@tex
$$ RAVI = 100 \times { | SMA[short] - SMA[long] | \over SMA[long] }$$
@end tex
@ifnottex
@example
             abs (SMA[short] - SMA[long])
RAVI = 100 * ----------------------------
                      SMA[long]
@end example
@end ifnottex


@c ---------------------------------------------------------------------------
@node Relative Strength Index, Relative Volatility Index, RAVI, Indicators
@section Relative Strength Index

doc/chart.texi  view on Meta::CPAN

$$ U = 0 $$
$$ D = close_{yesterday} - close_{today} $$
@end tex
@ifnottex
@example
U = 0
D = close[yesterday] - close[today]
@end example
@end ifnottex

The sequence of U values over time is averaged with an EMA
(@pxref{Exponential Moving Average}) and likewise the D values.  The
ratio is the ``relative strength'',

@tex
$$ RS = { EMA[N] \, of \, U \over EMA[N] \, of \, D } $$
@end tex
@ifnottex
@example
     EMA[N] of U
RS = -----------
     EMA[N] of D
@end example
@end ifnottex

This is turned into an index between 0 and 100,

@tex
$$ RSI = 100 \times { 1 \over 1 + RS } $$
@end tex
@ifnottex
@example
              1
RSI = 100 * ------
            1 + RS
@end example
@end ifnottex

This can also be written as follows, emphasising the way the RSI measures up
movement as a proportion of the two up and down,

@tex
$$ RSI = 100 \times { EMA[N]\,of\,U
                \over (EMA[N]\,of\,U) + (EMA[N]\,of\,D) } $$
@end tex
@ifnottex
@example
                    EMA[N] of U
RSI = 100 * -----------------------------
            (EMA[N] of U) + (EMA[N] of D)
@end example
@end ifnottex

Wilder recommended a smoothing period of N=14, and that's the default in
Chart.  Note also that the period is interpreted by Wilder's reckoning of EMA
smoothing (see @ref{Wilder EMA period}).

An index value of 70 is considered overbought and 30 oversold; those levels
are shown as dashed lines.  The principle is that after a large proportion of
movement in one direction, a reaction the other way becomes likely.  On the
other hand it's easy to see from the formula that a steady progressive trend
(every day up, or every day down) can push the RSI to an extreme and hold it
there.

The term ``relative strength'' also refers to a comparison between a stock and
the overall market.  This is sometimes called ``relative strength
comparative'' to avoid confusion.  This is unrelated to the relative strength
and relative strength index described in this section.

See also CMO (@pxref{Chande Momentum Oscillator}) which is an RSI with SMA
smoothing, and TSI (@pxref{True Strength Index}) which is an RSI with
double-EMA smoothing.


@c ---------------------------------------------------------------------------
@anchor{Stochastic RSI}
@subsection Stochastic RSI
@cindex Stochastic RSI

The stochastic RSI is an N-day unsmoothed %K stochastic
@c FIXME
@c (@pxref{Stochastics}) 
applied to the RSI line.  The position of today's RSI is
expressed as a fraction 0 to 1 of its overall range (lowest to highest) in the
past N days, the same N as used for the RSI calculation,

@tex
$$ Stoch\,RSI = { RSI_{today} - RSI_{Nday\,low}
                \over RSI_{Nday\,high} - RSI_{Nday\,low} } $$
@end tex
@ifnottex
@example
               RSI[today] - RSI[Nday low]
Stoch RSI =  ------------------------------
             RSI[Nday high] - RSI[Nday low]
@end example
@end ifnottex


@c ---------------------------------------------------------------------------
@node Relative Volatility Index, Random Walk Index, Relative Strength Index, Indicators
@section Relative Volatility Index
@cindex Relative volatility index
@cindex RVI
@cindex Index, relative volatility

@cindex Dorsey, Donald
The Relative Volatility Index (RVI) by Donald Dorsey is similar to the RSI
(@pxref{Relative Strength Index}) but where the RSI adds up price change
amounts based on price direction, the RVI instead adds standard deviations
(stddev, @pxref{Standard Deviation}) based on price direction.

The standard deviation is over a past 10 days, then an EMA (@pxref{Exponential
Moving Average}) of deviations on up days is compared to all deviations,
giving Dorsey's original 1993 definition of RVI on closing prices.

@tex
$$ S = Stddev[10\,days] $$
$$ U = \left\{
 \matrix{ S & \mathop{\rm if} \; price > prev\,price \cr
          0 & otherwise \hfill \cr

doc/chart.texi  view on Meta::CPAN

@end example
@end ifnottex

When a data source doesn't provide high/low values just the closes are used,
which ends up as Dorsey's original.  The stddev period of 10 days and the
default EMA of 14 days are parameters (@pxref{View Style}).  The EMA period
follows J.@: Welles Wilder's reckoning (@pxref{Wilder EMA period}), the same
as an RSI.

@anchor{Inertia}
@section Inertia
@cindex Inertia

Dorsey also smoothed the RVI with a 20-day least squares moving average
(LSQMA, @pxref{Endpoint Moving Average}) and called the result the inertia
indicator.  The 20-day smoothing period is a parameter.

An LSQMA can of course also be applied to an RVI directly, this can be good to
see how it smooths.  But inertia is offered as a separate selection since the
smoothed line tends to follow the raw RVI quite closely, making it hard to see
which is which.


@c ---------------------------------------------------------------------------
@node Random Walk Index, Stochastics, Relative Volatility Index, Indicators
@section Random Walk Index
@cindex Random walk index
@cindex Index, random walk
@cindex RWI

The random walk index (RWI) by E.@: Michael Poulos is a measure of how much
price ranges over N days differ from what would be expected by a random walk
(randomly going up and down).  A bigger than expected range suggests a trend.

The index is in two parts, an RWI high which looks at upward movement and an
RWI low for downward movement.  In Chart RWI high is shown in green, and RWI
low in red.  The RWI high looks at terms like

@tex
$$ { High[today] - Low[K] \over Average TR [K] } \times { 1 \over \sqrt K } $$
@end tex
@ifnottex
@example
High[today] - Low[K]     1
-------------------- * ------
   Average TR [K]      sqrt(K)
@end example
@end ifnottex

which is the move from the low K days ago up to today's high, scaled by an
average of the true range (TR, @pxref{True Range}).  Such terms are calculated
for each number of days 2, 3, etc, up to the given RWI parameter N, and the
maximum is the RWI@.  The first term for instance is today's high less
yesterday's low, compared to a two-day average of the true range (yesterday's
true range and the day before's).  RWI low is similar, but using @math{High[K]
- Low[today]} for the movement down from past high to today's low.

The factor @m{\sqrt K, sqrt(K)} compares the movement to a random walk.  If a
random walk has a 50% chance of going up by one, or a 50% chance of going down
by one, then it can be shown that on average the distance travelled after K
steps is @m{\sqrt K, sqrt(K)}.  So the formula compares observed distance in
average day's steps compared to the @m{\sqrt K, sqrt(K)} steps which would be
the expected move if it were random.  Thus 1 is when movement is apparently
random, and higher or lower if some apparently non-random trend or lack of
trend (respectively) appears to be present.


@c ---------------------------------------------------------------------------
@node Stochastics, TD Range Expansion Index, Random Walk Index, Indicators
@section Stochastics
@cindex Stochastics

@cindex Lane, George
Stochastics are an oscillator and signal line described by George Lane based
on each day's close within the total trading range of past N days.  This
should not be confused with stochastic processes etc in mathematics, the two
are unrelated.

@cindex %K stochastic
The %K line is the close position within the past N-days trading range
(highest high to lowest low) expressed as a percentage 0 to 100.

@tex
$$ \%K = 100 \times {{close - Nday\;low} \over Nday\;high - Nday\;low } $$
@end tex
@ifnottex
@example
             close - Nday low
%K = 100 * --------------------
           Nday high - Nday low
@end example
@end ifnottex

@cindex %D stochastic
An extreme of 0 is reached for a close at the day's low which is also a new
N-day low.  Likewise 100 for a close at the day's high and a new N-day high.
A signal line %D is added by smoothing %K with a simple moving average
(@pxref{Simple Moving Average}).

@tex
$$ \%D = SMA[D] \; of \; \%K $$
@end tex
@ifnottex
@example
%D = SMA[D] of %K
@end example
@end ifnottex

The default periods in chart are 14 days for %K, and 3 days smoothing for %D.
The %K line is drawn in red and the %D line in green.

@cindex Fast stochastics
@cindex Slow stochastics
%K and %D just described are called the ``fast'' stochastics.  Corresponding
``slow'' stochastics are formed by smoothing %K with a simple moving average,
and calculating %D from that smoothed series.  The extra smoothing is the
``slow days'' parameter in Chart.  The default is 0 for no slowing, a value of
3 is often used.

Incidentally, a value of 1 for the slowing is the same as no slowing, because
a 1-period SMA of course doesn't change the data.

doc/chart.texi  view on Meta::CPAN

moving average of closing prices.  The slope is calculated as a percentage
change between today and yesterday's triple smoothed EMA values.

@tex
$$ TRIX = 100 \times { EMAofEMAofEMA[today] - EMAofEMAofEMA[yesterday]
                       \over EMAofEMAofEMA[yesterday] } $$
@end tex
@ifnottex
@example
             EMAofEMAofEMA[today] - EMAofEMAofEMA[yesterday]
TRIX = 100 * ---------------------------------------
                    EMAofEMAofEMA[yesterday]
@end example
@end ifnottex

A positive TRIX means the triple EMA is rising, suggesting a steady uptrend,
in the same way any rising moving average does.  Conversely a negative value
means the triple EMA is falling, suggesting a downtrend.  A cross through zero
is a peak or trough in the triple EMA and may suggest a trend change.  Chart
draws a line at the zero level.

@cindex EMA of EMA of EMA
@cindex Triple exponential moving average
@cindex Average, triple exponential
@cindex Moving average, triple exponential
@anchor{EMA of EMA of EMA}
@section EMA of EMA of EMA

A triple smoothed EMA is prices smoothed with an EMA then those values
smoothed again with another EMA and finally a third time with a further EMA
(all of the same given period).

The result is quite different from a plain EMA@.  It's still a weighted
average of recent prices, but whereas a plain EMA is dominated by the most
recent prices, a triple EMA spreads much more broadly, and the latest few
days' influence is in fact smaller than the peak weights (at about N-days
back).  The following graph shows the weights for @math{N=10}.

@myimage{chart-ema-3-weights, EMA of EMA of EMA weights graph}

An EMA of EMA of EMA can also be viewed directly, in the upper prices window.
This can be used to see the effect its smoothing has, and may help for
adjusting the period N to get a desired smoothness versus responsiveness.
Note the N-day period is set separately for the two windows.


@c ---------------------------------------------------------------------------
@node Twiggs Money Flow, Ulcer Index, TRIX, Indicators
@section Twiggs Money Flow
@cindex Twiggs money flow
@cindex Money flow, Twiggs
@cindex Index, Twiggs money flow

@uref{http://www.incrediblecharts.com/technical/twiggs_money_flow.htm}

@cindex Twiggs, Colin
The Twiggs money flow index by Colin Twiggs is a variation of the Chaikin
money flow index (@pxref{Chaikin Money Flow}) using true range so as to
include gap moves, and using EMA smoothing (@pxref{Exponential Moving
Average}) to avoid jumps when a high volume day drops out of the calculation.
The formula is

@tex
$$
Twiggs\,MF = { {EMA[N] \,of\;\; volume *
          \left( 2 {{close - truelow} \over {truehigh - truelow}} - 1 \right) }
               \over EMA[N] \,of\;\; volume } $$
$$ truehigh = \max (high, prevclose) $$
$$ truelow  = \min (low, prevclose) $$
@end tex
@ifnottex
@example
                                /      close - truelow       \
            EMA[N] of  volume * | 2 * ------------------ - 1 |
                                \     truehigh - truelow     /
Twiggs MF = --------------------------------------------------
                  EMA[N] of  volume

truehigh = max (high, prevclose)
truelow  = min (low,  prevclose)
@end example
@end ifnottex

The default EMA period is 21 days, and the period is reckoned by J.@: Welles
Wilder's method (@pxref{Exponential Moving Average}).


@c ---------------------------------------------------------------------------
@node Ulcer Index, Ultimate Oscillator, Twiggs Money Flow, Indicators
@section Ulcer Index
@cindex Ulcer index
@cindex Index, Ulcer

@uref{http://www.tangotools.com/ui/ui.htm}

@cindex Martin, Peter
The Ulcer Index by Peter Martin is a measure of downside volatility.  For a
given N-day period the closing prices are considered from oldest to newest and
for each close a retracement percentage is calculated, relative to the highest
close so far.

@tex
$$ R_i = 100 \times { price_i - maxprice\,so\,far \over maxprice\,so\,far } $$
@end tex
@ifnottex
@example
       price[i] - maxprice so far
R[i] = --------------------------
           maxprice so far
@end example
@end ifnottex

@cindex Quadratic mean
@cindex Mean, quadratic
So for instance a price $5.00 falling back to $4.50 is a -10% retracement.
These are averaged with a quadratic mean, which has the effect of emphasising
large drawdowns, but incorporating all into the result.

@tex
$$ Ulcer = \sqrt { R_1^2 + R_2^2 + \cdots R_N^2 \over N } $$
@end tex

doc/chart.texi  view on Meta::CPAN

high.  Pullbacks smaller than the given X% are ignored.  The trend is only
considered to have turned down when a point X% below that latest high is
penetrated.  Then a down line is drawn, it in turn continuing until a reversal
of more than X% above the last lowe occurs.  The result is a kind of zig zag,
ignoring small moves, small according to the X%.

For the last line segment, at the right of the chart, the line is drawn to the
high (or low) then horizontally to the edge of the screen.  The horizontal
part means there hasn't yet been a retracement of X% from that level shown.

@subsection Additional Resources
@itemize
@item
@uref{http://stockcharts.com/education/IndicatorAnalysis/indic_ZigZag.html} --
sample chart of @samp{HPQ} from 1999/2000.
@end itemize


@c ---------------------------------------------------------------------------
@node Common Calculations, Other Indicator Packages, Indicators, Top
@chapter Common Calculations
@cindex Common calculations

The following are algorithms and calculations shared among various indicators
and averages.

@menu
* Linear Regression::
* Standard Deviation::
* True Range::
@end menu


@c ---------------------------------------------------------------------------
@node Linear Regression, Standard Deviation, Common Calculations, Common Calculations
@section Linear Regression
@cindex Linear regression
@cindex Least squares, line

The ``least squares'' or ``linear regression'' algorithm produces a best
fitting straight line through the middle of a set of N data points
@m{x_1@comma{}y_1@comma{} ...@comma{} x_N@comma{}y_N, x1@comma{}y1@comma{}
...@comma{} xN@comma{}yN}.  In Chart this means a set of prices Y, and dates X
(with non-trading days collapsed out).

For a possible fitted line @m{L(X)=a+bX,L(X)= a + b*X}, the vertical distance
from the line to each point is squared, and a total deviation formed.

@tex
$$ SumSquares = (y_1 - L(x_1))^2 + \cdots + (y_N - L(x_N))^2 $$
@end tex
@ifnottex
@example
SumSquares = (y1 - L(x1))^2 + ... + (yN - L(xN))^2
@end example
@end ifnottex

The line parameters @math{a} and @math{b} are then chosen to make SumSquares
as small as possible (hence the name ``least squares''), and there's just one
line with that smallest SumSquares.  The calculation is made easier if the X
coordinates are shifted so that @math{Mean(X)=0}.  With that the formulas for
@math{a} and @math{b} are

@tex
$$ a = Mean \; Y = { y_1 + \cdots + y_N \over N } $$
$$ b = { x_1 y_1 + \cdots x_N y_N \over x_1^2 \cdots + x_N^2 } $$
@end tex
@ifnottex
@example
             y1 + ... + yN
a = Mean Y = -------------
                   N

    x1*y1 + ... + xN*yN
b = -------------------
      x1^2 + ... xN^2
@end example
@end ifnottex

A least squares fit is ``best'' under certain mathematical assumptions:
basically that the data points were a straight line to which normally
distributed random amounts (positive or negative) have been added.  Of course
an underlying straight line is unlikely in market price data, or in economics
generally, and in particular any cyclical component invalidates the
assumptions.  Even so the algorithm is quite widely used because it offers an
objective basis for fitting a line.

@cindex Linear regression slope indicator
@cindex Regression coefficient
@cindex Coefficient, regression
@anchor{Linear Regression Slope}
@subsection Slope

The slope of the linear regression line, the @math{b} above, is sometimes
called the @dfn{regression coefficient}.  This is available as an indicator
(Linear Regression Slope), to show how steep the fitted trend line is.  The
units are price change per day, which is negative for a downward sloping line.
This may or may not be particularly useful so it's under ``Low Priority'' in
the indicator lists.

@cindex Standard error
@anchor{Linear Regression Standard Error}
@subsection Standard Error

Standard error (stderr) is a statistical measure of how much values differ
from an assumed underlying curve.  It's calculated as the quadratic mean of
the vertical distances from each point to the curve.

Standard error from a linear regression line @math{y=a+bx} is

@tex
$$ Stderr = \sqrt { (y_1 - (a + bx_1))^2 + \cdots + (y_N - (a + bx_N))^2
                    \over N } $$
@end tex
@ifnottex
@example
               / (y1 - (a+b*x1))^2 + ... + (yN - (a+b*xN))^2 \
Stderr = sqrt |  -------------------------------------------  |
               \                     N                       /
@end example
@end ifnottex

doc/chart.texi  view on Meta::CPAN

For reference, there's no need to actually calculate the linear regression
@math{a} and @math{b}, the stderr can be formed directly as

@tex
$$ Stderr = \sqrt { Variance(Y) - { Covariance(X,Y)^2 \over Variance(X) }} $$
@end tex
@ifnottex
@example
               /               Covariance(X,Y)^2 \
Stderr = sqrt |  Variance(Y) - -----------------  |
               \                  Variance(X)    /
@end example
@end ifnottex

@noindent
where variance and covariance are as follows (and notice they simplify if
@math{X} values are chosen to make @math{Mean(X)} zero),

@tex
$$ \mathop{Covariance} X,Y = \mathop{Mean} (XY)
                             - (\mathop{Mean} X) (\mathop{Mean} Y) $$
$$ \mathop{Variance} X = \mathop{Mean} (X^2) - (\mathop{Mean} X)^2 $$
@end tex
@ifnottex
@example
Covariance X,Y = Mean (X*Y) - (Mean X) * (Mean Y)
Variance X = Mean(X^2) - (Mean X)^2
@end example
@end ifnottex

Standard error from a linear regression like this is used as a channel width
in Kirshenbaum Bands (@pxref{Kirshenbaum Bands}).  It can also be viewed
directly as an indicator, but this is probably of limited use and for that
reason is under ``Low Priority'' in the indicator lists.

@subsection Additional Resources
@itemize
@item
@uref{http://mathworld.wolfram.com/LeastSquaresFitting.html} -- on calculating
stderr without the a,b parameters
@end itemize


@c ---------------------------------------------------------------------------
@node Standard Deviation, True Range, Linear Regression, Common Calculations
@section Standard Deviation
@cindex Standard deviation
@cindex Stddev

Standard deviation (stddev) is a statistical measure of how much the values in
a data set deviate from their average (mean).  The stddev of a past N days is
used in the calculation of Bollinger bands (@pxref{Bollinger Bands}) and VIDYA
and @ref{Variable Index Dynamic Average}).

The raw stddev values can be shown in Chart as an indicator, to see what goes
into those calculations.  The values have little direct use though, and for
that reason stddev is under ``Low Priority'' in the indicator lists.

@cindex Quadratic mean
@cindex Mean, quadratic
For reference, the formula on prices @ms{p,1} to @ms{p,N} is as follows.  Each
@m{p_i-m,p[i]-m} is the distance from the mean @math{m}, and those distances
are averaged with a quadratic mean.

@tex
$$ \sigma = { \sqrt{ { (p_1-m)^2 + (p_2-m)^2 + \cdots + (p_N-m)^2 } \over N }}
$$
@end tex
@ifnottex
@example
               / (p1-m)^2 + (p2-m)^2 + ... + (pN-m)^2 \
Stddev = sqrt (  ------------------------------------  )
               \                   N                  /
@end example
@end ifnottex

where @math{m} is the arithmetic mean

@tex
$$ m = { { p_1 + p_2 + \cdots + p_N } \over N } $$
@end tex
@ifnottex
@example
    p1 + p2 + ... + pN
m = ------------------
            N
@end example
@end ifnottex

Also, for reference, the formula can be rearranged to the following form,
``sum of the squares minus square of the sums''.  This is what Chart uses,
because a new term can be shifted into the sums without recalculating all N
terms.

@tex
$$ \sigma = { \sqrt{ { { p_1^2 + p_2^2 + \dots + p_N^2 } \over N }
            - { \left( { p_1 + p_2 + \dots + p_N } \over N \right)^2 }}}
$$
@end tex
@ifnottex
@example
               / p1^2 + p2^2 + ... + pN^2   (p1 + p2 + ... + pN)^2 \
Stddev = sqrt (  ------------------------ - ----------------------  )
               \            N                         N^2          /
@end example
@end ifnottex


@c ---------------------------------------------------------------------------
@node True Range,  , Standard Deviation, Common Calculations
@section True Range
@cindex True range
@cindex TR

True range is simply the day's trading range (high to low) extended to include
the previous day's close, should that close be above the high or below the
low.

@tex
$$ true\,range = \max(high,prev\,close) - \min(low,prev\,close) $$
@end tex
@ifnottex
@example
true range = max(high, prev close) - min(low, prev close)
@end example
@end ifnottex

The effect is to include any ``gap'' left between yesterday's close and
today's range.  Quite often there's no gap, but when overnight news makes
prices jump it can be desirable in some algorithms to include that distance.

When a stock doesn't have high/low values (some indices for instance), then
just close-to-close changes are used for true range, which may or may not be
particularly useful.

Raw true range values are generally uninteresting, they're merely used in
other indicators.  Wilder's average true range (@pxref{Average True Range})
uses smoothed true range values.  Setting @math{N=0} for the smoothing period
can show the raw true range values if desired.


@c ---------------------------------------------------------------------------
@node Other Indicator Packages, Watchlist, Common Calculations, Top
@chapter Other Indicator Packages
@cindex Other indicator packages
@cindex Indicator packages
@cindex Add-on indicators

The indicators and averages from the following packages can be selected in
Chart under the View Style dialog (@pxref{View Style}).

doc/chart.texi  view on Meta::CPAN

volume                      number or nil
note                        string or nil
@end example

Which fields actually have data depends on the data source.  @code{name} is
the stock or commodity name as a string, or @code{nil} if not available.
Dates and times are in the timezone of the symbol.  @code{note} is a string
with extra notes, such as ex-dividend or limit up, or @code{nil} if no other
notes.

@example
(chart-latest "F" 'volume) @result{} 10492900
@end example
@c SYMBOL: F

@var{scale} (an integer) is how many places to move the decimal point down.
For example if SCALE is 2 then price 1.23 is returned as 123.  This is good
for working in cents when quotes are in dollars, etc.

@code{chart-latest} doesn't download new quotes but just returns existing
data.
@end defun

@c The @var{scale} argument is a power of 10 to apply to prices.  For example if
@c @var{scale} is 2 then a price 2.75 is returned as 275.  This can be useful for
@c instance if you want to work in cents but quotes are in dollars.  The default
@c is 0, for no scaling, giving the usual units of the source.
@c 
@c @var{field} @code{decimals} is how many decimal places Chart is using for
@c prices internally.  Internally prices are kept as an integer with a count of
@c decimals.  Using this value for @var{scale} will ensure an integer return.
@c 
@c @example
@c (chart-latest "BHP.AX" 'name) @result{} "BHP BILLITON LIMITED"
@c @end example
@c @c SYMBOL: BHP.AX

@c  No tp type index generated, this @deftp just gets the formatting style,
@c  and we stick thing-at-point in the concept index.
@deftp {Form} thing-at-point 'chart-symbol
@cindex @code{thing-at-point}
A call @code{(thing-at-point 'chart-symbol)} gives the Chart symbol at point
(@pxref{Buffer Contents, @code{thing-at-point}, Examining Buffer Contents,
elisp, GNU Emacs Lisp Reference Manual}).  Note that you must @code{(require
'chartprog)} before using this, it's not autoloaded.
@end deftp


@section Simple Emacs Spreadsheet
@cindex Simple Emacs Spreadsheet
@cindex SES spreadsheet

@cindex @file{example.ses}
@code{chart-latest} above can be used in SES (@CHARTpxreftop{ses, Simple Emacs
Spreadsheet}) expressions to include prices in a portfolio etc.  See
@file{emacs/example.ses} in the Chart sources for a sample spreadsheet doing
this.

Since @code{chart-latest} doesn't download new data an
@kbd{M-x ses-recalculate-all} just shows existing downloaded quotes
(@pxref{Formulas, @code{ses-recalculate-all}, Cell formulas, ses, SES: Simple
Emacs Spreadsheet}).

@findex @code{chart-ses-refresh}
@kbd{M-x chart-ses-refresh} does a combination @code{ses-recalculate-all} and
download of Chart prices used.  A first recalculate records calls to
@code{chart-latest} for which prices are used in the spreadsheet, they're
downloaded, then a second recalculate applies the new data.  (Further rounds
of download and recalculate are done as necessary if conditionals in
expressions use yet more symbols.)

@c @item
@c @cindex @command{gnuserv}
@c gnuserv, client/server program for Emacs (see @command{man gnuserv}). @*
@c @uref{http://meltin.net/hacks/emacs/}


@c ---------------------------------------------------------------------------
@node Concept Index, Function Index, Emacs, Top
@unnumbered Concept Index
@printindex cp

@c ---------------------------------------------------------------------------
@node Function Index,  , Concept Index, Top
@unnumbered Function and Variable Index
@printindex fn
@bye

@c Local variables:
@c fill-column: 78
@c End:



( run in 0.635 second using v1.01-cache-2.11-cpan-39bf76dae61 )