\input texinfo    @c -*-texinfo-*-
@c %**start of header
@setfilename chart.info
@include version.texi
@settitle Chart Manual
@synindex vr fn
@iftex
@afourpaper
@end iftex
@comment %**end of header

@copying
This manual describes how to install and use Chart, version @value{VERSION}.

Copyright 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2014, 2015, 2016, 2017 Kevin Ryde

Chart is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 3, or (at your option) any later version
(@pxref{Copying}).
@end copying

@dircategory Financial
@direntry
* Chart: (chart).                       Stock and commodity charting.
@end direntry

@c  Usage: @CHARTreftop{info,title}
@c         @CHARTpxreftop{info,title}
@c
@c  Like @ref{} and @pxref{}, but designed for a reference to the top of a
@c  document, not a particular section.
@c
@c  Doesn't come out looking great in html, but mung-html.scm takes care of
@c  that.
@c
@macro CHARTreftop{info,title}
@ref{Top,\title\,\title\,\info\,\title\}
@end macro
@macro CHARTpxreftop{info,title}
@pxref{Top,\title\,\title\,\info\,\title\}
@end macro
@c
@iftex
@unmacro CHARTreftop
@macro CHARTreftop{info,title}
@i{\title\}
@end macro
@unmacro CHARTpxreftop
@macro CHARTpxreftop{info,title}
see @i{\title\}
@end macro
@end iftex

@c  Usage: @CHARTureflong{url, urlsplit}
@c
@c  Give an @uref{} for a long url.  The url is the raw url, and the urlsplit
@c  part is with some line breaks at judicious places.  The split format is
@c  used in formats which don't handle long lines well.
@c
@c  Actually, this doesn't work very well.  If you use a split form for tex
@c  then there's no link in the pdf.  Hmm.
@c
@ifinfo
@macro CHARTureflong{url,urlsplit}
@uref{\url\}
@end macro
@set CHARTureflongdefined
@end ifinfo
@c
@ifhtml
@macro CHARTureflong{url,urlsplit}
@uref{\url\}
@end macro
@set CHARTureflongdefined
@end ifhtml
@c
@iftex
@macro CHARTureflong{url,urlsplit}
@indicateurl{\urlsplit\}
@end macro
@set CHARTureflongdefined
@end iftex
@c
@ifclear CHARTureflongdefined
@alias CHARTureflong=uref
@end ifclear

@c  @cross{} is a \times symbol in tex, or an "x" in info.
@c  In tex it works inside or outside $ $.
@tex
\gdef\cross{\ifmmode\times\else$\times$\fi}
@end tex
@ifnottex
@macro cross
x
@end macro
@end ifnottex

@c  @alph{} is \alpha symbol in tex, or an "alpha" in info.
@c  In tex it works inside or outside $ $.
@tex
\gdef\alph{\ifmmode\alpha\else$\alpha$\fi}
@end tex
@ifnottex
@macro alph
alpha
@end macro
@end ifnottex

@c  @m{T,N} is $T$ in tex or @math{N} otherwise.
@iftex
@macro m {T,N}
@tex$\T\$@end tex
@end macro
@end iftex
@ifnottex
@macro m {T,N}
@math{\N\}
@end macro
@end ifnottex

@c  @ms{V,N} is a subscript $V_N$ in tex or just vn otherwise.
@iftex
@macro ms {V,N}
@tex$\V\_{\N\}$@end tex
@end macro
@end iftex
@ifnottex
@macro ms {V,N}
\V\\N\
@end macro
@end ifnottex

@c  @nicode{S} is plain S in info, or @code{S} elsewhere.  This can be used
@c  when the quotes that @code{} gives in info aren't wanted, but the
@c  fontification in tex or html is wanted.  @alias is used rather than @macro
@c  because backslashes don't work properly in an @macro.
@ifinfo
@alias nicode=asis
@end ifinfo
@ifnotinfo
@alias nicode=code
@end ifnotinfo

@c  @nisamp{S} is plain S in info, or @samp{S} elsewhere.  This can be used
@c  when the quotes that @samp{} gives in info aren't wanted, but the
@c  fontification in tex or html is wanted.  @alias is used rather than @macro
@c  because backslashes don't work properly in an @macro.
@ifinfo
@alias nisamp=asis
@end ifinfo
@ifnotinfo
@alias nisamp=samp
@end ifnotinfo

@c  @iquot{S} is italics in TeX, HTML, etc, or quotes in info.  This is meant
@c  for the names of books etc.
@ifinfo
@macro iquot {S}
``\S\''
@end macro
@end ifinfo
@ifnotinfo
@alias iquot=i
@end ifnotinfo

@c  @CHARTniuref{S} is plain S in info, or @uref{S} elsewhere.  This is when
@c  the quotes that @uref{} gives in info aren't wanted, but the font in TeX
@c  or the link in HTML are wanted.  @alias is used rather than @macro because
@c  backslashes don't work properly in an @macro.
@ifinfo
@alias CHARTniuref=asis
@end ifinfo
@ifnotinfo
@alias CHARTniuref=uref
@end ifnotinfo

@c  @rightarrow{} made available in info too
@ifnottex
@macro rightarrow
->
@end macro
@end ifnottex

@c  @pi{} (TeX \pi) made available in info too
@ifnottex
@macro pi
pi
@end macro
@end ifnottex

@c  @pm{} (TeX \pm) made available in info too
@ifnottex
@macro pm
+/-
@end macro
@end ifnottex

@c  @myimage{filename,alt}
@c
@c  Leave out the "alt" in info mode, since there's an ascii art rendition
@c  from the txt file, which should be enough for a viewer that doesn't
@c  recognise [image].
@c
@c  And leave out "png" from info mode because although it ought to do no
@c  harm, a malloc problem in makeinfo 4.8 is tickled.  (It goes one char over
@c  the malloced size, which means certain sized filenames are affected, and
@c  depending if libc puts any padding.)
@c
@ifinfo
@macro myimage {F,A}
@quotation
@image{\F\}
@end quotation

@end macro
@end ifinfo
@c
@ifnotinfo
@macro myimage {F,A}
@*
@center @image{\F\, 14cm, 7.5cm, \A\, png}
@end macro
@end ifnotinfo


@finalout
@headings double
@setchapternewpage on
@paragraphindent 0

@c  html <meta name=description content="...">
@documentdescription
How to install and use the Chart program, version @value{VERSION}.
@end documentdescription

@ifnottex
@node Top, Introduction, (dir), (dir)
@top Chart
@end ifnottex

@iftex
@titlepage
@title Chart
@subtitle Edition @value{EDITION}
@subtitle @value{UPDATED}
@page
@vskip 0pt plus 1filll
@insertcopying
@end titlepage
@end iftex

@ifnottex
@insertcopying
@sp 1
@end ifnottex

@menu
* Introduction::
* Copying::
* Installing::
* Invocation::
* Symbol Lists::
* Display::
* Annotations::
* Averages::
* Channels and Boxes::
* Indicators::
* Common Calculations::
* Other Indicator Packages::
* Watchlist::
* Intraday::
* Download::
* Data Sources::
* Internationalization::
* Emacs::
* Concept Index::
* Function Index::
@end menu

@c  No contents for html.
@ifnothtml
@contents
@end ifnothtml


@c ---------------------------------------------------------------------------
@node Introduction, Copying, Top, Top
@chapter Introduction
@cindex Introduction

Chart is a stock and commodity price charting program, featuring various
display options, data downloading, and user extensibility.

Chart is written in Perl and uses Gtk through the Gtk2-Perl interface.
Extensions can be written using Perl.  The home page is

@quotation
@uref{http://user42.tuxfamily.org/chart/index.html}
@end quotation

@section Getting Started
@cindex Getting started

Once you've installed Chart (@pxref{Installing}), getting started is easy.
Run @command{chart}, and choose File/Open from the menu bar.  Enter a symbol,
like @samp{GM} (for General Motors USA) and click ``New''.  The download
dialog pops up and gets an initial 5 years data, then the chart is displayed.
@c SYMBOL: GM

The Watchlist is easy too (@pxref{Watchlist}).  Choose Tools/Watchlist from
the menu bar, go to the Symbol box, enter a symbol like @samp{NAB.AX} (for
National Australia Bank) and press @key{Return}.  The symbol is added to the
list and a latest quote downloaded.  Click on ``Refresh'' to update.
@c SYMBOL: NAB.AX

Stock symbols broadly follow Yahoo Finance conventions, which is the exchange
symbol plus a suffix, like @samp{.L} for the London Stock Exchange
(@pxref{Yahoo Finance}).  But Chart is not Yahoo specific, other data sources
have other suffixes.


@c ---------------------------------------------------------------------------
@node Copying, Installing, Introduction, Top
@chapter Copying Conditions
@cindex Copying
@cindex Conditions for copying
@cindex License

@cindex GNU General Public License
@cindex General Public License
@cindex GPL
@cindex @file{COPYING}
Chart is Free Software, published under the terms of the GNU General Public
License (version 3 or later).  The file @file{COPYING} contains the full
license terms (view it under Help/About within the program).

@cindex Distribution
@cindex Redistribution
Chart is not in the public domain.  It's copyrighted and there are
restrictions on its distribution and redistribution, but these restrictions
are designed to permit everything a cooperating person would want to do.

Essentially you can give or sell copies to anyone, with or without
modifications, but you must allow everyone else to do the same and you must
clearly identify any modifications.

@cindex Warranty
Be aware there is no warranty whatsoever for Chart.  This is described in full
in the license terms.  No warranty whatsoever includes no warranty against any
losses or any missed gains as a result of anything Chart does or doesn't do or
show.

@cindex Financial advice
@cindex Investment advice
Note that Chart is only a program for displaying data.  The program and this
manual do not give financial advice.

@section Data Copying
@cindex Copying, data
@cindex Data copying
@cindex License, data

The data that Chart may download or display will be copyright to the creator
of that data and will be provided under terms decided by the creator.  You
must check each data source used to see that you and your intended use are
within the terms (@pxref{Data Sources}).  The minimum for a source in Chart is
that personal non-commercial use is permitted.  Usually no re-distribution is
permitted.

The author believes that the manipulations Chart performs on downloaded data
are purely mechanical and do not cause the program's terms to be added to any
results.  Derived forms like the database files, watchlist quotes, screenshots
of graphs, etc, will be subject only to the conditions of the data originators
(cumulatively if data from more than one source is shown).


@c ---------------------------------------------------------------------------
@node Installing, Invocation, Copying, Top
@chapter Installing
@cindex Installing

@noindent
@cindex Required software
The following programs and libraries are required, see their respective
documentation for installation instructions.

@itemize @bullet
@item
Perl 5.10 or higher
@* @uref{http://www.perl.org}

@item
Gtk 2 libraries, version 2.12 or higher.
@cindex Gtk
@* @uref{http://www.gtk.org}

@item
Gtk2-Perl, version 1.200 or higher.
@cindex Gtk2-Perl
@* @uref{http://gtk2-perl.sourceforge.net}

@item
The large number of Perl modules listed in @file{Makefile.PL}, all of which
are available from CPAN,
@* @uref{http://www.cpan.org}
@end itemize

Chart uses an @code{ExtUtils::MakeMaker} build system.  A basic build and
install can be made as follows.  This will install under @samp{/usr/local}.

@example
perl Makefile.PL
make
make install
@end example

@c @cindex Build options
The usual @code{ExtUtils::MakeMaker} options and build targets are available.
Here are some other notes,

@table @asis
@item Optional Software
Various optional features and their required Perl modules are set out in the
@code{optional_features} section of @file{META.yml}.  Some of the smart Perl
install tools might offer them in an automated way, otherwise look at
@file{META.yml} or @file{Makefile.PL} and install desired things manually.
The most interesting options include @code{Finance::Quote} (@pxref{Finance
Quote}), Genius Trader and TA-Lib (@pxref{Other Indicator Packages}).

@item HTTP Compression
If suitable modules are available then LWP is set to request compression in
HTTP downloads.  Various servers will do this and it saves download size when
the server does.  Gzip is the most common and its decompression uses
@code{IO::Uncompress::Gunzip} which comes with Perl so should be available
always.

@c FIXME: not included yet
@c the only the BSX and ZSE servers are known
@c to take advantage of this (@pxref{Bendigo Stock Exchange}, and @ref{Zagreb
@c Stock Exchange}).

@item HTTPS
@cindex @code{https}
@cindex SSL
@cindex OpenSSL
For @code{https} protocol the @code{LWP::Protocol::https} module is required.
In libwww 6 and up it comes separately and expresses its required supporting
modules.  In libwww 5 see its @file{README.SSL} on the recommended
@code{Crypt::SSLeay} module (using OpenSSL)@.  Many data sources need
@code{https}, including @ref{Yahoo Finance}.

@c @item @command{lha}
@c @cindex LHa
@c @cindex LZH
@c The LHa archive program (@pxref{References}) is required for data sources in
@c LZH format (@pxref{Kansai Commodities Exchange, KEX}).
@c 

@item Documentation
@cindex Documentation
@cindex Manual
@cindex Texinfo manual
@cindex @TeX{} manual
The source for the manual you're now reading is @file{doc/chart.texi}, in
Texinfo format (@CHARTpxreftop{texinfo, Texinfo}).

@cindex HTML manual
@cindex Info manual
@cindex PostScript manual
@cindex PDF manual
@cindex DVI manual
HTML format @file{chart.html} is installed as
@file{lib/App/Chart/doc/chart.html} with the source code.  It can be viewed
with the Help commands within Chart, or with any browser.  The following
@command{make} targets can build other formats,

@example
make info      # Info
make dvi       # TeX DVI
make ps        # PostScript
make pdf       # PDF
@end example

producing files @file{doc/chart.info}, @file{doc/chart.dvi}, etc.  They need
enough of Chart's Perl dependencies installed to run the @file{doc/weights.pl}
script, then Info requires @command{makeinfo} (@pxref{Creating an Info File,,,
texinfo, Texinfo}) and DVI, PS and PDF require various @TeX{} and Texinfo
tools.  PDF also requires either @command{epstopdf} from Texlive or TeTeX, or
@command{ps2pdf} from Ghostscript.
@cindex DocBook manual
@cindex XML manual
@command{makeinfo} can produce other formats, including DocBook and XML
(@pxref{makeinfo options,, Options for @command{makeinfo}, texinfo, Texinfo}).

@item Scrollkeeper
@cindex OMF
@cindex Open metadata framework
@cindex Scrollkeeper
@cindex Yelp
@cindex @command{gnome-help}
A Scrollkeeper entry
(@uref{http://scrollkeeper.sourceforge.net}) @file{doc/chart.omf} is included
for the manual (HTML form).  It can be used by Gnome help (Yelp) and similar
programs.  Currently it's not automatically installed but you can copy to
@file{/usr/share/omf/chart/chart.omf} and run @command{scrollkeeper-update}.

@item User Directory
@cindex User directory
@cindex @env{CHART_DIRECTORY}
The default directory for Chart downloaded data and configurations is
@file{~/Chart}, ie.@: a @file{Chart} subdirectory of the user's home
directory.  The @env{CHART_DIRECTORY} environment variable can be set to a
different directory if something else is preferred, or perhaps to experiment
or keep some things separate.

@end table


@c ---------------------------------------------------------------------------
@node Invocation, Symbol Lists, Installing, Top
@chapter Invocation
@cindex Invocation
@cindex Command line
@cindex Options
@cindex @command{chart}

@noindent
The Chart command line is

@example
chart [--options] [symbol@dots{}]
@end example

The default is to run the Gtk graphical interface.  The optional @var{symbol}
is an initial symbol to display.

@var{symbol} can be a partial name and is matched against the database the
same way as in the Open dialog (@pxref{Open}).  So if @code{TSCO.L} is the
only thing in the database starting with ``TS'' then just @samp{chart ts} is
enough, or similarly for @code{^GSPC} just @samp{chart gsp} may be enough.

The graphical options are

@table @asis
@item @option{--display=@var{dpy}}
@cindex @option{--display}
@cindex @env{DISPLAY}
Start on the given display @var{dpy}.  The default is the usual @env{DISPLAY}
environment variable, which should be set as part of X startup, and shouldn't
need to be overridden.  See @command{man X} for more.

@item @option{--watchlist}
@cindex @option{--watchlist}
@cindex Ticker, stand alone
Start with just the Watchlist dialog (@pxref{Watchlist}).  The initial list
displayed is selected by the symbol options like @samp{--all} below.

@example
chart --watchlist --all
@end example

A full main chart window can be opened from a symbol by double-clicking or
choosing ``Chart'' from the Button-3 menu in the usual way.

@item @option{--ticker}
@cindex @option{--ticker}
@cindex Ticker, stand alone
Instead of running the full GUI, show just the stock ticker (@pxref{Ticker}).
The symbol options below select the symbols displayed.  The default is the
favourites list.  For example,

@example
chart --ticker --alerts
@end example
@end table

@cindex Gtk options
@option{--display} is a standard Gtk option, other standard Gtk options are
accepted too, but there's none that do much for Chart.  See @command{man 7
gtk-options} for a full list.

@section Symbol Options

The following options select one or more symbol lists or symbols for
@option{--watchlist} and @option{--ticker} above, and for the command line
@option{--download} below.  The options are cumulative, so you can have a
combination like

@example
chart --alerts --favourites '*.AX'
@end example

For the symbols in those lists plus all @samp{.AX} symbols.  (In the ticker a
combination like that updates if the list contents or available @samp{.AX}
symbols changes.)

@table @asis
@item @option{--all}
@cindex @option{--all}
The ``All'' list of all current symbols in the database, meaning everything
except the historical list.

@item @option{--alerts}
@cindex @option{--alerts}
The ``Alerts'' list of all symbols currently outside their alert levels.

@item @option{--favourites}
@cindex @option{--favourites}
The ``Favourites'' list.
downloaded.

@item @option{symbol@dots{}}
The given explicit symbols.

@item @option{*.*}
Shell style wildcards @samp{*} and @samp{?} can be used to match existing
database symbols.  @samp{*} matches any sequence of characters, @samp{?}
matches any single character.  For example to update all Australian shares

@example
chart --download '*.AX'
@end example

The quotes @nisamp{' '} are only to stop the @samp{*} being interpreted by the
shell (@pxref{Quoting,,, bashref, Bash Features}).
@end table

@section Download
@cindex Download, non-graphical
@cindex @option{--download}
@cindex @command{cron}
Chart can do its data downloading from the command line.  Error messages are
printed to the standard output and a progress status line is shown if it's a
terminal.  This is good for a @command{cron} job or other automated update.
The usual way to update everything is

@example
chart --download --all
@end example

The symbol options above select what to display.  Explicitly named symbols are
added to the database if not already present, and are raised out of
``historical'' status if there's some new data.

For @option{--favourites} only symbols from it already in the database are
downloaded.  Other symbols there are assumed to wanted for the watchlist, but
not downloaded.

@c @item @option{--backto @var{year}}
@c @cindex @option{--backto}
@c Instead of downloading updates, download back to the given @var{year}
@c (eg.@: 1995) for each selected symbol.  Various data sources only have limited
@c past data, this option does the best it can.

@section Other
@noindent
Other options are

@table @asis
@item @option{--version}
@cindex @option{--version}
@cindex Version
Print the program version, and exit.

@item @option{--help}
@cindex @option{--help}
@cindex Help
Print a summary of the command line options, and exit.
@end table

@cindex Bash
@cindex GNU Bash
@cindex Completion, command line
@cindex @file{chart.bash}
@section Bash

Chart has some support for the GNU Bash command line completion feature
(@pxref{Commands For Completion,, Letting Readline Type For You, bashref, Bash
Features}).

The @file{chart.bash} script lets you hit @key{Tab} etc to complete symbols
entered on the command line.  For example type @samp{chart --download bh}
@key{Tab} could complete to @samp{BHP.AX}.  It uses the @command{sqlite3}
command-line program to access the Chart database.  Command options are
completed too, so @samp{chart --do} @key{Tab} gives @samp{--download}.

@cindex @code{bash_completion}
To load this, source the file from your @file{.bashrc} (@pxref{Bash Startup
Files,,, bashref, Bash Features}),

@example
. chart.bash
@end example

See comments in @file{chart.bash} for more, including use with the
@code{bash_completion} project
(@uref{http://www.caliban.org/bash/index.shtml#completion}).


@c ---------------------------------------------------------------------------
@node Symbol Lists, Display, Invocation, Top
@chapter Symbol Lists
@cindex Symbol Lists

There are four builtin symbol lists in Chart, and you can create user defined
lists from the Watchlist dialog (@pxref{Watchlist}).

@section Favourites List
@cindex Favourites list

The favourites list is the default shown in the watchlist and is intended for
symbols which you're interested in at the moment.  Symbols don't have to be in
the database, they can be in the list just to see quotes in the watchlist.

@cindex @key{!}
@cindex @key{Control-!}
Symbols can be added or removed using the watchlist dialog, and from the main
window (@pxref{Main Window}) when viewing a chart using the File menu entries
(accelerators @key{!} and @key{Control-!}).  Entries can be moved around from
the watchlist too.

@section Alerts List
@cindex Alerts list

The alerts list is symbols which have gone above or below alert level
annotations which you set (@pxref{Annotations}).  This changes with the latest
quotes or database prices available.  If you change an alert level then the
symbol is added or removed accordingly too.

@section Historical List
@cindex Historical list

When a stock has been delisted or a futures contract has expired, the symbol
is put into the historical list.  The current rule is to go when there's no
new data for 3 weeks, or 3 weeks after a known contract expiry date.

``No new data'' doesn't merely mean no trades, it means no new information at
all from the data source for that time.  Current data sources don't give
direct indications of stocks that have been delisted, the rule here is
designed to pick them up but not catch stocks merely suspended for a period.

@cindex @key{Ctrl-U}
The historical list cannot be directly edited, but if a stock is re-listed you
can lift it out of historical status by explicitly downloading.  (Do a
@key{Ctrl-U} update, or ask for that symbol in the download dialog,
@pxref{Download}.)

@section All List
@cindex All list

The all list is all symbols in the database, except those in the historical
list described above.


@c ---------------------------------------------------------------------------
@node Display, Annotations, Symbol Lists, Top
@chapter Display
@cindex Display

@menu
* Open::
* Main Window::
* View Style::
* Dividends::
* Cross::
* Ticker::
@end menu


@c ---------------------------------------------------------------------------
@node Open, Main Window, Display, Display
@section Open
@cindex Open
@cindex Dialog, open
@cindex Select chart

@cindex File/Open
The File/Open dialog selects a symbol to display.  Click on an entry in the
tree, or type in a symbol.  Upper or lower case can be entered, and just some
of the symbol is enough.  The tree selection jumps to show what's matched.
There's no need to give a suffix, unless two symbols are the same apart from
the suffix.

@cindex @key{N}
@cindex @key{P}
The tree shows the various symbol lists (@pxref{Symbol Lists}), but for the
favourites list only symbols actually in the database.  Clicking on an entry
makes that list current, so @key{N} and @key{P} then navigate within that.
Initially the start of the tree is current, so @key{N} starts in the first
list.

To add a new symbol, enter it and click ``New'' (@key{Alt-N}).  In this case
you must have upper/lower case and the suffix correct.  There's no validation
for that, you just have to be careful.  An initial download is done and the
chart is displayed.

When adding a lot of new symbols the command line download
(@pxref{Invocation}) may be easier than entering them individually in the GUI.
You can give a long list and let Chart go away and do all the initial
downloads.  (The command is the same as an ``update'', because an update of a
stock with no data means do an initial download.)  For example,

@example
chart --download TSCO.L RNO.PA TEL.NZ BMW.DE
@end example
@c SYMBOL: TSCO.L
@c SYMBOL: RNO.PA
@c SYMBOL: TEL.NZ
@c SYMBOL: BMW.DE

The TreeView in the dialog has an irritating animated arrow when expanding or
collapsing a symlist.  You can fix that for Chart and other Gtk2 by adding to
your @file{~/.gtkrc-2.0} file

@example
gtk-enable-animations = 0
@end example


@c ---------------------------------------------------------------------------
@node Main Window, View Style, Open, Display
@section Main Window
@cindex Main window
@cindex Window, main
@cindex Graph

@cindex OHLC
@cindex Weekly
@cindex Monthly
@cindex @key{Ctrl-D}
@cindex @key{Ctrl-W}
@cindex @key{Ctrl-M}
The default display is daily open/high/low/close candlesticks with volume
below.  @key{Ctrl-W} selects a weekly display, or @key{Ctrl-M} monthly.
@key{Ctrl-D} goes back to daily.

@cindex Scroll
@cindex Centre
@cindex @key{Page-Up}
@cindex @key{Page-Down}
@cindex @key{Ctrl-C}
@cindex @key{Button-1}
The scroll bars move the visible portion.  Arrow keys @key{Up}, @key{Down},
etc move by a step, or control-arrows and @key{Page-Up}/@key{Page-Down} move
by a page.  Mouse @key{Button-1} drags the graph within the window.
@key{Ctrl-C} centres it vertically in the window, if you lose track when
paging around.

@cindex Zoom
@cindex @key{Z}
@cindex @key{Shift-Z}
@cindex @key{W}
@cindex @key{Shift-W}
@key{Z} and @key{Shift-Z} zoom in and out vertically.  @key{W} and
@key{Shift-W} zoom in and out horizontally (@samp{W} stands for ``wider'').
The initial vertical scaling is based on apparent price volatility, so active
stocks take the full window (or more), and sedate stocks are shown fairly
flat.

@cindex Latest
During trading, the current day's open/high/low/last so far is shown in yellow
(to emphasise it's a latest quote).  This is always in OHLC style, even on a
candlestick chart.  The figure drawn looks like

@ifnottex
@example
  |
  |
  +--
  |
  +-----
  |
  +--
  |
--+
  |
  |
@end example
@end ifnottex
@tex
{\hfill
\vbox to 12 ex{%
  \vskip 8.5 ex
  \hrule width 1.5 ex height 1 ex
  \vfill
}\vbox to 12 ex {%
  \hbox{\vrule width 1 ex height 12 ex}
  \vfill
}\vbox to 12 ex {%
  \vskip 2 ex
  \hrule width 1.5 ex height 1 ex
  \vskip 1.5 ex
  \hrule width 3.5 ex height 1 ex
  \vskip 1.5 ex
  \hrule width 1.5 ex height 1 ex
  \vfill
}\hfill}
@end tex

The left line is the open as usual.  The long line on the right is the last
trade, and the surrounding shorter lines are the current bid and offer.  The
last trade might be equal to the bid or offer, overlapping it, or they might
surround the last, as shown here.  In any case this figure gives the current
day visually.


@c ---------------------------------------------------------------------------
@node View Style, Dividends, Main Window, Display
@section View Style
@cindex Style
@cindex View style
@cindex Dialog, view style

@cindex Edit/Viewstyle
@cindex OHLC
@cindex Candles
@cindex Line style
@cindex HL, line style
@cindex Solid, line style
@cindex Splits, adjustment
@cindex Stock splits, adjustment
@cindex Dividends, adjustment
@cindex Futures, rollover
@cindex Rollover
@cindex Indicator
The Edit/Viewstyle dialog has options for the line style (OHLC, candles, etc),
whether to adjust for stock splits (default yes), dividends (default no), and
futures rollovers (default yes), and selections to enable various indicators.

Candlestick figures are shown in green for close above the open, or red for
close below the open.  This is instead of traditional hollow and solid,
because hollow is hard to see when zoomed out to fit maximum data on the
screen.  If there's no opening prices, candlesticks fallback to OHLC figures
(just high/low and close).  If there's no high/low either, then candlesticks,
OHLC and HL styles all fall back to a plain line.

@cindex Indicator
@cindex Average
Various averages (@pxref{Averages}) or channels (@pxref{Channels and
Boxes}) can be applied in the main window, and an indicator
(@pxref{Indicators}) and an average (on it) in the lower window.  The
indicators have various parameters, like smoothing periods.  For some closely
related indicators the parameters are shared (eg.@: ADX and DMI), but most are
independent for ease of tuning.  The ``Info'' button at the right opens this
manual at the selected indicator's description.

@cindex @key{Shift-Button-3}
@key{Shift-Button-3} (ie. mouse @key{Button-3} while the @key{Shift} key is
held down) pops up a quick menu to change the indicator.  On a two-button
mouse @key{Button-3} is usually the right button.  The menu has a tearoff to
keep it open for quick selection too.  But parameter values can only be set
from the Edit/Viewstyle dialog.

There's just one global view style, applied to all charts viewed.


@c ---------------------------------------------------------------------------
@node Dividends, Cross, View Style, Display
@section Dividends and Splits
@cindex Dividends
@cindex Splits

Dividends and stock splits are shown across the top of the chart at ex dates.
Both are part of normal data downloading, but may not be available for all
exchanges or all stocks, and might have only recent or upcoming dividends (not
historical dividends).

@c FIXME
@c Prices drawn in the graphs are adjusted for splits, bringing past prices to
@c the same capital basis as current prices.  Dividends can be adjusted
@c similarly, possibly with imputation credits (Australia and New Zealand)
@c included.
@c These adjustments are controlled from the Edit/Viewstyle dialog
@c (@pxref{View Style}).
@c 
@c Dividend adjustments are made using a multiplier factor based on the dividend
@c amount and the last close before going ex-dividend.  This is like a ``dividend
@c reinvestment'' plan or an accumulation style share index.
@c 
@c @cindex Rollover
@c @cindex Futures, rollover
@c For ``front month'' futures symbols (the commodity alone like
@c @samp{GC.CMX}), the rollover to each new contract is recorded in the
@c dividends.  Normally the next contract is a higher price (representing a cost
@c of carry) and the extra amount is treated like a kind of reverse dividend, an
@c extra amount to pay to keep a long position.  With rollover adjustment (the
@c default) the front month is therefore as if reinvesting in the next month on
@c each expiry day.
@c @c SYMBOL: GC.CMX
@c 
@c @cindex Dialog, dividends
@c @cindex Edit/Dividends
@c The Edit/Dividends menu entry opens the dividends dialog to manually add or
@c amend entries, or just to see the full list.  Be warned that the data download
@c will consider it knows best and will overwrite an entry it has information
@c about.  Annotations should be used for a personal reminder etc
@c (@pxref{Annotations}).  Currently there's nothing specific for capital
@c returns, the suggestion is to enter them manually as dividends (no data
@c sources get this information automatically).
@c 
@c Dividend amounts can be recorded as free-form strings and certain special
@c cases like ``to be advised'' instead of numbers.  Splits are always recorded
@c as numbers.  When editing, the forms like the following are generated and
@c recognised,
@c 
@c @example
@c unknown
@c to-be-advised
@c 12.5
@c estimated 12.5
@c split 5 for 4
@c month: Jan 2007
@c @end example
@c 
@c The words here like @samp{to-be-advised} are in the selected language where
@c possible (@pxref{Internationalization}), but for ease of use are always
@c recognised in English too.


@c ---------------------------------------------------------------------------
@node Cross, Ticker, Dividends, Display
@section Cross
@cindex Cross

The cross is an orange horizontal and vertical line drawn following the mouse.
It's designed to help show relative price levels, or to see down to the time
scale.  The date and price are shown in the status area at the bottom too.

@cindex @key{C}
@cindex @key{Button-3}
@cindex Tools/Cross
The cross can be toggled with the @key{C} key, or from the Tools/Cross menu
entry.  It can also be enabled just temporarily by pressing and holding mouse
@key{Button-3}.  On a 2-button mouse @key{Button-3} is usually the right
button.

There's a cross in the intraday graphs similarly (@pxref{Intraday}).


@c ---------------------------------------------------------------------------
@node Ticker,  , Cross, Display
@section Ticker
@cindex Ticker

The ticker scrolls prices along a line at the bottom of the screen, refreshed
periodically.  It's selected in the main window from the Tools/Ticker menu, or
can be run standalone with the @option{--ticker} command line option
(@pxref{Invocation}).

Mouse @key{Button-1} drags the text back and forward if you miss something or
want to hurry it up.  @key{Button-3} pops up a menu to pause, force a refresh,
or close it.  On a 2-button mouse @key{Button-3} is usually the right button.
Prices are automatically refreshed every 5 minutes while running and visible.

The default is to show the favourites list (@pxref{Symbol Lists}), but that
can be changed from the menu.  When standalone a symbol list or specified
symbols can be given on the command line.  For example to see everything in
the database

@example
chart --ticker --all
@end example


@c ---------------------------------------------------------------------------
@node Annotations, Averages, Display, Top
@chapter Annotations
@cindex Annotations

Annotations can be added to a chart, in the form of notes for particular days,
and lines drawn on the chart.

@section Notes
@cindex Notes
@cindex Text notes

@cindex Dialog, annotations
@cindex Edit/Annotations
Text notes are added with the Edit/Annotations dialog.  These are free-form
and can be used as personal reminders about particular events.  (Usually they
should be just a couple of words, as currently the drawing doesn't do a good
job with long text.)

@section Lines
@cindex Lines
@cindex Trend lines
@cindex Edit lines

Lines can be drawn on a chart as personal reminders of apparent trends or
support/resistance etc.  Lines can be drawn anywhere desired, and are stored
using date and price so they scale with the display.

@cindex @key{Button-2}
To draw a line press and hold mouse @key{Button-2} at the starting point, and
drag to the end.  On a two-button mouse @key{Button-2} usually means pressing
both buttons at the same time.

@cindex @key{H}
@cindex @key{Escape}
@cindex @key{D}
While drawing, press @key{H} to toggle between a sloping line (the default)
and a horizontal line.  Press the spacebar to swap to move the opposite end of
the line.  An existing line can be repositioned by pressing and dragging
@key{Button-2} near an endpoint.  Press @key{Escape} to abort an edit.  To
delete a line press @key{D} while dragging it.

@section Alert Levels
@cindex Alert levels
@cindex Alert list
@cindex Edit alert levels

Alert levels can be set if you want to know when a stock trades (or has a
bid/offer) above or below some price.  Symbols which have gone past an alert
level are put into the Alerts list.

@cindex @key{A}
Alert levels are edited like lines above.  While editing, press @key{A} to
switch to an alert, and then @key{A} again to toggle between an alert above
(the default) or below the level.  An above alert is drawn like

@example
          |
          |
----------+
@end example

@noindent
and below like
 
@example
----------+
          |
          |
@end example

Basically the little up or down tag at the right hand end points the direction
it will be interested in (ie.@: above or below).


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

When an indicator or average is based on a some number of past days, only
trading days are counted, so for instance 10 days is 2 weeks.  Days with no
trading (public holiday, trading halt, etc) are skipped too.

At the start of data, either the initial listing, or just the start of what's
been downloaded, generally a shortened period of averaging is applied, so
there's an average immediately shown, though it may not be based on less than
the desired period until N dayes, etc.

Of the following averages, the simple moving average and exponential moving
average are the best known.

@menu
* Simple Moving Average::
* Exponential Moving Average::
* Weighted Moving Average::
* Double and Triple Exponential Moving Average::
* Endpoint Moving Average::
* Fractal Adaptive Moving Average::
* Guppy Multiple Moving Average::
* Hull Moving Average::
* Kaufman Adaptive Moving Average::
* Laguerre Filter::
* Median-Average Adaptive Filter::
* Moving Median::
* Regularized Exponential Moving Average::
* Sine Weighted Moving Average::
* T3 Moving Average::
* 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
             - WMA(N) ) $$
@end tex
@ifnottex
@example
HMA = WMA[floor(sqrt(N))] of (2 * WMA[floor(N/2)] - WMA[N])
@end example
@end ifnottex

The average is weighted towards recent prices, and in fact has negative
weights for prices past about @math{N/2} days ago.  Those negatives can make
the average overshoot actual price action after a big jump (the same as other
lag-reduced averages do).  The following graph shows the weights for
@math{N=15}.

@myimage{chart-hull-weights, Hull moving average weights graph}


@c ---------------------------------------------------------------------------
@node Kaufman Adaptive Moving Average, Laguerre Filter, Hull Moving Average, Averages
@section Kaufman Adaptive Moving Average
@cindex Kaufman adaptive moving average
@cindex KAMA
@cindex Average, Kaufman adaptive
@cindex Moving average, Kaufman adaptive

@cindex Kaufman, Perry J.
The Kaufman adaptive moving average (KAMA) by Perry J.@: Kaufman
(@uref{http://www.perrykaufman.com}) is an exponential style average
(@pxref{Exponential Moving Average}) but with a smoothing that varies
according to recent data.  In a steadily progressing move the latest prices
are tracked closely, but when going back and forward with little direction the
latest prices are given only small weights.

The smoothing factor is determined from a given past N days closes (default
10).  The net change (up or down) over that time is expressed as a fraction of
the total daily changes (up and down).  This is called the ``efficiency
ratio''.  If every day goes in the same direction then the two amounts are the
same and the ratio is 1.  But in the usual case where prices backtrack to some
extent then the net will be smaller than the total.  The ratio is 0 if no net
change at all.

@tex
$$ ER = { | close_{today} - close_{Ndays\,ago} |
          \over \sum_{past\,Ndays} | close - close_{prev} | } $$
@end tex
@ifnottex
@example
     abs (close[today] - close[N days ago])
ER = --------------------------------------
         Sum     abs (close - close[prev])
      past N days
@end example
@end ifnottex

The ER is rescaled to between 0.0645 and 0.666 and then squared to give an
alpha factor for the EMA of between 0.444 and 0.00416.  This corresponds to
EMA periods from a fast 3.5 days to a very slow 479.5 days.

@tex
$$ \alpha = (ER \times 0.6015 + 0.0645)^2 $$
@end tex
@ifnottex
@example
alpha = (ER * 0.6015 + 0.0645) ^ 2
@end example
@end ifnottex

An exponential moving average of prices is then taken, using each alpha value
calculated.

@tex
$$ KAMA = \alpha \times close + (1-\alpha) \times KAMA_{prev} $$
@end tex
@ifnottex
@example
KAMA = alpha * close + (1-alpha) * KAMA[prev]
@end example
@end ifnottex

These alpha values can be viewed directly with ``KAMA alpha'' in the lower
indicator window (a low priority option, near the end of the lists).  High
values show where KAMA is tracking recent prices closely, low values show
where it's responding only slowly.


@subsection Additional Resources
@itemize
@item
@uref{http://www.traders.com/Documentation/FEEDbk_docs/Archive/0398/TradersTips/Tips9803.html}
-- TASC Trader's Tips March 1998 with various code.
@item
@uref{http://www.tssupport.com/support/base/?action=article&id=1769} -- short
tradestation article and EFS code.
@end itemize


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

@uref{http://www.mesasoftware.com/technicalpapers.htm} @*
@uref{http://www.mesasoftware.com/Papers/TIME%20WARP.pdf}

@cindex Ehlers, John
The Laguerre Filter by John Elhers is a smoothing filter based on Laguerre
polynomials.  Its first term is an EMA (@pxref{Exponential Moving Average}),
followed by certain feedback terms.  The smoothing is controlled by an @alph{}
factor which is the alpha for the EMA and also damps the further terms.  Alpha
can range from 1 to follow prices almost exactly, down to 0 for a very slow
response.

The result is still a weighted average of past prices.  The weights for
example for the default @math{@alph{}=0.2} are as follows.

@myimage{chart-laguerre-weights, Laguerre Filter weights graph}

@cindex Adaptive laguerre filter
@anchor{Adaptive Laguerre Filter}
@section Adaptive Laguerre Filter

The adaptive laguerre filter is a variation on the laguerre filter using a
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.

@myimage{chart-tma-weights, Triangular weights graph}

It's interesting to note TMA is equivalent to a twice-smoothed simple moving
average of half period (@pxref{Simple Moving Average}).

@tex
$$     TMA(N) = SMA \left( \left\lfloor {N\over2} \right\rfloor + 1 \right)
   \;\; of \;\; SMA \left( \left\lceil N\over2 \right\rceil \right)
$$
@end tex
@ifnottex
@example
TMA[N] = SMA[floor(N/2)+1] of SMA[ceil(N/2)]
@end example
@end ifnottex

In Chart TMA is under ``Low Priority'' in the indicator lists.


@c ---------------------------------------------------------------------------
@node Variable Index Dynamic Average, Volume Weighted Moving Average, Triangular Moving Average, Averages
@section Variable Index Dynamic Average
@cindex Variable index dynamic average
@cindex VIDYA
@cindex Average, variable index dynamic
@cindex Moving average, variable index dynamic

@cindex Chande, Tushar
@cindex Kroll, Stanley
The variable index dynamic average (VIDYA) by Tushar Chande and Stanley Kroll
(in their book @iquot{The New Technical Trader}, 1984) is an exponential style
moving average (@pxref{Exponential Moving Average}) with a smoothing that
varies according to recent price volatility.

A volatility measure is obtained by taking the standard deviation (stddev,
@pxref{Standard Deviation}) of the past 9 days closing prices, expressed as a
fraction of a longer stddev of 30 days.  A scaling factor of 0.2 produces an
alpha usually in the range of about 0.3 to 0.1, corresponding to EMA periods
of about 5 to 20 days.

@tex
$$ \alpha = 0.2 \times { stddev_{short}\;of\;closing\;prices
                         \over stddev_{long}\;of\;closing\;prices } $$
@end tex
@ifnottex
@example
              stddev[short] of closing prices
alpha = 0.2 * -------------------------------
              stddev[long] of closing prices
@end example
@end ifnottex

An exponential moving average of prices is then formed in the usual way, with
each day's alpha.

@tex
$$ VIDYA = \alpha \times close + (1-\alpha) \times VIDYA_{prev} $$
@end tex
@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.

The top of a box is formed when the high of day 1 is not penetrated on the
immediately following day 2 and day 3.  The bottom of the box is established
similarly when a low is not penetrated on two subsequent days.  The first
candidate low is the low of day 3, and the search for a low can extend
indefinitely.  If the box top is penetrated while looking for the low then the
box is abandoned.

Boxes in Chart are drawn without sides, only top and bottom, so as not to
obscure the price plot.  The starting point for box finding is the start of
all data in the database, which attempts to make the results consistent,
though it's still not deterministic in the worst case, since it's never
certain there can't be a huge enclosing box back in past data.


@c ---------------------------------------------------------------------------
@node Donchian Channel, Ichimoku Kinko Hyo, Darvas Boxes, Channels and Boxes
@section Donchian Channel
@cindex Donchian channel
@cindex Channel, Donchian

@cindex Donchian, Richard
The Donchian Channel by Richard Donchian is a simple band system showing an
N-day highest high, N-day lowest low, and a midpoint line between them.

The N days start from yesterday, so a day which is a new N-day high or N-day
low will break out of the channel.  This is taken as a bullish or bearish
signal (respectively).

@subsection Additional Resources
@itemize
@item
@uref{http://www.linnsoft.com/tour/techind/donch.htm} -- sample graph of Intel
(symbol @samp{INTC}) from July-September 2001 (year not marked, but is 2001).
@end itemize


@c ---------------------------------------------------------------------------
@node Ichimoku Kinko Hyo, Keltner Channel, Donchian Channel, Channels and Boxes
@section Ichimoku Kinko Hyo
@cindex Ichimoku kinko hyo

@cindex Ichimoku Sanjin
@cindex Sanjin, Ichimoku
@cindex Hosoda, Goichi
Ichimoku kinko hyo by journalist Goichi Hosoda (writing under the pseudonym
``Ichimoku Sanjin'' the 1930s) is a set of indicator lines designed to show
the overall state of the market.  The name in Japanese means roughly ``chart
equilibrium at a glance''.

@table @asis
@item Tenkan (orange) and Kijun (red)
The tenkan line shown in orange is the midpoint of the past 9-day trading
range, and the kijun line shown in red is a similar midpoint but of a slower
26 day period.  A crossing of the tenkan up through the kijun is taken as a
bullish signal, or conversely a downwards crossing is bearish.  This is
similar to fast/slow moving average crossing systems, but using range
midpoints.

@item Senkou cloud (green)
A senkou or ``cloud'' region is shown between green lines.  One line is the
average (the mean) of the tenkan and kijun, the other is the midpoint of the
52 day trading range.  But these lines are drawn 26-days ahead, and thus
extend out past the end of the latest data.  The idea is that the present
values of those are predicted to have a future influence.

The cloud adds to the bullishness or bearishness of the tenkan/kijun
crossovers.  A bullish cross while above the cloud is a strong buy signal,
whereas within the cloud it's only a normal buy, or below the cloud a weak
buy.  Conversely a bearish cross is a strong sell if below the cloud, normal
within, or weak if above.  The cloud region beyond current data is also
interpreted as prospective future support/resistance.

@item Chikou (blue)
The chikou line drawn in blue is closing prices shifted back 26 days.  It's
interpreted relative to those past prices, with chikou above being bullish or
below being bearish.  This is similar to the kind of comparison momentum makes
(@pxref{Momentum and Rate of Change}).
@end table

The time periods of 9 days and 26 days are parameters in Chart (@pxref{View
Style}).  When Hosoda designed the system Japanese markets traded 6 days a
week, so 9 days was @m{1 1\over2,1 1/2} trading weeks and 26 days was a month.
The same calendar times in today's 5 day weeks can be had with 7 and 22 days.

@cindex Range Midpoint
@anchor{Range Midpoint}
@subsection Range Midpoint

An N-day range midpoint like the tenkan, kijun and cloud lines is also
available separately as ``Range Midpoint'' if you want to experiment.  It's
under ``Low Priority'' in the averages list.


@c ---------------------------------------------------------------------------
@node Keltner Channel, Kirshenbaum Bands, Ichimoku Kinko Hyo, Channels and Boxes
@section Keltner Channel
@cindex Keltner channel
@cindex Channel, Keltner

@cindex Keltner, Chester W.
The Keltner channel is an N-day simple moving average (@pxref{Simple Moving
Average}) of ``typical price'' (which is (high+low+close)/3), and bands drawn
above and below that at a distance which is the simple moving average of daily
ranges (high to low) in the period.

@cindex Ten-day moving average trading rule
This indicator was described by Chester W. Keltner in his 1960 book @iquot{How
To Make Money in Commodities}, and those who learnt of it from him apparently
gave it the name Keltner Channel.  Keltner himself called it the ``Ten-Day
Moving Average Trading Rule'' and never claimed any originality for the idea
-- it may have come from grain traders in the 1930s, or even earlier.

The idea is that closes outside the channel suggest strong bullish (or strong
bearish) sentiment and can be bought (or sold).  The 10-day period is a
parameter in Chart.

The channel bands need daily high/low data, so when that's not available (a
few indexes for instance) they can't be drawn.  The centre line is still shown
(it ends up as just a simple moving average of the closes).


@c ---------------------------------------------------------------------------
@node Kirshenbaum Bands, Parabolic SAR, Keltner Channel, Channels and Boxes
@section Kirshenbaum Bands
@cindex Kirshenbaum bands
@cindex Average
@cindex Moving average
@cindex Variance
@cindex Deviation
@cindex Standard error

@cindex Kirshenbaum, Paul
Kirshenbaum bands are channel lines drawn around an exponential moving average
(@pxref{Exponential Moving Average}).  The channel width is a multiple of the
``standard error'' from a linear regression of a past N days (@pxref{Linear
Regression}, and the EMA is smoothed using the same N days.

Kirshenbaum bands are similar to Bollinger bands (@pxref{Bollinger Bands}),
but with a linear regression standard error (stderr) instead of a standard
deviation (stddev, @pxref{Standard Deviation}).  The difference is that stddev
takes no account of a trend, so the Bollinger channel widens when a trend is
in progress.  But stderr is based on deviation from a fitted sloping line, so
if prices are making steady progress up or down the channel width remains
small.

The standard error values (ie.@: the channel width) can be viewed directly as
an indicator too as ``Linear Regression Stderr'' (@pxref{Linear Regression}).


@c ---------------------------------------------------------------------------
@node Parabolic SAR,  , Kirshenbaum Bands, Channels and Boxes
@section Parabolic SAR
@cindex Parabolic SAR
@cindex Stop and reverse, parabolic

@cindex Wilder, J. Welles
Parabolic stop and reverse (SAR) by J.@: Welles Wilder is a trend following
system which establishes a trailing stop that's progressively advanced as a
price move continues.  If penetrated then one's position short or long is
reversed and a new stop established for the move in the opposite direction.

The stop is calculated as follows.  For an upward move, the initial SAR is the
lowest low made in the preceding down movement.  From there an extreme high of
the current move is maintained and the stop advances towards that by a
fraction called the ``acceleration factor''.

@tex
$$ SAR = SAR_{prev} + accel \times (extreme - SAR_{prev}) $$
@end tex
@ifnottex
@example
SAR = SAR[prev] + accel * (extreme - SAR[prev])
@end example
@end ifnottex

The initial acceleration factor is 0.02, and each time a new extreme is made,
ie. a new high, it's increased by adding 0.02, up to a maximum of 0.2.  (Those
values are parameters in Chart.)  The effect is to move the stop up faster in
a strong move making successive new highs.

If the SAR for a given day is penetrated by any part of that day's trading
range then it's a signal to reverse one's position and the SAR becomes a
trailing stop for a short.  The calculation for that is the same, using the
previous extreme high as the initial stop and maintaining a low to step
towards.  Reversals can be seen in the graph when the stop mark switches from
above to below the prices, or back.

This approach is only suited to trending markets.  If prices are chopping back
and forward in a ranging market then a lot of whipsaw reversals are generated.
At each reversal the new stop point can be quite a distance from the current
prices, ie.@: one's entry point, making those whipsaws expensive.  Wilder
believed markets trend only about 30% of the time.  His ADX
(@pxref{Directional Movement Index}) is one way to identify such conditions.

In Chart the default is not to adjust for dividend payments in the display or
in indicator calculations.  If price falls on ex-dividend dates are causing
unwarranted SAR reversals you can turn on the adjustment option in the view
style (@pxref{View Style}).  (Assuming the data source provides dividend
information.)


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

@menu
* Accumulation/Distribution::
* Accumulative Swing Index::
* 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 ---------------------------------------------------------------------------
@node Aroon, Average True Range, Accumulative Swing Index, Indicators
@section Aroon
@cindex Aroon

@cindex Chande, Tushar
The Aroon indicator by Tushar Chande shows the length of time since the
highest or lowest close among the past N days' closes.  There are three lines:
Aroon Up for the high, Aroon Down for the low, and the Aroon Oscillator.

Aroon Up and Down are both expressed as percentages 0 to 100.  If today is a
new N-day high then Aroon Up is 100, and for each day that passes (without a
fresh N-day high) it drops by 100/N, down to 0 for no new highs in the past N
days.  Conversely for Aroon Down for new N-day lows.

The Aroon Oscillator is simply the difference between the Up and Down lines,

@tex
$$ AroonOsc = AroonUp - AroonDown $$
@end tex
@ifnottex
@example
AroonOsc = AroonUp - AroonDown
@end example
@end ifnottex

In Chart the Up line is drawn in green, the down in red, and the oscillator in
white.


@c ---------------------------------------------------------------------------
@node Average True Range, Centre of Gravity Oscillator, Aroon, Indicators
@section Average True Range
@cindex Average true range
@cindex ATR

@cindex True range
@cindex Wilder, J. Welles
Average true range (ATR) by J.@: Welles Wilder is the daily ``true range''
values (@pxref{True Range}) smoothed by an N-period exponential moving average
(@pxref{Exponential Moving Average}).

@tex
$$ ATR = EMA[N] \, of \, True \, Range $$
@end tex
@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 indexes 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 indexes 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
values (ie. ignoring negative signs),

@tex
$$ meandev = { |tp_1 - mean\;tp| + |tp_2 - mean\;tp| + \cdots + |tp_N - mean\;tp| \over N } $$
@end tex
@ifnottex
@example
          abs(tp1 - mean tp) + abs(tp2 - mean tp) + ... abs(tpN - mean tp)
meandev = ----------------------------------------------------------------
                                       N
@end example
@end ifnottex

The scaling factor 0.015 above is designed to put the index between +100 and
-100 roughly 70% to 80% of the time.  Those levels are drawn as dashed lines.
Lambert regarded index values outside that range as overbought or oversold,
but with no actual buy or sell signal until crossed back, ie. rising above
+100 then coming back below that, or conversely falling below -100 then rising
back above it again.

The default N-day period in Chart is 20 days.  Lambert recommended making it
about 1/3 of the market cycle, so 20 days would correspond to a 60 day cycle.

The @math{meandev} calculated is similar to the standard deviation
(@pxref{Standard Deviation}) in that it's an average difference from the mean,
but @math{meandev} is a mean of the absolute differences, whereas stddev is a
quadratic mean of those differences.


@c ---------------------------------------------------------------------------
@node Coppock Curve, Detrended Price Oscillator, Commodity Channel Index, Indicators
@section Coppock Curve
@cindex Coppock curve
@cindex Curve, Coppock

@cindex Coppock, Edwin
The Coppock Curve, or Coppock Indicator, by Edwin Coppock, first published in
Barrons magazine 1962, is a smoothed rate of change style indicator designed
to identify long-term buy signals on a monthly chart.

The indicator is calculated as the sum of 14-period and 11-period ROC values
(@pxref{Momentum and Rate of Change}), smoothed with a 10-period WMA
(@pxref{Weighted Moving Average}).  Adding the two ROCs has the effect of
averaging their values.

@tex
$$ Coppock = WMA[10] \; of \; (ROC[14] + ROC[11]) $$
@end tex
@ifnottex
@example
Coppock = WMA[10] of (ROC[14] + ROC[11])
@end example
@end ifnottex

Coppock designed the indicator for use on a monthly time scale, which can be
viewed in Chart with @key{Ctrl-M} (@pxref{Main Window}).  In other timebases
(days or weeks) Chart uses the same 14, 11 and 10 periods, which may or may
not be useful, since months were what Coppock intended.

The indicator generates a buy signal for long-term investors when it's below
zero and turns upwards from a trough.  The nature of the calculation means
this will be well after the low in prices, the signal is meant to indicate a
good rally has been established.


@c ---------------------------------------------------------------------------
@node Detrended Price Oscillator, Directional Movement Index, Coppock Curve, Indicators
@section Detrended Price Oscillator
@cindex Detrended price oscillator
@cindex DPO
@cindex Oscillator, detrended price

The detrended price oscillator (DPO) aims to eliminate an intermediate or long
term trend and show variations around that trend.  It's calculated on a given
N days using today's close and a past simple moving average (@pxref{Simple
Moving Average}),

@tex
$$ DPO = close - SMA\ over\ N\ days,\ as\ at\ {N\over2}+1\ days\ ago $$
@end tex
@ifnottex
@example
DPO = close - SMA over N days, as at N/2+1 days ago
@end example
@end ifnottex

This is somewhat similar to momentum (@pxref{Momentum and Rate of Change}),
but instead of taking the close N days ago, an average (the SMA) of N days
surrounding that point is used.


@c ---------------------------------------------------------------------------
@node Directional Movement Index, Ease of Movement, Detrended Price Oscillator, Indicators
@section Directional Movement Index
@cindex Directional movement index
@cindex DMI

@cindex Wilder, J. Welles
The directional movement index by J.@: Welles Wilder expresses so-called
directional movement, from high to high, or low to low, as a percentage of
true range (@pxref{True Range}).

When today's high is above yesterday's high, the increase is upwards
directional movement, written DM+.  If today's high is not above yesterday's
then DM+ is zero.  Conversely when today's low is less than yesterday's low
the decrease is downward directional movement, written DM-.  Again if today's
low is not below yesterday's then DM- is zero.  Both DM+ and DM- are positive
numbers, the ``+'' and ``-'' signs just refer to the direction of the
movement.

On an ``inside day'' where today's trading range is entirely within
yesterday's both DM+ and DM- are zero.  On an ``outside day'' where today's
trading goes both above and below yesterday's range, only the larger of DM+
and DM- is used and the other is set to zero.

The two DM+ and DM- series are each smoothed with an N-day exponential moving
average (@pxref{Exponential Moving Average}) and expressed as a percentage of
average true range (@pxref{Average True Range}).  The ATR uses the same N-day
EMA smoothing.  Two lines are formed, the upwards directional index DI+ and
downwards directional index DI-.

@tex
$$ DI+ = 100 \times { EMA[N] \, of \, DM+ \over ATR[N] } \;\;\;\;\;
   DI- = 100 \times { EMA[N] \, of \, DM- \over ATR[N] } $$
@end tex
@ifnottex
@example
            EMA[N] of DM+                 EMA[N] of DM+
DI+ = 100 * -------------     DI+ = 100 * -------------
                ATR[N]                        ATR[N]
@end example
@end ifnottex

In Chart, DI+ is drawn in green (for upwards) and DI- is drawn in red (for
downwards).

The smoothing N is by Wilder's reckoning of EMA smoothing period (as discussed
in @ref{Exponential Moving Average}), the default is the 14 he recommended.

An extreme of 100 is approached on DI+ when each day trades entirely above
yesterday's range (eg. runaway gaps), and then closes at the high of the day.
This is rather rare, usually there's some pullbacks.  Essentially DM+ counts
just the advance, the true range in the denominator counts the backtracking
too.  For DI-, an extreme of 100 is approached similarly when each day trades
entirely lower the previous, and closes at its low.

@cindex Average directional index
@cindex ADX
@anchor{Average Directional Index}
@subsection Average Directional Index

The average directional index (ADX) combines DI+ and DI-, expressing their
difference (ignoring the sign) as a percentage of the total, forming a single
line ranging 0 to 100,

@tex
$$ ADX = 100 \times { |DI+ - DI-| \over DI+ + DI- } $$
@end tex
@ifnottex
@example
            abs(DI+ - DI-)
ADX = 100 * --------------
              DI+ + DI-
@end example
@end ifnottex


@c ---------------------------------------------------------------------------
@node Ease of Movement, Elder Bull/Bear Power, Directional Movement Index, Indicators
@section Ease of Movement
@cindex Ease of movement
@cindex Movement, Ease of

@cindex Arms, Richard
The ease of movement indicator by Richard Arms shows a ratio of price
movements over volume.  Big moves on light volume mean easy movement through
price levels, small moves and/or heavier volume means difficult movement.

@tex
$$ Ease = { midpoint_{today} - midpoint_{yesterday} \over box\,ratio } $$
@end tex
@ifnottex
@example
       midpoint[today] - midpoint[yesterday]
Ease = -------------------------------------
                  box ratio
@end example
@end ifnottex

The midpoint is the middle of the day's trading range,
ie. @math{(high+low)/2}.  The box ratio is volume over trading range, giving
the amount of volume required to move by one price tick, on the day.  Volume
is taken in millions, to bring the scale up (with no effect on the shape).

@tex
$$ box\,ratio = { volume_{today} \over high_{today} - low_{today} } $$
@end tex
@ifnottex
@example
                 volume[today]
box ratio = ------------------------
            high[today] - low[today]
@end example
@end ifnottex

Ease of movement is smoothed with an exponential moving average
(@pxref{Exponential Moving Average}), with default 14 periods.  The raw daily
values can be seen, if desired, by setting the average to 1 day.


@c ---------------------------------------------------------------------------
@node Elder Bull/Bear Power, Fisher Transform, Ease of Movement, Indicators
@section Elder Bull/Bear Power
@cindex Elder bull/bear power
@cindex Bull power
@cindex Bear power

@cindex Elder, Alexander
Bull power and bear power by Dr.@: Alexander Elder show where today's high and
low lie relative to the a 13-day EMA (@pxref{Exponential Moving Average}) of
the closing prices.

@tex
$$ Bull\;power = High - EMA[13]\,of\,close $$
$$ Bear\;power = Low - EMA[13]\,of\,close $$
@end tex
@ifnottex
@example
Bull power = High - EMA[13] of close
Bear power =  Low - EMA[13] of close
@end example
@end ifnottex

Bull power is drawn in green and the bear power in red.  The 13-day period is
an option (@pxref{View Style}).  A 13-day EMA can be selected in the top
window to show the basis for the calculation.  The indicator lines are like
``detrended'' variations around that average.

Elder takes the 13-day EMA to be a consensus of value, and the amount bulls
can push the daily highs above that is their power, and conversely the amount
the bears can push daily lows below it is theirs (sending the bear power line
negative).


@c ---------------------------------------------------------------------------
@node Fisher Transform, Force Index, Elder Bull/Bear Power, Indicators
@section Fisher Transform
@cindex Fisher transform

@uref{http://www.mesasoftware.com/technicalpapers.htm}
@uref{http://www.mesasoftware.com/Papers/USING%20THE%20FISHER%20TRANSFORM.pdf}

@cindex Ehlers, John
The fisher transform indicator by John Ehlers is a range oscillator showing
where today's price is within the past N-days highest and lowest.  It has some
smoothing, plus what's known in mathematics as a fisher transform.

The range position is similar to Stochastics and to Williams %R
@c FIXME (@pxref{Stochastics}, and
(@pxref{Williams %R}).  The fisher transformation stretches out values near
the N-day high and low to make large peaks so as to help highlight those
extremes.

The calculation is as follows.  The prices used are the midpoint between the
day's high and low (as in most of Ehlers' indicators).  Today's price is
located within the highest and lowest of those midpoints from the past N days,
scaled to @math{-1} for the low and @math{1} for the high.

@tex
$$ price = { high + low \over 2 } $$
$$ 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
open-to-close movement in the past N days as percentage of total open-to-close
movement (up and down).

@tex
$$ IMI = { Sum[N]\;of\; \max(close-open, 0)
     \over Sum[N]\;of\; |close-open| } $$
@end tex
@ifnottex
@example
      Sum[N] of max(close-open, 0)
IMI = ----------------------------
        Sum[N] of abs(close-open)
@end example
@end ifnottex

This is like an RSI (@pxref{Relative Strength Index}) but on open-to-close
movement and with a simple moving average.

The use of open-to-close is also similar to the way QStick
(@pxref{QStick}) shows proportions of black and white candlesticks, with IMI
scaling according to the total real-body height in the past N days.


@c ---------------------------------------------------------------------------
@node Klinger Volume Oscillator, MACD, Intraday Momentum Index, Indicators
@section Klinger Volume Oscillator
@cindex Klinger volume oscillator
@cindex KVO
@cindex KO
@cindex Oscillator, Klinger volume

@cindex Klinger, Stephen J.
The Klinger volume oscillator (KVO) by Stephen J.@: Klinger is based on
cumulative volume, with volume added or subtracted according to the direction
of typical price and weighted by a certain daily range calculation.

A trend direction is determined from today and yesterday's ``typical prices''
(which are @math{(high+low+close)/3}),

@tex
$$ trend = \left\{ \matrix{
   1 & \mathop{\rm if} \; TP_{today}  >  TP_{yesterday} \cr
  -1 & \mathop{\rm if} \; TP_{today} \le TP_{yesterday} \cr
} \right. $$
@end tex
@ifnottex
@example
trend = /  1 if  TP[today] >  TP[yesterday]
        \ -1 if  TP[today] <= TP[yesterday]
@end example
@end ifnottex

A daily measurement @math{DM = high-low} is calculated and then a cumulative
measurement formed (cumulative while the trend direction is the same),

@tex
$$ CM = \left\{ \matrix{
  CM_{yesterday} + DM_{today}
                 & \mathop{\rm if} \; trend_{today} = trend_{yesterday} \cr
  DM_{yesterday} + DM_{today}
                 & \mathop{\rm if} \; trend_{today} \ne trend_{yesterday} \cr
} \right. $$
@end tex
@ifnottex
@example
CM[today] = / CM[yesterday] + DM[today]  if  trend[today]==trend[yester]
            \ DM[yesterday] + DM[today]  if  trend[today]!=trend[yester]
@end example
@end ifnottex

A ``volume force'' is then formed by accumulating volume amounts, with the
``trend'' factor making them add or subtract according to the typical price
direction, and with the values scaled by DM and CM.

@tex
$$ VF = volume \times trend \times |2{DM \over CM} - 1| $$
@end tex
@ifnottex
@example
VF = volume * trend * abs(2*DM/CM - 1)
@end example
@end ifnottex

The Klinger oscillator is then formed as the difference between fast (34-day)
and slow (55-day) EMAs (@pxref{Exponential Moving Average}) of the volume
force.

@tex
$$ KVO = EMA[34] \, of \, VF - EMA[55] \, of \, VF $$
@end tex
@ifnottex
@example
KVO = EMA[34] of VF - EMA[55] of VF
@end example
@end ifnottex

This is drawn in green, and a trigger line is drawn in red, being a 13-period
EMA of the KVO line.  The view style (@pxref{View Style}) has an option to
draw the difference between the two lines as a histogram, in MACD style
(@pxref{MACD}).

The raw volume force can be viewed directly as ``KVO volume force'' under
``Low Priority'' near the end of the indicator lists.


@c ---------------------------------------------------------------------------
@node MACD, MASS Index, Klinger Volume Oscillator, Indicators
@section MACD
@cindex MACD
@cindex Moving average convergence/divergence

@cindex Appel, Gerard
The MACD (Moving Average Convergence/Divergence) indicator by Gerard Appel
shows how two moving averages on closing prices come together or move apart
(ie.@: converge or diverge).  The main MACD line is the difference between a
fast and slow EMA (@pxref{Exponential Moving Average}), this is shown in green
in Chart.

@tex
$$ MACD = EMA[12]\,of\,price - EMA[26]\,of\,price $$
@end tex
@ifnottex
@example
MACD = EMA[12] of price - EMA[26] of price
@end example
@end ifnottex

A signal or trigger line is then formed by smoothing this with a further EMA.
This is shown in red in Chart.

@tex
$$ signal = EMA[9]\,of\,MACD $$
@end tex
@ifnottex
@example
signal = EMA[9] of MACD
@end example
@end ifnottex

A crossing of the MACD up through the signal line is taken as a buy signal, or
downwards a sell signal.  The difference between these lines is shown as a
histogram (solid white block).  This helps show whether the lines are coming
together or going further apart.

@tex
$$ histogram = MACD - signal $$
@end tex
@ifnottex
@example
histogram = MACD - signal
@end example
@end ifnottex

Crossings of the MACD line up or down through zero are also interpreted as
bullish or bearish (respectively).  This corresponds to crossings of the
underlying EMA[12] up or down through the EMA[26].

Periods 12,26,9 are frequently used, but can be varied in Chart (@pxref{View
Style}).


@c ---------------------------------------------------------------------------
@node MASS Index, Momentum and Rate of Change, MACD, Indicators
@section MASS Index
@cindex MASS index
@cindex Index, MASS

@cindex Dorsey, Donald
The MASS index by Donald Dorsey is based on daily trading range.  Each day's
range high to low is calculated and those values are smoothed with a 9-day EMA
(@pxref{Exponential Moving Average}).  A ratio of that value with a second EMA
smoothing is then taken, and the past 25 days of those ratios added up.

@tex
$$ MASS = Sum[25] \; of \; { EMA[9] \; of \; high-low
                      \over EMAofEMA[9] \; of \; high-low } $$
@end tex
@ifnottex
@example
                    EMA[9] of high-low
MASS = Sum[25] of -----------------------
                  EMAofEMA[9] of high-low
@end example
@end ifnottex

The EMA and the EMA of EMA are normally quite close, making their ratio
usually about 1 and hence the sum formed is usually close to 25.  The most
significant pattern Dorsey looked for was a ``reversal bulge'' where the index
goes above 27 then falls back below 26.5, indicating a widening of daily
trading range and suggesting a reversal in price is likely.

@cindex EMA of EMA
@cindex Double exponential moving average
@cindex Average, double exponential
@cindex Moving average, double exponential
@anchor{EMA of EMA}
@section EMA of EMA

Applying an EMA a second time gives a quite different result 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 double EMA spreads more broadly, and
the latest few days' influence is in fact smaller than the peak weights (at
about N/2 days back).  The following graph shows the weights for @math{N=10}.

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

The twice-smoothed EMA is also available directly as a moving average option,
under ``Low Priority'' in the indicator lists, to see its effect on prices or
on an oscillator.


@c ---------------------------------------------------------------------------
@node Momentum and Rate of Change, Money Flow Index, MASS Index, Indicators
@section Momentum
@cindex Momentum
@cindex Rate of change
@cindex ROC

Momentum and rate of change show a difference between today's close and the
close N days ago.  Momentum is the difference as a price amount (positive or
negative), rate of change scales it to a percentage increase or decrease from
that N-day ago close.  This scaling is an advantage if comparing past times
when prices levels were much higher or lower than now.  If @ms{p,1} is today,
@ms{p,2} yesterday, etc, then

@tex
$$ Momentum = p_1 - p_{N+1} $$
$$ ROC = 100 \; {p_1 - p_{N+1} \over p_{N+1}} $$
@end tex
@ifnottex
@example
Momentum = p[1] - p[N+1]

            p[1] - p[N+1]
ROC = 100 * -------------
               p[N+1]
@end example
@end ifnottex

It will be noticed that momentum is the difference between an N-day simple
moving average (@pxref{Simple Moving Average}) for today and yesterday, with a
scale factor N, ie.@:

@tex
$$ {Momentum \over N} = SMA_{today} - SMA_{yesterday} $$
@end tex
@ifnottex
@example
Momentum
-------- = SMA[today] - SMA[yesterday]
   N
@end example
@end ifnottex

This is the slope of the SMA line (price change per day) at that point.
Momentum crosses up through zero when SMA makes a peak, or down through zero
when SMA makes a trough.  The TRIX indicator (@pxref{TRIX}) does a similar
thing with a triple exponential moving average.

@subsection Additional Resources

@itemize
@item
@uref{http://trader.online.pl/MSZ/e-w-Chandes_Trendscore.html} -- Formula and
sample on Polish WIG20 from 2000.
@end itemize


@c ---------------------------------------------------------------------------
@node Money Flow Index, On-Balance Volume, Momentum and Rate of Change, Indicators
@section Money Flow Index
@cindex Money Flow Index
@cindex MFI
@cindex Index, money flow

The Money Flow Index (MFI) ranges from 0 to 100 showing dollar volume
(referred to as ``money flow'') on up days as a percentage of total up and
down days, in a given past N days.

The calculation is as follows.  A ``typical price'' is formed from the average
of high, low and close.  If high/low figures are not available then Chart just
uses the close,

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

``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 indexes
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
@cindex Relative strength index
@cindex RSI
@cindex Index, relative strength

@cindex Wilder, J. Welles
The Relative Strength Index (RSI) by J.@: Welles Wilder compares average
upward close-to-close movement against all close-to-close movement, each
smoothed by an EMA (@pxref{Exponential Moving Average}).

For each day an upward or downward movement is calculated.  On an up day

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

or on a down day as follows (notice D is a positive amount),

@tex
$$ 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
} \right. $$
$$ RVIorig = 100 \times { EMA[W14]\;of\;U
                    \over EMA[W14]\;of\;S } $$
@end tex
@ifnottex
@example
S = Stddev[10 days]

U = /  S   if price > prev price
    \  0   otherwise

                EMA[W14] of U
RVIorig = 100 * -------------
                EMA[W14] of S
@end example
@end ifnottex

In 1995 Dorsey revised his idea, to apply RVI to the daily highs and daily
lows and average the result, thus the following, which is the RVI used in
Chart.

@tex
$$ RVIorig = { RVIorig\;of\;highs + RVIorig\;of\;lows \over 2 } $$
@end tex
@ifnottex
@example
      RVIorig of highs + RVIorig of lows
RVI = ----------------------------------
                      2
@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.


@c ---------------------------------------------------------------------------
@node TD Range Expansion Index, Trend Intensity Index, Stochastics, Indicators
@section TD Range Expansion Index
@cindex TD range expansion index
@cindex Range expansion index
@cindex TDREI

@cindex DeMark, Tom
The range expansion index by Tom DeMark is designed to identify price
exhaustion which may be the end of a move up or down.

The calculation is somewhat similar to an RSI (@pxref{Relative Strength
Index}) but looks at 2-day changes in the daily high and daily low values and
smooths with a 5-day SMA (@pxref{Simple Moving Average}).  Changes are ignored
if the current day in not either within or covering price action from 5 or 6
days ago.  That test effectively holds the indicator around zero while prices
are making breakaway runs.

DeMark regarded values above @math{+45} or below @math{-45} as overbought or
oversold.  Such a reading maintained for up to five days suggests a reversal,
except that if it remains there for 6 or more days then the signal may be
unreliable and trading should be avoided.


@c ---------------------------------------------------------------------------
@node Trend Intensity Index, Trendscore, TD Range Expansion Index, Indicators
@section Trend Intensity Index
@cindex Trend intensity index
@cindex TII

@cindex Pee, M. H.
The trend intensity index (TII) by M.@: H.@: Pee measures the strength of a
trend, by looking at what proportion of the past 30 days prices have been
above or below the level of today's 60-day simple moving average
(@pxref{Simple Moving Average}).

The 60-day average is as of today, not its past values at each of
those past 30 days.  For each day the deviation @math{close-avg} is
taken.  Positive amounts are up deviations, and negative amounts have
the sign discarded and are down deviations.

@tex
$$ up = \left\{
 \matrix{ close - average & \mathop{\rm if} \; close > average \cr
                        0 & otherwise \hfill \cr
} \right. $$
$$ down = \left\{
 \matrix{ average - close & \mathop{\rm if} \; average > close \cr
                        0 & otherwise \hfill \cr
} \right. $$
@end tex
@ifnottex
@example
up   = /  close - average   if close > average
       \        0           otherwise

down = /  average - close   if average < close
       \        0           otherwise
@end example
@end ifnottex

The percentage of the total up amounts out of total up and down amounts is
then the trend intensity index,

@tex
$$ RVIorig = 100 \times { total \; up
                  \over   total \; up + total \; down } $$
@end tex
@ifnottex
@example
                  total up
TDI = 100 * ---------------------
            total up + total down
@end example
@end ifnottex

The extreme of 100 occurs when all closes in the past 30 days have been above
today's 60-day moving average level, and conversely the extreme of 0 when all
below that level.

Visually the index is like looking at the area under the graph of prices.  The
area above a horizontal line at today's 60-day moving average is the up
amounts, the area below it is the down amounts, and the index is the fraction
of the up out of the total.

Pee recommended entering trades when levels of 80 on the upside or 20 on the
downside are reached.  Lines are shown in Chart at those levels, as is 50
which is a neutral level.

The 60 and 30 days are configurable (@pxref{View Style}).  Any values are
accepted, but it probably doesn't make much sense to have the MA period (60)
shorter than the deviations period (30).  Certainly it makes no sense to have
the two equal, because the up deviations are then always exactly 50% of the
total.


@c ---------------------------------------------------------------------------
@node Trendscore, True Strength Index, Trend Intensity Index, Indicators
@section Trendscore
@cindex Trendscore

@cindex Chande, Tushar
Trendscore by Tushare Chande@footnote{@iquot{Rating Trend Strength}, Technical
Analysis of Stocks and Commodities magazine, 11:9 (382-386)} rates the
strength of a trend.  The calculation is quite simple, today's close is
compared to each close at 11 through 20 days ago and scored @math{+1} for each
it's above and @math{-1} if below.

@tex
$$ Trendscore = \left\{
  \matrix{
    if\,close \ge close[11]\; then\; +1\; else \;-1 \cr
    +\, if\,close \ge close[12]\; then\; +1\; else \;-1 \cr
    \cdots \cr
    +\, if\,close \ge close[20]\; then\; +1\; else \;-1 \cr
} \right. $$

$$ Trendscore = 100 \times { TripleEMA[today] - TripleEMA[yesterday]
                       \over TripleEMA[yesterday] } $$
@end tex
@ifnottex
@example
Trendscore =   if close >= close[11] then +1 else -1
             + if close >= close[12] then +1 else -1
             ...
             + if close >= close[12] then +1 else -1
@end example
@end ifnottex

The result is a rating between @math{+10} or @math{-10} for how many of those
past days the current close is above.  The high of @math{+10} is when above
all those past prices, or @math{-10} when below them all.  In a good trend up
or down those extremes are often reached.


@c ---------------------------------------------------------------------------
@node True Strength Index, TRIX, Trendscore, Indicators
@section True Strength Index
@cindex True strength index
@cindex Index, True strength
@cindex TSI

@cindex Blau, William
The true strength index (TSI) by William Blau@footnote{@iquot{The True
Strength Index}, Technical Analysis of Stocks and Commodities magazine,
November 1991, and @iquot{Trading With the True Strength Index}, May 1992.} is
variation of the RSI (@pxref{Relative Strength Index}) using two EMAs to
smooth (@pxref{Exponential Moving Average}), and a scale @math{-100} to
@math{+100}.

@tex
$$ TSI = 100 \times { EMA[13]\; of\; EMA[25]\; of\; (close - prevclose )
                \over EMA[13]\; of\; EMA[25]\; of\; \left| close - prevclose \right| } $$
@end tex
@ifnottex
@example
            EMA[13] of EMA[25] of   (close - prevclose)
TSI = 100 * --------------------------------------------
            EMA[13] of EMA[25] of  abs(close - prevclose)
@end example
@end ifnottex

The TSI ranges from @math{-100} up to @math{+100} with positive values
representing upward momentum and negative values downward momentum.  Extreme
values can be interpreted as overbought and oversold, as per the ordinary RSI.

The two EMA periods are parameters in Chart.  If you set one of them to 1 then
you get a plain RSI, though with a period by the usual reckoning whereas the
RSI is in Wilder's style (@pxref{Wilder EMA period}), so for instance a TSI
27,1 is equivalent to an RSI 14.

See @ref{EMA of EMA} for the effect of two EMAs.  In general it leads to less
weighting on the most recent data (the close-to-close differences in this
case) than a single EMA.

See also CMO (@pxref{Chande Momentum Oscillator}) using another different
moving average for an RSI.


@c ---------------------------------------------------------------------------
@node TRIX, Twiggs Money Flow, True Strength Index, Indicators
@section TRIX
@cindex TRIX

@cindex Hutson, Jack
TRIX by Jack Hutson shows the slope of a triple-smoothed N-day exponential
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
@ifnottex
@example
              / R[1]^2 + R[2]^2 + ... + R[N]^2 \
Ulcer = sqrt |  ------------------------------  |
              \              N                 /
@end example
@end ifnottex

The index can be calculated over the kind of period one might hold an
investment to calculate a measure of the ulcer-producing drawdowns suffered
during that period.


@c ---------------------------------------------------------------------------
@node Ultimate Oscillator, Vertical Horizontal Filter, Ulcer Index, Indicators
@section Ultimate Oscillator
@cindex Ultimate oscillator

@cindex Williams, Larry
The Ultimate Oscillator by Larry Williams is based on buying pressure as a
proportion of true range over recent periods, with the past 7 days, 14
days and 28 days combined together.

The calculation starts with ``buying pressure'', which is the amount by which
the close is above the ``true low'' on a given day.  The true low is the
lesser of the given day's trading low, and the previous close.

@tex
$$ bp = close - \min (low, prev\,close) $$
@end tex
@ifnottex
@example
bp = close - min (low, prev close)
@end example
@end ifnottex

The true range (the same as in @ref{True Range}) is the difference between the
``true high'' and the true low above.  The true high is the greater of the
given day's trading high, and the previous close.

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

The total buying pressure over the past 7 days is expressed as a fraction of
the total true range over that period.  If @ms{bp,1} is today, @ms{bp,2}
yesterday, etc then

@tex
$$ avg_7 = {bp_1 + bp_2 + \cdots + bp_7 \over tr_1 + tr_2 + \cdots + tr_7 } $$
@end tex
@ifnottex
@example
       bp1 + bp2 + ... + bp7
avg7 = ---------------------
       tr1 + tr2 + ... + tr7
@end example
@end ifnottex

The same is done for the past 14 days and past 28 days and the resulting three
values combined in proportions 4:2:1, and expressed as a percentage.

@tex
$$ UltOsc = 100 \times {4 \times avg_7 + 2 \times avg_{14} + avg_{28}
                        \over 4 + 2 + 1 } $$
@end tex
@ifnottex
@example
                4 * avg7 + 2 * avg14 + avg28
UltOsc = 100 *  ----------------------------
                         4 + 2 + 1
@end example
@end ifnottex

The oscillator ranges from 0 to 100 and is interpreted in similar ways to
other oscillators, with extremes indicating overbought or oversold conditions,
and bullish or bearish divergence when new lows or highs fail to be made.
Williams recommended levels of 70 and 30 for overbought or oversold and those
are drawn by Chart.


@c ---------------------------------------------------------------------------
@node Vertical Horizontal Filter, Volatility Ratio, Ultimate Oscillator, Indicators
@section Vertical Horizontal Filter
@cindex Vertical horizontal filter
@cindex VHF
@cindex Filter, vertical horizontal

@cindex White, Adam
The vertical horizontal filter (VHF) by Adam White expresses the range of
closing prices as a fraction of total close-to-close movement over a given
N-day period.

@tex
$$ VHF = { highest\,close - lowest\,close
     \over total \, of \, each \, |close - prev\,close| }
$$
@end tex
@ifnottex
@example
          highest close - lowest close
VHF = -------------------------------------
      total of each abs(close - prev close)
@end example
@end ifnottex

This ratio ranges from 0 to 1.  The extreme of 1 means all close-to-close
movement was in one direction, so they added up to the full range.  A usual
value is somewhere in the middle, reflecting a mixture of advances and
retreats that occur even in a strong market.


@c ---------------------------------------------------------------------------
@node Volatility Ratio, Williams %R, Vertical Horizontal Filter, Indicators
@section Volatility Ratio
@cindex Volatility ratio
@cindex Ratio, volatility
@cindex VOLR

@cindex Schwager, Jack
The volatility ratio by Jack Schwager expresses the latest day's trading range
as a ratio of the overall range for a past N days.  ``True range'' is used for
both (@pxref{True Range}), so gaps are included in the calculation.

For an N-day true range the close immediately preceding those N days is
incorporated.  Thus

@tex
$$ TR\;Ndays = \max(high_1, high_2, \dots, high_N, close_{N+1})
             - \min(low_1, low_2, \dots, low_N, close_{N+1}) $$
@end tex
@ifnottex
@example
TR Ndays = max(high[1], high[2], ... high[N], close[N+1])
         - min(low[1],  low[2], ...  low[N],  close[N+1])
@end example
@end ifnottex

The volatility ratio is then simply

@tex
$$ VOLR = { TR \over TR\;Ndays } $$
@end tex
@ifnottex
@example
          TR
VOLR = --------
       TR Ndays
@end example
@end ifnottex

When a strong breakout from a tight range occurs the day's range can be a
sizeable fraction of the recent range.  A level of 0.5 is considered
significant and that's drawn as a line in Chart.


@c ---------------------------------------------------------------------------
@node Williams %R, Williams Accumulation/Distribution, Volatility Ratio, Indicators
@section Williams %R
@cindex Williams %R
@cindex %R

@cindex Williams, Larry
Williams %R by Larry Williams is an oscillator showing the day's close
relative to the trading range of the last N days (the highest high to the
lowest low).  The scale is 0 for a close at the high, down to -100 for a close
at the low.

Williams used a 10 day period, which is the default in Chart, and held that a
close above -20 suggested an overbought condition, and below -80 suggests
oversold.  Those levels are shown as lines in Chart.  Extremes are reached
almost any time new N-day highs or lows are being made, so Williams'
conditions for trading were to buy an oversold when

@itemize @bullet
@item
%R reaches -100%.
@item
Five trading days pass since -100% was last reached
@item
%R rises above -95% or -85%.
@end itemize

or conversely to sell an overbought

@itemize @bullet
@item
%R reaches 0%.
@item
Five trading days pass since 0% was last reached
@item
%R falls below -5% or -15%.
@end itemize


@c ---------------------------------------------------------------------------
@node Williams Accumulation/Distribution, Zig Zag Indicator, Williams %R, Indicators
@section Williams Accumulation/Distribution
@cindex Williams accumulation/distribution
@cindex Accumulation/distribution, Williams
@cindex Index, Williams accumulation/distribution

@cindex Williams, Larry
The Williams Accumulation/Distribution index by Larry Williams forms a running
total of ``buying pressure'' on up days, or ``selling pressure'' on down days.

@tex
$$ WAD = WAD_{prev} + \left\{
  \matrix{
    (close - true\,low)  & \mathop{\rm if} \; close > prev\,close \cr
    0                    & \mathop{\rm if} \; close = prev\,close \cr
    (close - true\,high) & \mathop{\rm if} \; close < prev\,close \cr
} \right. $$
@end tex
@ifnottex
@example
                   / (close - true low)   if close > prev close
WAD = WAD[prev] + |  0                    if close = prev close
                   \ (close - true high)  if close > prev close
@end example
@end ifnottex

Buying pressure is represented by how far the close is above the true low
(which is the lesser of today's low or yesterday's close).  Selling pressure
is represented by how far the close is below the true high (which is the
greater of today's high or yesterday's close).  Notice the difference ``close
- true high'' is negative, so on down days WAD decreases.

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


@c ---------------------------------------------------------------------------
@node Zig Zag Indicator,  , Williams Accumulation/Distribution, Indicators
@section Zig Zag Indicator
@cindex Zig zag indicator
@cindex Indicator, zig zag

The zig zag indicator is a simple way to ignore retracements less than a given
X percentage.

When prices are rising, a line is drawn up from the previous low to the latest
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

Notice the numerator is the same SumSquares which was minimized above.
Standard error is similar to standard deviation (@pxref{Standard Deviation});
but where stddev takes differences from a horizontal line (the @math{Y} mean),
stderr here goes from the sloping linear regression line.

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 indexes 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}).

@itemize
@item Genius Trader @uref{http://www.geniustrader.org}
@cindex Genius Trader
@item TA-Lib @uref{http://www.ta-lib.org}
@cindex TA Lib
@end itemize

Genius Trader is written in Perl and to install you only need to have its code
somewhere in your Perl module path (@env{PERL5LIB} etc).

TA-Lib has a Perl interface generated by Swig.  As of version 0.5 the
interface is statically linked, so once compiled you only need to ensure the
generated @file{.pm} and @file{.so} files are in your Perl module path.

Various indicators and averages are available both natively in Chart and in GT
and/or TA-Lib too.  Sometimes there's subtle differences in the calculations
near the start of data, but generally it's just ``more than one way to do
it''.


@c ---------------------------------------------------------------------------
@node Watchlist, Intraday, Other Indicator Packages, Top
@chapter Watchlist
@cindex Watch list

The watchlist window shows latest quotes for stocks and commodities in the
favourites list or other list.  For example,

@example
Symbol   Bid/Offer    Last  Change  High    Low   Volume When Notes
^GSPC        /      1237.81  8.68 1228.33 1237.81   19m  Thu
GM           /        34.91 -0.10   34.57   35.38 3.74m  Thu
BHP.AX  21.03/21.05   21.05  0.31   20.75   21.05   16m  10:45
@end example

The favourites list and other user lists can be edited.  New symbols are added
by entering a symbol in the text box and pressing @key{Return} or clicking
``Insert''.  If already present then the list scrolls to it.  Move entries by
dragging.  Delete an entry by selecting it (click or @key{space}) and clicking
the ``Delete'' button.

Clicking in the symbol column edits the symbol there.  Double clicking in the
other columns opens the main Chart display on that symbol.  Mouse button-3
(usually the right-hand button) pops up a menu of other actions, including
opening an intraday window (@pxref{Intraday}).


@table @asis
@item Refresh
The Refresh button downloads new quotes for the whole list, or the Refresh
menu item for just that symbol.  For some data sources Chart knows the trading
times, and if there won't be after hours changes then the quote locks to the
end-of-day and is not re-downloaded until the next day.

@item Displayed List
The displayed list can be selected from a menu with Button-3 in the upper left
notebook tab, where the current list name is displayed.

The ``Symlists'' tab shows the available lists.  New lists can be created from
there, or the names of existing user lists changed.  Double clicking displays
the list.  Use the ``Edit Name'' button in the action area to change a name.
The order of the lists controls how they appear in the Open dialog
(@pxref{Open}) and the sequence for Next and Prev in the main display.  You
can drag rows to re-order.

@item Colours
Each line is shown in green for a last trade higher than yesterday's close,
red for lower, or black unchanged.  Blue means a refresh download is in
progress.

@item Bid/Offer Column
The bid/offer column is normally shown as say @samp{2.10/2.12}, but when the
market is crossed (ie.@: bid higher than offer) an ``x'' is used to highlight
this, for example @samp{2.20x1.99}.  What that means depends on the exchange,
it might be a pre-open auction, or merely transient.

@item Volume Column
Volume is abbreviated @samp{k} for thousands, @samp{m} for millions, @samp{b}
for billions.  This is number of shares (or number of contracts), the same as
shown in the main chart.

@item When Column
The ``When'' column shows just a time for today, just the day for the past
week, or a full date prior to that.  The timezone of the exchange is used.  If
the exchange is in your local zone then there's no difference, but if you're
elsewhere then the exchange zone has the advantage that you can see where it
is in the trading session, eg.@: early on, the close, etc.  It's easier to
remember opening and closing times at the exchange than local equivalents
(especially when daylight savings affects them).

@item Tooltip
Moving the mouse over an entry (and keeping it still) opens a tooltip box
showing the stock name (if available), full date/times for the quote and last
trade, and the exchange timezone location.
@end table


@c ---------------------------------------------------------------------------
@node Intraday, Download, Watchlist, Top
@chapter Intraday
@cindex Intraday

@cindex @key{Ctrl-I}
The View/Intraday menu entry (@key{Ctrl-I}) or the Intraday button in the
watchlist (@pxref{Watchlist}) opens an intraday image window for the current
symbol, showing trading today, or so-far today.

Alas there are no longer any data sources with intraday images.

@c are only
@c available from a few data sources (@pxref{Data Sources}).

@c @cindex @key{Alt-R}
@c The default display is 1-day, downloaded when the window is opened (then
@c cached).  The option menu can select other timeframes such as 5-day, depending
@c on the data source.  The underlined mnemonics ``5'' etc in the menu are
@c accelerator keys, eg.@: @key{Alt-5}.  Click on Refresh (@key{Alt-R}) to update
@c as trading progresses through the day.
@c 
@c Multiple intraday windows can be opened, or a new symbol entered in the text
@c box to view a different symbol (press @key{Return} or click the ``Enter''
@c button).
@c 
@c To see the intraday for a symbol not in the database or watchlist just open an
@c intraday window for any symbol (or no symbol at all) then enter the desired
@c one.


@c ---------------------------------------------------------------------------
@node Download, Data Sources, Intraday, Top
@chapter Download
@cindex Download
@cindex Dialog, download

@cindex Tools/Download
The Tools/Download menu entry opens the download dialog.  Choose ``What'' to
download, either all symbols, the favourites list, or a particular symbol.
@c Then choose ``When'' for the period to download, either an update of new
@c available data, or back to a given year (where possible).

The default is an update of all symbols.  This is usually what's wanted, to
get all latest data.

Click on the ``Start'' button to begin.  The top box is the subprocesses
running, the middle box is the jobs running or queued, and errors are shown in
the lower text window.  If you're offline the errors will usually be ``host
name lookup failure'' or ``network unreachable''.  To abort select the job in
the middle box and click on ``Stop''.

The main chart display can be used while downloading, for instance to look
immediately at the first few symbols updated while the rest are still going.
Sometimes a database update can make the GUI block for a moment.

@section Update Current Chart
@cindex Update data

@cindex @key{Ctrl-U}
In the main Chart window, @key{Ctrl-U} starts an update download for the
currently viewed chart.  This is a good shortcut to grab new data for just one
symbol.  Download progress is shown in the main window statusbar (as well as
the download dialog).

@section Download Automation
@cindex @command{cron}
@cindex Automation, download

You can run @samp{chart --download} to do a command-line (non-GUI) download
(@pxref{Invocation}), for instance in a script perhaps when first going
online, or at selected times.  Progress messages are shown if the output is a
terminal.

Care should be taken not to hammer the various data sources when automating
downloads.  Keep update attempts to times when there should be new data, and
don't retry endlessly.

Chart tries to know when to expect new data, and will do nothing in an update
until then, but this is often imperfect.  Public holidays (with no data) are
not tracked, and it's easy for a data source to be delayed unexpectedly.


@c ---------------------------------------------------------------------------
@node Data Sources, Internationalization, Download, Top
@chapter Data Sources
@cindex Data sources
@cindex Sources, data

Note that data from each of these sources is subject to various disclaimers
and conditions for its use.  A summary of the restrictions is noted in each
section and links to the relevant parts of the web sites which should be
consulted for full information.

The minimum terms for a source in Chart are that personal non-commercial use
is permitted.  In fact that's usually all that's permitted, and in particular
further copying or distribution is generally not allowed (and this will
include derived forms like the graphs drawn by Chart).

@menu
* Finance Quote::
* MLC Funds::
* New Zealand Stock Exchange::
* Reserve Bank of Australia::
* Thrift Savings Plan::
* Yahoo Finance::
@end menu


@c ---------------------------------------------------------------------------
@c @node Athens Stock Exchange, Australian Stock Exchange, Data Sources, Data Sources
@c @section Athens Stock Exchange
@c @cindex Athens Stock Exchange
@c @cindex ATHEX
@c 
@c @uref{http://www.ase.gr/default_en.asp}
@c 
@c ATHEX provides
@c 
@c @itemize
@c @item
@c End-of-day quotes.
@c @item
@c Historical data, but only for the past 30 days.
@c @item
@c Historical and upcoming dividends.
@c @end itemize
@c 
@c The content is for information only and is not to be retransmitted, see the
@c disclaimer,
@c 
@c @quotation
@c @uref{http://www.ase.gr/content/en/disclaimer/}
@c @end quotation
@c 
@c @cindex @code{.ATH}
@c In Chart ATHEX symbols have a @samp{.ATH} suffix, eg.@: @samp{HTO.ATH} for
@c Hellenic Telecom.  The home page has a company and symbol search.  Only the
@c English symbols are currently supported.


@c ---------------------------------------------------------------------------
@c Omitted while just plain yahoo ...
@c
@c @node Australian Stock Exchange, Finance Quote, Data Sources, Data Sources
@c @section Australian Stock Exchange
@c @cindex Australian Stock Exchange
@c @cindex ASX
@c 
@c @uref{http://www.asx.com.au}
@c 
@c @c ASX shares are handled by a combination of Yahoo (@pxref{Yahoo Finance}) for
@c @c quotes and dividends, and Float (@pxref{Float}) for daily and historical data.
@c @c CommSec (@pxref{Commonwealth Securities}) can also be used by CommSec clients.
@c 
@c ASX shares are handled by Yahoo (@pxref{Yahoo Finance}), with CommSec
@c (@pxref{Commonwealth Securities}) optionally for use by CommSec clients.
@c 
@c @cindex @code{.AX}
@c In Chart, symbols for ASX shares follow the Yahoo convention, which is the ASX
@c code and a @samp{.AX} suffix, eg.@: @samp{NAB.AX} for National Australia Bank.
@c The ASX home page (above) has a symbol search, as does Yahoo,
@c @c SYMBOL: NAB.AX
@c 
@c @quotation
@c @uref{http://au.finance.yahoo.com/l}
@c @end quotation


@c ---------------------------------------------------------------------------
@c Changed ...
@c
@c @node Commonwealth Securities, Finance Quote, Australian Stock Exchange, Data Sources
@c @section Commonwealth Securities
@c @cindex Commonwealth Securities
@c @cindex CommSec
@c 
@c @uref{http://www.comsec.com.au}
@c 
@c @cindex Australian Stock Exchange
@c @cindex ASX
@c CommSec provides the following Australian Stock Exchange data
@c (@pxref{Australian Stock Exchange}),
@c 
@c @itemize
@c @item
@c Daily data for shares, warrants, etc (but not indices) for the past 10 years.
@c Each day's data is available from 8:30pm Sydney time each day (when the ASX
@c finishes its closing).
@c @end itemize
@c 
@c This service is only for use by CommSec clients.
@c 
@c @cindex Preferences, CommSec
@c @c CommSec is used (when enabled) for updating individual stocks, since just a
@c @c past few months can be downloaded, which is faster than full history downloads
@c @c from Float (@pxref{Float}).
@c CommSec is preferred over Yahoo (@pxref{Yahoo
@c Finance}) since its data is available sooner than Yahoo.  If you're a CommSec
@c client you can enable it by entering ``yes'' in the Edit/Preferences dialog.


@c ---------------------------------------------------------------------------
@node Finance Quote, MLC Funds, Data Sources, Data Sources
@section Finance Quote
@cindex @code{Finance::Quote}
@cindex FQ

@uref{http://finance-quote.sourceforge.net}

If you have the @code{Finance::Quote} package installed Chart can use it for

@itemize
@item
Quotes for all stocks on all FQ methods.
@end itemize

@cindex @code{.FQ}
In Chart symbols are of the form @samp{CODE.method.FQ}, for example
@samp{FBGRX.fidelity.FQ} for Fidelity fund @samp{FBGRX} using the
Finance-Quote @code{fidelity} method.
@c SYMBOL: FBGRX.fidelity.FQ

A number of the FQ methods are covered by Chart natively (like US shares and
indexes from Yahoo for instance).

When using an FQ method not in the builtin defaults, you can add it to the
@env{FQ_LOAD_QUOTELET} environment variable in the usual way.  Chart also
tries a module of the same name as the method (case insensitive), so for
simple add-ons you might not need to configure anything.


@c ---------------------------------------------------------------------------
@node MLC Funds, New Zealand Stock Exchange, Finance Quote, Data Sources
@section MLC Funds
@cindex MLC Funds
@cindex Funds, MLC

@uref{http://www.mlc.com.au}

MLC provides the following for its managed investment funds and superannuation
funds,

@itemize
@item
Daily unit prices, with each day available some time the following afternoon
(Friday's prices not available until Monday afternoon).
@item
Historical prices back to the inception of each fund.
@end itemize

The web site is for general information only, and only provided for residents
of Australia, see the disclaimer at

@quotation
@uref{http://www.mlc.com.au/mlc/im_considering_mlc/personal/footer_tools/advice_warning_and_disclaimer}
@end quotation

Downloads use @code{https} so Chart needs the secure sockets modules for LWP
(@pxref{Installing}).

@cindex @code{.MLC}
There are no apparent fund symbols so Chart uses the full fund and product
name, with a @samp{.MLC} suffix.  For example,

@example
MLC Property Securities Fund,MasterKey Superannuation (Gold Star).MLC
@end example
@c SYMBOL: MLC Property Securities Fund,MasterKey Superannuation (Gold Star).MLC

This is a lot to type, but it can normally be cut and pasted from the full
list at the following unit prices page (the page source has the fund and
product names together),

@quotation
@uref{https://www.mlc.com.au/masterkeyWeb/execute/FramesetUnitPrices?null}
@end quotation


@c ---------------------------------------------------------------------------
@node New Zealand Stock Exchange, Reserve Bank of Australia, MLC Funds, Data Sources
@section New Zealand Stock Exchange
@cindex New Zealand Stock Exchange
@cindex NZX

@c Sep 2017 the http redirects to https
@uref{https://www.nzx.com}

NZX provides

@itemize
@item
Upcoming dividends.
@end itemize

Quotes, historical data and other information is obtained from Yahoo
(@pxref{Yahoo Finance}).

The NZX web site is for non-commercial or personal use only, see the terms at

@quotation
@uref{https://www.nzx.com/terms}
@end quotation

@cindex @code{.NZ}
In Chart NZX symbols follow the Yahoo convention, which is the exchange symbol
and a @samp{.NZ} suffix, for example @samp{FBU.NZ}.  The NZX home page above
has a search to lookup symbols (as does Yahoo).
@c SYMBOL: FBU.NZ


@c ---------------------------------------------------------------------------
@node Reserve Bank of Australia, Thrift Savings Plan, New Zealand Stock Exchange, Data Sources
@section Reserve Bank of Australia
@cindex Reserve Bank of Australia
@cindex RBA
@cindex Australian dollar

@uref{http://www.rba.gov.au}

The RBA provides

@itemize
@item
Daily exchange rates for the Australian dollar as at 4pm (Sydney time) each
business day, for about the past 2 years.
@end itemize

The RBA web site is for personal non-commercial use, with proper attribution.
See the full terms at the following link.  (Material is to be used in
``unaltered form'', but the bank advised a long time ago that import into a
charting program is permitted.)

@quotation
@uref{http://www.rba.gov.au/copyright/index.html}
@end quotation

Available currencies can be found on the exchange rates page

@quotation
@uref{http://www.rba.gov.au/statistics/frequency/exchange-rates.html}
@end quotation

In Chart symbols are @samp{AUDXXX.RBA} for the value of one Australian dollar
in the currency @samp{XXX}.  Currently these are as follows

@quotation
@multitable {@nicode{MMMMMM.RBA}} {MMMMMMMMMMMMMMMMMMMMMMM}
@headitem Symbol @tab Currency
@item AUDUSD.RBA @tab US dollar
@c SYMBOL: AUDUSD.RBA
@item AUDCNY.RBA @tab Chinese renminbi
@c SYMBOL: AUDCNY.RBA
@item AUDJPY.RBA @tab Japanese yen
@c SYMBOL: AUDJPY.RBA
@item AUDEUR.RBA @tab Euro
@c SYMBOL: AUDEUR.RBA
@item AUDKRW.RBA @tab South Korean won
@c SYMBOL: AUDKRW.RBA
@item AUDSGD.RBA @tab Singapore dollar
@c SYMBOL: AUDSGD.RBA
@item AUDNZD.RBA @tab New Zealand dollar
@c SYMBOL: AUDNZD.RBA
@item AUDGBP.RBA @tab UK pound sterling
@c SYMBOL: AUDGBP.RBA
@item AUDMYR.RBA @tab Malaysian ringgit
@c SYMBOL: AUDMYR.RBA
@item AUDTHB.RBA @tab Thai baht
@c SYMBOL: AUDTHB.RBA
@item AUDIDR.RBA @tab Indonesian rupiah
@c SYMBOL: AUDIDR.RBA
@item AUDINR.RBA @tab Indian rupee
@c SYMBOL: AUDINR.RBA
@item AUDTWD.RBA @tab Taiwanese dollar
@c SYMBOL: AUDTWD.RBA
@item AUDVND.RBA @tab Vietnamese dong
@c SYMBOL: AUDVND.RBA
@item AUDPNK.RBA @tab Papua New Guinea kina
@c SYMBOL: AUDPNK.RBA
@item AUDCHF.RBA @tab Swiss franc
@c SYMBOL: AUDCHF.RBA
@item AUDAED.RBA @tab UAE dirham
@c SYMBOL: AUDAED.RBA
@item AUDCAD.RBA @tab Canadian dollar
@c SYMBOL: AUDCAD.RBA
@item AUDPHP.RBA @tab Philippines peso
@c SYMBOL: AUDPHP.RBA
@end multitable
@end quotation

@cindex Special Drawing Right
@cindex Trade Weighted Index
Plus the following for the RBA's Trade Weighted Index for the Australian
dollar, and the Australian dollar valued in the IMF's Special Drawing Right
basket of currencies.

@quotation
@multitable {@nicode{MMMMMM.RBA}} {MMMMMMMMMMMMMMMMMMMMMMM}
@headitem Symbol @tab Value
@item AUDTWI.RBA              @tab Trade Weighted Index
@c SYMBOL: AUDTWI.RBA
@item AUDSDR.RBA              @tab Special Drawing Right
@c SYMBOL: AUDSDR.RBA
@end multitable
@end quotation

The historical data page
@uref{http://www.rba.gov.au/statistics/historical-data.html} has XLS files
going back to 1983 (and monthly to 1969) but the code for that in Chart has
bit-rotted and the CSV is about half the size.  The server offers compressed
downloads (@pxref{Installing}).

@c Incidentally, the historical data processing in Chart is very slow.  The main
@c bottleneck is @code{Spreadsheet::ParseExcel} apparently due to lots of
@c formatted rows in the XLS files.


@c ---------------------------------------------------------------------------
@node Thrift Savings Plan, Yahoo Finance, Reserve Bank of Australia, Data Sources
@section Thrift Savings Plan
@cindex Thrift Savings Plan
@cindex TSP
@cindex Funds, TSP

@uref{http://www.tsp.gov}

The US government Thrift Savings Plan (TSP) provides

@itemize
@item
Past 5 years daily fund prices, with new prices around 8pm (New York time)
each day.
@end itemize

@cindex @code{.TSP}
In Chart symbols are the fund code and a @samp{.TSP} suffix, for example
@samp{C.TSP} for the common stock fund.  The lifecycle funds are like
@samp{L2020.TSP}, and the lifecycle income fund is @samp{LINCOME.TSP}.

@cindex @code{Finance::Quote}
@cindex @code{Finance::Quote::TSP}
Chart uses @code{Finance::Quote::TSP} for the latest prices, so you must have
that module installed (it comes with the main @code{Finance::Quote}).


@c ---------------------------------------------------------------------------
@node Yahoo Finance,  , Thrift Savings Plan, Data Sources
@section Yahoo Finance
@cindex Yahoo Finance
@cindex New York Stock Exchange
@cindex NYSE
@cindex AMEX
@cindex NASDAQ

@uref{http://finance.yahoo.com}

Yahoo provides the following for many stock exchanges around the world
(@pxref{Yahoo Exchanges}),

@itemize
@item
Quotes, real-time for indexes and delayed for shares.
@c @item
@c Intraday graphs.
@item
Historical daily data, dividends and splits.
@item
Upcoming dividends.
@end itemize

Yahoo does not allow commercial use, see the terms of service at

@quotation
@uref{https://policies.yahoo.com/us/en/yahoo/terms/utos/index.htm}
@end quotation

Chart uses the Yahoo stock symbol conventions.  For US stocks (AMEX, Nasdaq,
NYSE) this is just the exchange symbol like @samp{AAPL} for Apple Computer.
Stocks from elsewhere are the exchange symbol and a suffix, like @samp{BMW.DE}
for BMW on Xetra.  See @ref{Yahoo Exchanges}, below, for those supported in
Chart.  Yahoo has a symbol lookup on most pages (and at the country-specific
sites),
@c SYMBOL: AAPL
@c SYMBOL: BMW.DE

@quotation
@uref{http://finance.yahoo.com/lookup}
@end quotation

@cindex Currencies
@cindex Metals, spot prices
Some currency cross-rates are available, they take a form such as
@samp{AUDUSD=X} for the value of one Australian dollar in US dollars.  Some
spot metals prices are available in a similar form, for example
@samp{XAUUSD=X} for Gold in US dollars.
@c SYMBOL: AUDUSD=X
@c SYMBOL: XAUUSD=X

Yahoo gives some information on market closing times, but Chart doesn't make
use of that.  A day's trading is written as daily data at 6pm (in the
exchange's timezone).  Before that the current day is a latest quote.  The
downloads are slightly overlapped so that if 6pm was too soon then its prices
are replaced on a subsequent download.

@c Dividends are re-downloaded weekly.  They seem to be a bit patchy, with not
@c all dividends actually appearing in the data for some stocks.  The most recent
@c dividend on the quotes pages is added to the database, so the latest should be
@c available at least.

@menu
* Yahoo Exchanges::
@end menu


@c @c ---------------------------------------------------------------------------
@c @node Yahoo Configuration, Yahoo Exchanges, Yahoo Finance, Yahoo Finance
@c @subsection Yahoo Configuration
@c @cindex Preferences, Yahoo
@c 
@c Historical data and intraday graphs always come from the main
@c @uref{http://finance.yahoo.com} site but quotes can be taken from the
@c country-specific sites.  It's not clear if this is an advantage, but you can
@c try it if you want.
@c 
@c All sites give quotes for all worldwide stocks, though it's possible a few
@c symbols might differ on the UK and European sites.  The full list of sites is
@c at the bottom of the Yahoo home page, but the only ones supported in Chart are
@c those with commas in the ``download data'' and dividend dates in English.
@c Currently this means the following (timezone names per the Olson database),
@c 
@c @quotation
@c @multitable {@CHARTniuref{MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM}} {@nicode{MMMMMMMMMMMMMMMM}}
@c @headitem URL @tab Timezone
@c @item @CHARTniuref{http://download.finance.yahoo.com} @tab @nicode{America/New_York}
@c @item @CHARTniuref{http://au.finance.yahoo.com} @tab @nicode{America/New_York}
@c @item @CHARTniuref{http://ca.finance.yahoo.com} @tab @nicode{America/Vancouver}
@c @item @CHARTniuref{http://in.finance.yahoo.com} @tab @nicode{America/New_York}
@c @item @CHARTniuref{http://sg.finance.yahoo.com} @tab @nicode{America/New_York}
@c @item @CHARTniuref{http://uk.finance.yahoo.com} @tab @nicode{Europe/London}
@c @end multitable
@c @end quotation
@c 
@c Under Edit/Preferences in Chart you can set your nearest site and its
@c timezone.  The timezone is as you might set the @env{TZ} environment variable
@c (@pxref{TZ Variable,,, libc, GNU C Library Reference Manual}).  If you have
@c trouble finding a zone setting your system understands then at worst you
@c should be able to set for example @samp{BST-1} for British Summer Time, 1 hour
@c ahead of GMT (negatives are ahead), and remember to change it when daylight
@c savings ends.
@c 
@c As shown in the table, the timezone is not necessarily the site's zone, which
@c is a bit bizarre.  If the timezone is wrong then the quote times in the
@c watchlist etc will be wrong, and even possibly the date of the latest drawn in
@c the charts.


@c ---------------------------------------------------------------------------
@node Yahoo Exchanges,  , Yahoo Finance, Yahoo Finance
@subsection Yahoo Exchanges

See also @ref{New Zealand Stock Exchange}, which uses Yahoo and is described
in its own section.

@c See also @ref{Australian Stock Exchange}, and @ref{New Zealand Stock
@c Exchange}, which use Yahoo, and are described in their own sections.

@c @url{https://help.yahoo.com/kb/SLN2310.html}

@quotation
@multitable {Suffix} {Mmmmmmmmmm} {MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM}
@headitem Suffix @tab Country @tab Exchange

@item none @tab USA
@cindex American Stock Exchange
@cindex AMEX
@tab American Stock Exchange (AMEX) @* @uref{http://www.amex.com}
@item

@item none @tab
@cindex New York Stock Exchange
@cindex NYSE
@tab New York Stock Exchange (NYSE) @* @uref{http://www.nyse.com}
@item

@item none @tab
@cindex NASDAQ
@tab NASDAQ @* @uref{http://www.nasdaq.com}
@item

@item
@cindex @code{.OB}
@nisamp{.OB}
@tab
@cindex Over the Counter
@cindex OTC
@tab Over the Counter (OTC) @* @uref{http://www.otcbb.com}
@item

@c @item @nisamp{.PK} @tab
@c @cindex @code{.PK}
@c @cindex Pink Sheets
@c @tab Pink Sheets @* @uref{http://www.pinksheets.com}
@c @item

@item @nisamp{.BA} @tab Argentina
@cindex @code{.BA}
@cindex Buenos Aires Stock Exchange
@cindex BCBA
@cindex Argentina
@tab Buenos Aires Stock Exchange (BCBA) @* @uref{http://www.bcba.sba.com.ar}
@item

@item @nisamp{.AX} @tab Australia
@cindex @code{.AX}
@cindex Australian Stock Exchange
@cindex Australia
@tab Australian Stock Exchange @* @uref{http://www.asx.com.au}
@item

@item @nisamp{.VI} @tab Austria
@cindex @code{.VI}
@cindex Wiener Borse
@cindex Austria
@tab Wiener Borse @* @uref{http://en.wienerborse.at}
@item

@item @nisamp{.SA}  @tab Brazil
@cindex @code{.SA}
@cindex Sao Paolo Stock Exchange
@cindex Brazil
@tab Sao Paolo Stock Exchange @* @uref{http://www.bovespa.com.br}

@item
@item @nisamp{.TO} @tab Canada
@cindex @code{.TA}
@cindex Toronto Stock Exchange
@cindex TSX
@cindex Canada
@tab Toronto Stock Exchange @* @uref{http://www.tsx.com}
@item

@item @nisamp{.V} @tab
@cindex @code{.V}
@cindex Toronto Venture
@cindex TSX Venture
@cindex Canada
@tab Toronto Stock Exchange Venture division @* @uref{http://www.tsx.com}
@item

@item @nisamp{.CO} @tab Denmark
@cindex @code{.CO}
@cindex Copenhagen Stock Exchange
@cindex Denmark
@tab Copenhagen Stock Exchange @* @uref{http://www.cse.dk}
@item

@item @nisamp{.PA} @tab France
@cindex @code{.PA}
@cindex Paris Stock Exchange
@cindex France
@tab Paris Stock Exchange (now part of Euronext)
@* @uref{http://www.euronext.com}
@item

@item @nisamp{.BE}  @tab Germany
@cindex @code{.BE}
@cindex Berlin Stock Exchange
@cindex Germany
@tab Berlin @* @uref{http://www.berlinerboerse.de}
@item

@item @nisamp{.BM} @tab
@cindex @code{.BM}
@cindex Bremen Stock Exchange
@cindex Germany
@tab Bremen @* @uref{http://www.berlinerboerse.de}
@item

@item @nisamp{.D} @tab
@cindex @code{.D}
@cindex Duesseldorf Stock Exchange
@cindex Germany
@tab Duesseldorf @* @uref{http://www.boerse-duesseldorf.de}
@item

@item @nisamp{.F} @tab
@cindex @code{.F}
@cindex Frankfurt Stock Exchange
@cindex Germany
@tab Frankfurt
@item

@item @nisamp{.H} @tab
@cindex @code{.H}
@cindex Hamburg Stock Exchange
@cindex Germany
@tab Hamburger Boerse @* @uref{http://www.hamburger-boerse.de}
@item

@item @nisamp{.HA} @tab
@cindex @code{.HA}
@cindex Hanover Stock Exchange
@cindex Germany
@tab Hanover
@item

@item @nisamp{.MU} @tab
@cindex @code{.MU}
@cindex Boerse Muenchen
@cindex Munich Stock Exchange
@cindex Germany
@tab Boerse Muenchen
@* @uref{http://www.boerse-muenchen.de}
@item

@item @nisamp{.SG} @tab
@cindex @code{.SG}
@cindex Boerse Stuttgart
@cindex Stuttgart Stock Exchange
@cindex Germany
@tab Stuttgart @* @uref{http://www.boerse-stuttgart.de}
@item

@item @nisamp{.DE} @tab
@cindex @code{.DE}
@cindex XETRA
@cindex Germany
@tab XETRA
@item

@item @nisamp{.HK} @tab Hong Kong
@cindex @code{.HK}
@cindex Hong Kong Stock Exchange
@cindex HKEX
@tab Hong Kong Stock Exchange @* @uref{http://www.hkex.com.hk}
@item

@item @nisamp{.BO} @tab India
@cindex @code{.BO}
@cindex Bombay Stock Exchange
@cindex BSE
@cindex India
@tab Bombay Stock Exchange (BSE) @* @uref{http://www.bseindia.com}
@item

@item @nisamp{.CL}  @tab
@cindex @code{.CL}
@cindex Calcutta Stock Exchange
@cindex CSE
@cindex India
@tab Calcutta Stock Exchange (CSE) @* @uref{http://www.cse-india.com}
@item

@item @nisamp{.NS}  @tab
@cindex @code{.NS}
@cindex National Stock Exchange of India
@cindex India, National Stock Exchange
@cindex NSE
@tab National Stock Exchange of India (NSE) @* @uref{http://www.nseindia.com}
@item

@item @nisamp{.JK}  @tab Indonesia
@cindex @code{.JK}
@cindex Jakarta Stock Exchange
@cindex Indonesia
@tab Jakarta Stock Exchange @* @uref{http://www.idx.co.id/}
@item

@item @nisamp{.MI}  @tab Italy
@cindex @code{.MI}
@cindex Italian Stock Exchange
@cindex Borsa Italiana
@tab Italian Stock Exchange (Borsa Italiana) @*
@uref{http://www.borsaitaliana.it/homepage/homepage.en.htm}
@item

@item @nisamp{.KS}  @tab Korea
@cindex @code{.KS}
@cindex Korean Stock Exchange
@cindex KRX
@tab Korean Stock Exchange @* @uref{http://eng.krx.co.kr}
@item

@item @nisamp{.KQ}  @tab
@cindex @code{.KQ}
@cindex KOSDAQ
@cindex Korea
@tab KOSDAQ @* @uref{http://eng.krx.co.kr/abk/abk_d_025.jsp}
@item

@item @nisamp{.KL} @tab Malaysia
@cindex @code{.KL}
@cindex Kuala Lumpur Stock Exchange
@cindex KLSE
@cindex Malaysia
@tab Kuala Lumpur Stock Exchange (KLSE) @* @uref{http://www.klse.com.my}
@item

@item @nisamp{.MX} @tab Mexico
@cindex @code{.MX}
@cindex Bolsa Mexicana de Valores
@cindex Mexico Stock Exchange
@tab Mexico Stock Exchange (Bolsa Mexicana de Valores)
@* @uref{http://www.bmv.com.mx}
@item

@item @nisamp{.AS} @tab Netherlands
@cindex @code{.AS}
@cindex Amsterdam Stock Exchange
@cindex Netherlands
@tab Amsterdam Stock Exchange (now part of Euronext)
@uref{http://www.euronext.com}
@item

@item @nisamp{.NZ} @tab New Zealand
@cindex @code{.NZ}
@cindex New Zealand Stock Exchange
@cindex New Zealand
@tab New Zealand Stock Exchange @* @uref{http://www.nzx.com} @* and see
@ref{New Zealand Stock Exchange}
@item

@item @nisamp{.OL} @tab Norway
@cindex @code{.OL}
@tab Oslo Stock Exchange
@cindex Oslo Stock Exchange
@cindex Oslo Bors
@cindex Norway
@* @uref{http://www.oslobors.no/ob_eng/}

@item
@item @nisamp{.SI} @tab Singapore
@cindex @code{.SI}
@cindex Singapore Stock Exchange
@cindex SGX
@tab Singapore Stock Exchange (SGX) @* @uref{http://www.sgx.com}

@item
@item @nisamp{.BC} @tab Spain
@cindex @code{.BC}
@cindex Barcelona Stock Exchange
@cindex Bolsa de Barcelona
@cindex Spain
@tab Barcelona Stock Exchange (Bolsa de Barcelona)
@uref{http://www.borsabcn.es}
@c The english home page is
@c     http://www.borsabcn.es/bolsabcn/navegacion.nsf/vweb/p_eng?OpenDocument
@c but that url is a bit too long and crazy to want to include here.

@item
@item @nisamp{.BI} @tab
@cindex @code{.BI}
@cindex Bilbao Stock Exchange
@cindex Bolsa de Bilbao
@cindex Spain
@tab Bilbao Stock Exchange (Bolsa de Bilbao) @uref{http://www.bolsabilbao.es}

@item
@item @nisamp{.MA} @tab
@cindex @code{.MA}
@cindex Madrid Stock Exchange @uref{http://www.bolsamadrid.es}
@cindex Spain
@tab Madrid

@item
@item @nisamp{.MC} @tab
@cindex @code{.MC}
@tab Madrid CATS

@item
@item @nisamp{.MF} @tab
@cindex @code{.MF}
@tab Madrid fixed income

@item
@item @nisamp{.ST}
@cindex @code{.ST}
@cindex Stockholm Stock Exchange
@cindex Sweden
@tab Sweden @tab Stockholm

@item
@item @nisamp{.SW} @tab Switzerland
@cindex @code{.SW}
@cindex Swiss Exchange
@cindex SWX
@tab Swiss Exchange (SWX) @* @uref{http://www.swx.com}

@item
@item @nisamp{.VX} @tab
@cindex @code{.VX}
@cindex Virt-X Exchange
@tab Virt-X (part of the SWX Group) @* @uref{http://www.virt-x.com}

@item
@item @nisamp{.TW}  @tab Taiwan
@cindex @code{.TW}
@cindex Taiwan Stock Exchange
@cindex TSE
@tab Taiwan Stock Exchange @* @uref{http://www.tse.com.tw/docs/eng_home.htm}

@item
@item @nisamp{.TWO} @tab
@cindex @code{.TWO}
@cindex Taiwan OTC
@cindex OTC, Taiwan
@tab Taiwan OTC

@item
@item @nisamp{.L} @tab UK
@cindex @code{.L}
@cindex London Stock Exchange
@cindex LSE
@tab London Stock Exchange (LSE) @* @uref{http://www.londonstockexchange.com}

@item
@item @nisamp{.IL} @tab
@cindex @code{.IL}
@cindex International Order Book
@cindex IOB
@tab London Stock Exchange International Order Book (IOB) @*
@uref{http://www.londonstockexchange.com/iob}

@end multitable
@end quotation



@c ---------------------------------------------------------------------------
@node Internationalization, Emacs, Data Sources, Top
@chapter Internationalization
@cindex Internationalization
@cindex Localization
@cindex Preferences, locale

Chart is written in English, but has support for various localizations,
selected by the usual system mechanisms.

@table @asis
@item Numbers
@cindex Decimal point
@cindex Thousands character
Numbers are shown with the locale decimal point and thousands separator.  You
can also customize these in your @file{init.pl}.

@item Dates
@cindex Date format
Dates are shown in the locale format, or the usual C language default is
@samp{mm/dd/yy}.  You can also customize this in your @file{init.pl} to set a
personal preference, like the month as a name instead of a number.

@item Messages
@cindex Message translations
@cindex Translations, messages
Message strings are translated into the selected language, when a translation
is available.  Gtk has a good set of translations for the standard menus and
dialogs, but for Chart specifics there's almost nothing yet.
@c
@c @item
@c @cindex Gettext
@c Gettext (@CHARTpxreftop{gettext, GNU @command{gettext} utilities}). @*
@c @uref{http://www.gnu.org/software/gettext/}

@item Stock and commodity names
@cindex Stock name translations
@cindex Commodity name translations
@cindex Name translations
@cindex Weblink
Names are downloaded in the selected or highest preference language, when
there's a choice.  Weblinks to company information or the exchange home page
likewise.

@item Annotations
@cindex Annotation locale
@cindex UTF-8
Annotation notes (@pxref{Annotations}) can be entered with unicode characters.

@c , Dividends
@c and dividends (@pxref{Dividends}) ...
@end table

@c @ifinfo
@c @sp 1
@c @end ifinfo
@section Locale Selection
@cindex Locale selection

@cindex Language
@cindex @env{LANG}
On a typical Unix/POSIX-style system the locale is selected with the
@env{LANG} environment variable, set to a language code and optional territory
and charset.  For example US English,

@example
LANG=en_US
export LANG
@end example

This is often set by the system administrator, but you can do it yourself in
your @file{~/.profile} (@pxref{Bash Startup Files,,, bashref, Bash Features}).

@cindex Language codes
@cindex Country codes
Language and country codes can be found in @ref{Language Codes,,, gettext, GNU
@command{gettext} utilities}, and @ref{Country Codes,,, gettext, GNU
@command{gettext} utilities}.  Usually there's only a few combinations
available on a system, run @samp{locale -a} to see them.

@cindex @env{LANGUAGE}
Additionally, on a GNU system the @env{LANGUAGE} environment variable gives a
list of language preferences for message translations (@pxref{Using
gettextized software,, User influence on @code{gettext}, libc, GNU C Library
Reference Manual}).  For example to have Italian preferred, otherwise Spanish,
otherwise English,

@example
LANGUAGE=it_IT:es:en
export LANGUAGE
@end example

Chart looks at @env{LANGUAGE} too (on all systems) for the preferred language
for stock and commodity names.


@c ---------------------------------------------------------------------------
@node Emacs, Concept Index, Internationalization, Top
@chapter Emacs
@cindex Emacs

@uref{http://www.gnu.org/software/emacs/}

@cindex @file{chartprog.el}
@cindex XEmacs
@file{chartprog.el} shows the Chart watchlist and gets quotes within Emacs
(@CHARTpxreftop{emacs, The Emacs Editor}).  It's designed for Emacs 21 and
higher, and also works with XEmacs 21 if you have the UTF-8 coding system (see
below).

@cindex Autoload @file{chartprog.el}
@cindex @file{chartprog-loaddefs.el}
@cindex @file{.emacs}
The Debian package has the following setups already.  Otherwise, the best way
to use @file{chartprog.el} is with autoloads for the commands.
@file{chartprog-loaddefs.el} is a small file which sets this up.  Add the
following to your @file{.emacs} file (@pxref{Init File,, The Init File
@file{~/.emacs}, emacs, The Emacs Editor}),

@lisp
(require 'chartprog-loaddefs)
@end lisp

@cindex @code{load-path}
@cindex @code{site-lisp}
The build system currently doesn't install @file{chartprog.el} into
@file{site-lisp}, so you should copy it and @file{chartprog-loaddefs.el} to
somewhere in your @code{load-path} (@pxref{Lisp Libraries,, Libraries of Lisp
Code for Emacs, emacs, The Emacs Editor}).

@c If Chart isn't installed in a standard location you'll need to add its lisp
@c directory (@file{$prefix/share/emacs/site-lisp}) to your Emacs
@c @code{load-path} 



@section Watchlist and Quotes

@findex @code{chart-watchlist}
@kbd{M-x chart-watchlist} displays the Favourites list in a buffer.  Key
@key{a} adds a symbol.  @kbd{C-k} and @kbd{C-y} kill and yank symbols.
@key{g} refreshes the quotes.  @key{L} selects a different list (like the
Alerts list).  The usual @kbd{C-h m} mode help shows other key bindings.

Chart communicates changes to the lists between the Emacs display and a
running Chart GUI@.  So if you have both open then changes in one are
reflected in the other a moment later.

@findex @code{chart-quote}
@kbd{M-x chart-quote} displays a quote for a given symbol in the message area.
It prompts for the symbol with default a symbol at point.  @key{Tab}
completion is available (@pxref{Completion,,, emacs, The Emacs Editor}) using
the database symbols, favourites list, and previously requested symbols.

@findex @code{chart-quote-at-point}
@kbd{M-x chart-quote-at-point} displays a quote for the symbol at point,
without prompting.

The language, date formats, etc, follow the Chart locale selection described
in @ref{Internationalization}.  Emacs @kbd{M-x set-language-environment} and
other Emacs setups don't influence the display.


@section UTF-8
@cindex Asian characters in Emacs
@cindex XEmacs UTF-8

UTF-8 is used in Emacs, the same as in the Gtk GUI display.  This is easiest
to implement, and should mean whatever is seen in the GUI can be seen in
Emacs.

@table @asis
@cindex MULE-UCS
@item Emacs 21
If you use an Asian locale then you probably know Emacs 21 has limited support
for Asian parts of UTF-8.  The typical symptom is @samp{\207}, @samp{\221} etc
in the display.  Install the MULE-UCS package to add to the builtin
characters: @uref{http://www.m17n.org}

@item XEmacs 21
If you use XEmacs 21 you probably know it has no builtin UTF-8.  To run
@code{chartprog.el} you must get one of the add-ons providing that.  MULE-UCS
is recommended (@uref{http://www.m17n.org}), and @code{chartprog.el} will
attempt to load it automatically.
@end table


@section Lisp
@cindex Lisp

@defun chart-latest symbol &optional field scale
Return the latest price for @var{symbol} (a string) from Chart.  If there's no
information available (an unknown stock, not online, nothing cached, etc) the
return is @code{nil}.

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

@var{field} is a lisp symbol for what data to return.  The default is
@code{last} which is the last traded price.  The fields are

@example
name                        string or nil
bid offer                   \ prices or nil
open high low last change   /
quote-date last-date        string like "2012-12-31", or nil
quote-time last-time        string like "16:59:59", or nil
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:
