Search This Blog

Saturday, March 31, 2012

R: Moving Averages Time series


MovingAverages {TTR}R Documentation

Moving Averages

Description

Calculate various moving averages (MA) of a series.

Usage

  SMA(x, n=10)
  EMA(x, n=10, wilder=FALSE)
  WMA(x, n=10, wts=1:n)
 DEMA(x, n=10)
EVWMA(price, volume, n=10)
ZLEMA(x, n=10)

Arguments

x Vector to be averaged.
price Vector of prices to be averaged.
volume Volume series corresponding to price series, or a constant. See Notes.
n Number of periods to average over.
wts Vector of weights. Length of wts vector must equal the length of x, or n (the default).
wilder logical; if TRUE, a Welles Wilder type EMA will be calculated; see notes.

Details

SMA calculates the arithmetic mean of the series over the past n observations.
EMA calculates an exponentially-weighted mean, giving more weight to recent observations. See Warning section below.
WMA is similar to an EMA, but with linear weighting, if the length of wts is equal to n. If the length of wts is equal to the length of x, the WMA will the values of wts as weights.
DEMA is calculated as: DEMA = 2 * EMA(x,n) - EMA(EMA(x,n),n).
EVWMA uses volume to define the period of the MA.
ZLEMA is similar to an EMA, as it gives more weight to recent observations, but attempts to remove lag by subtracting data prior to (n-1)/2 periods to minimize the cumulative effect.

Value

SMA Simple moving average.
EMA Exponential moving average.
WMA Weighted moving average.
DEMA Double-exponential moving average.
EVWMA Elastic, volume-weighted moving average.
ZLEMA Zero lag exponential moving average.

Warning

Some indicators (e.g. EMA, DEMA, EVWMA, etc.) are calculated using the indicators' own previous values, and are therefore unstable in the short-term. As the indicator receives more data, its output becomes more stable. See example below.

Note

For EMA, wilder=FALSE (the default) uses an exponential smoothing ratio of 2/(n+1), while wilder=TRUE uses Welles Wilder's exponential smoothing ratio of 1/n.
Since WMA can accept a weight vector of length equal to the length of x or of length n, it can be used as a regular weighted moving average (in the case wts = 1:n) or as a moving average weighted by volume, another indicator, etc.
For EVWMA, if volume is a series, n should be chosen so the sum of the volume for n periods approximates the total number of outstanding shares for the security being averaged. If volume is a constant, it should represent the total number of outstanding shares for the security being averaged.

Author(s)

Josh Ulrich

References

The following site(s) were used to code/document this indicator:
http://www.fmlabs.com/reference/ExpMA.htm
http://www.fmlabs.com/reference/WeightedMA.htm
http://www.fmlabs.com/reference/DEMA.htm
http://linnsoft.com/tour/techind/evwma.htm
http://www.fmlabs.com/reference/ZeroLagExpMA.htm

See Also

See wilderSum, which is used in calculating a Welles Wilder type MA.

Examples

  data(ttrc)
    ema.20 <-   EMA(ttrc[,"Close"], 20)
    sma.20 <-   SMA(ttrc[,"Close"], 20)
   dema.20 <-  DEMA(ttrc[,"Close"], 20)
  evwma.20 <- EVWMA(ttrc[,"Close"], 20)
  zlema.20 <- ZLEMA(ttrc[,"Close"], 20)

  ## Example of short-term instability of EMA
  x <- rnorm(100)
  tail( EMA(x[90:100],10), 1 )
  tail( EMA(x[70:100],10), 1 )
  tail( EMA(x[50:100],10), 1 )
  tail( EMA(x[30:100],10), 1 )
  tail( EMA(x[10:100],10), 1 )
  tail( EMA(x[ 1:100],10), 1 )

[Package TTR version 0.13 Index]

Defining your own Control Sequences in LaTeX

Defining your own Control Sequences in LaTeX

Suppose that we are producing a paper that makes frequent use of some mathematical expression. For example, suppose that integrals like
[GIF Image]
occur frequently throughout the text. This formula is obtained by typing
\[ \int_{-\infty}^{+\infty} f(x)\,dx.\] 
It would be nice if we could type \inftyint (say) to obtain the integral sign at the beginning. This can be done using \newcommand. What we do is to place a line with the command
\newcommand{\inftyint}{\int_{-\infty}^{+\infty}}
near the beginning of the input file (e.g., after the \documentclass command but before the \begin{document} command). Then we only have to type
\[ \inftyint f(x)\,dx.\] 
to obtain the above formula. We can modify this procedure slightly. Suppose that we we defined a new control sequence \intwrtx by putting the line
\newcommand{\intwrtx}[1]{\int_{-\infty}^{+\infty} #1 \,dx}
at the beginning of the input file. If we then type the line
\[ \intwrtx{f(x)}.\] 
then we obtain
[GIF Image]
What has happened is that the expression in braces after \intwrtx has been substituted in the expression defining \intwrtx, replacing the #1 in that expression. The number 1 inside square brackets in the \newcommand line defining \intwrtx indicates to LaTeX that it is to expect one expression (in braces) after \intwrtx to substitute for #1 in the definition of \intwrtx. If we defined a control sequence \intwrt by
\newcommand{\intwrt}[2]{\int_{-\infty}^{+\infty} #2 \,d #1}
then it would expect two expressions to substitute in for #1 and #2 in the definition of \intwrt. Thus if we then type
\[ \intwrt{y}{f(y)}.\] 
we obtain
[GIF Image]

LaTeX Command Words


LaTeX Command Words

a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z

A

Goto the top

B, C

Goto the top

D

Goto the top

E, F

Goto the top

G, H

Goto the top

I, J

Goto the top

K, L

Goto the top

M

Goto the top

N

Goto the top

O, P

Goto the top

Q, R

Goto the top

S

Goto the top

T

Goto the top

U, V, W, X, Y, Z

Goto the top Back to the main LaTeX page.

LaTeX:Commands

LaTeX:Commands

LaTeX
About - LaTeX on AoPS - Downloads - Basics - Math - Examples - Pictures - Layout - Symbols - Commands - Packages - Help
This page introduces various useful commands for rendering math in LaTeX, as well as instructions for building your own commands.

Contents

[hide]

Math Commands

Here are some commonly used math commands in LaTeX.

Exponents and Subscripts

Make exponents in LaTeX with ^ and subscripts with _ as shown in the examples below.
Symbol CommandSymbolCommand
2^{2}2^2\textstyle a_ia_i
\textstyle 2^{23}2^{23}\textstyle n_{i-1}n_{i-1}
a^{i+1}_3a^{i+1}_3x^{3^2}x^{3^2}
2^{a_i}2^{a_i}2^a_i2^a_i
Notice that we can apply both a subscript and an exponent at the same time, and that we can use {} to tell LaTeX what to apply a subscript or exponent to (compare the examples on the bottom row).
Finally, notice that we use {} for any exponent or subscript that is more than one character. You have to do so, or you'll end up with 2^234 or a^i+1_n-1 when you really want 2^{234} or a^{i+1}_{n-1}.

Fractions

SymbolCommand
\textstyle \frac{1}{2}\frac{1}{2}
\textstyle \frac{2}{x+2}\frac{2}{x+2}
\textstyle \frac{1+\frac{1}{x}}{3x + 2}\frac{1+\frac{1}{x}}{3x + 2}
Most fractions look better in (remember, you don't need the declaration if you are in \[...\] or $$...$$ mode.) You can use \dfrac as a shortcut:
Symbol Command
\frac{1}{2}\dfrac{1}{2}
\frac{2}{x+2}\dfrac{2}{x+2}
\frac{1+\frac{1}{x}}{3x + 2}\dfrac{1+\frac{1}{x}}{3x + 2}
Use \cfrac for continued fractions:
Symbol Command
\cfrac{2}{1+\cfrac{2}{1+\cfrac{2}{1+\cfrac{2}{1}}}}\cfrac{2}{1+\cfrac{2}{1+\cfrac{2}{1+\cfrac{2}{1}}}}

Radicals

Symbol Command
\sqrt{2}\sqrt{2}
\sqrt{x+y}\sqrt{x+y}
\sqrt{x+\frac{1}{2}}\sqrt{x+\frac{1}{2}}
\sqrt[3]{3}\sqrt[3]{3}
\sqrt[n]{x}\sqrt[n]{x}

Sums, Products, Limits and Logarithms

We use _ to get the 'bottom' parts of summations, products, and limits, as well as the subscripts of logarithms. We use ^ to get the 'top' parts of sums and products. (Integration symbols work the same way, as you'll see in the calculus section.) Click here for a few other commands which take 'bottom' parts.
Symbol Command
\textstyle \sum_{i=1}^{\infty}\frac{1}{i}\sum_{i=1}^{\infty}\frac{1}{i}
\textstyle \prod_{n=1}^5\frac{n}{n-1}\prod_{n=1}^5\frac{n}{n-1}
\textstyle \lim_{x\to\infty}\frac{1}{x}\lim_{x\to\infty}\frac{1}{x}
\textstyle \log_n n^2\log_n n^2
Some of these are prettier in display mode:
Symbol Command
\sum_{i=1}^{\infty}\frac{1}{i}\sum_{i=1}^{\infty}\frac{1}{i}
\prod_{n=1}^5\frac{n}{n-1}\prod_{n=1}^5\frac{n}{n-1}
\lim_{x\to\infty}\frac{1}{x}\lim_{x\to\infty}\frac{1}{x}
Note that we can use sums, products, and logarithms without _ or ^ modifiers.
Symbol Command
\sum\frac{1}{i}\sum\frac{1}{i}
\frac{n}{n-1}\frac{n}{n-1}
\textstyle \log n^2\log n^2
\textstyle \ln e\ln e

Mods

Symbol Command
9\equiv 3 \bmod{6}9\equiv 3 \bmod{6}
9\equiv 3 \pmod{6}9\equiv 3 \pmod{6}
9\equiv 3 \mod{6}9\equiv 3 \mod{6}
9\equiv 3\pod{6}9\equiv 3 \pod{6}

Combinations

Symbol Command
\scriptstyle\binom{9}{3}\binom{9}{3}
\scriptstyle\binom{n-1}{r-1}\binom{n-1}{r-1}
These often look better in display mode:
Symbol Command
\dbinom{9}{3}\dbinom{9}{3}
\dbinom{n-1}{r-1}\dbinom{n-1}{r-1}

Trigonometric Functions

SymbolCommandSymbolCommandSymbolCommand
\textstyle \cos\cos\textstyle \sin\sin\textstyle \tan\tan
\sec\sec\textstyle \textstyle \csc\csc\textstyle \cot\cot
\textstyle \arccos\arccos\textstyle \arcsin\arcsin\textstyle \arctan\arctan
\textstyle \cosh\cosh\textstyle \sinh\sinh\textstyle \tanh\tanh
\textstyle \coth\coth
Here are a couple examples:
Symbol Command
\textstyle \cos^2 x +\sin^2 x = 1\cos^2 x +\sin^2 x = 1
\cos 90^\circ = 0\cos 90^\circ = 0

Calculus

Below are examples of calculus rendered in LaTeX. Most of these commands have been introduced before. Notice how definite integrals are rendered (and the difference between regular math and display mode for definite integrals). The , in the integrals makes a small space before the dx.
Symbol Command
\frac{d}{dx}\left(x^2\right) = 2x\frac{d}{dx}\left(x^2\right) = 2x
\int 2x\,dx = x^2+C\int 2x\,dx = x^2+C
\int^5_1 2x\,dx = 24\int^5_1 2x\,dx = 24
\int^5_1 2x\,dx = 24\int^5_1 2x\,dx = 24
\frac{\partial^2U}{\partial x^2} + \frac{\partial^2U}{\partial y^2}\frac{\partial^2U}{\partial x^2} + \frac{\partial^2U}{\partial y^2}
\frac{1}{4\pi}\oint_\Sigma\frac{1}{r}\frac{\partial U}{\partial n} ds\frac{1}{4\pi}\oint_\Sigma\frac{1}{r}\frac{\partial U}{\partial n} ds

Overline and Underline

Symbol Command
\overline{a+bi}\overline{a+bi}
\underline{431}\underline{431}

Other Functions

Symbol CommandSymbol CommandSymbol Command
\arg\arg\textstyle\deg\deg\textstyle\det\det
\dim\dim\textstyle\exp\exp\textstyle\gcd\gcd
\hom\hom\inf\inf\ker\ker
\textstyle\lg\lg\liminf\liminf\limsup\limsup
\textstyle\max\max\textstyle\min\min\Pr\Pr
\sup\sup
Some of these functions take 'bottom' parts just like sums and limits. Some render differently in display mode and regular math mode.
Symbol CommandSymbol CommandSymbol Command
\dim_x\dim_x\textstyle\gcd_x\gcd_x\inf_x\inf_x
\liminf_x\liminf_x\limsup_x\limsup_x\textstyle\max_x\max_x
\textstyle\min_x\min_x\Pr_x\Pr_x\sup_x\sup_x

Matrices

We can build an array or matrix with the \begin{array} command, and use \left and \right to properly size the delimiters around the matrix:
The characteristic polynomial $f(\lambda)$ of the
$3 \times 3$ matrix
\[
\left(
\begin{array}{ccc}
a & b & c \\
d & e & f \\
g & h & i \end{array}
\right)\]
is given by the equation
\[ f(\lambda)
= \left|
\begin{array}{ccc}
\lambda - a & -b & -c \\
-d & \lambda - e & -f \\
-g & -h & \lambda - i \end{array}
\right|.\]

More simply, we can use the shortcut commands in the amsmath package:
The characteristic polynomial $f(\lambda)$ of the
$3 \times 3$ matrix
\[
\begin{pmatrix}
a & b & c \\
d & e & f \\
g & h & i
\end{pmatrix} \]
is given by the equation
\[ f(\lambda)
= \begin{vmatrix}
\lambda - a & -b & -c \\
-d & \lambda - e & -f \\
-g & -h & \lambda - i
\end{vmatrix}.\]
You can read more about how the array command works here (it works the same as tabular) and more about using \left and \right here.
We can also use this environment to typeset any mathematics that calls for multiple columns, such as funky function definitions like this one:
\[ f(x) = \left\{ \begin{array}{ll}
x+7 & \mbox{if $5< x$};\\
x^2-3 & \mbox{if $-3 \le x \le 5$};\\
-x & \mbox{if $x < -3$}.\end{array} \right. \]
But it would be better to use the cases environment and \text command that the amsmath package provides:
\[ 
f(x) = \begin{cases}
x+7 & \text{if $5< x$}; \\
x^2-3 & \text{if $-3 \le x \le 5$};\\
-x & \text{if $x < -3$}.
\end{cases}
\]

Text Styles in Math Mode

You can render letters in various styles in math mode. Below are examples; you should be able to use these with any letters. The \mathbb requires the amsfonts package to be include in your document's preamble.
Symbol CommandSymbol CommandSymbol CommandSymbol Comand
\mathbb{R}\mathbb{R}\mathbf{R}\mathbf{R}\mathcal{R}\mathcal{R}\mathfrak{R}\mathfrak{R}
Mathbb1.gif\mathbb{Z}\mathbf{Z}\mathbf{Z}\mathcal{Z}\mathcal{Z}\mathfrak{Z}\mathfrak{Z}
\mathbb{Q}\mathbb{Q}\mathbf{Q}\mathbf{Q}\mathcal{Q}\mathcal{Q}\mathfrak{Q}\mathfrak{Q}
If you're persistent, you can dig a few more out of this document.
If you want to drop a little bit of text in the middle of math mode, you can use the \text command. The \text command is most useful in $$...$$ or $...$ mode, where breaking up the math mode would force the output on to a new line entirely. So
$$n^2 + 5 = 30\text{ so we have }n=\pm5$$
gives
Text1.gif

How to Build Your Own Commands

The command \newcommand is used to create your own commands. We'll start with an example:
\documentclass[11pt]{article}
\usepackage{amsmath}

\pdfpagewidth 8.5in
\pdfpageheight 11in
\newcommand{\reci}[1]{\frac{1}{#1}}
\newcommand{\hypot}[2]{\sqrt{#1^2+#2^2}}
\newcommand{\cbrt}[1]{\sqrt[3]{#1}}

\begin{document}

The reciprocal of 2 is $\reci{2}$.

The hypotenuse has length $\hypot{3}{4}$.

I'm sick of writing `$\backslash$sqrt[3]{2}' all the time, just to get $\cbrt{2}$.

\end{document}
The \newcommand declarations are in the preamble. Each is of the form
\newcommand{name of new command}[number of arguments]{definition}
The name of the new command, which must begin with a \, is the name you'll use in the document to use the command. The number of arguments is how many inputs will be sent to the command. The definition is just normal LaTeX code, with #1, #2, #3, etc., placed where you want the inputs to go when the new command is called.
New commands can be used for all sorts of purposes, not just for making math commands you'll use a lot easier to call. For example, try this:
\documentclass[11pt]{article}
\usepackage{amsmath}

\pdfpagewidth 8.5in
\pdfpageheight 11in
\newcounter{prob_num}
\setcounter{prob_num}{1}
\newcommand{\prob}[5]{\bigskip \bigskip\arabic{prob_num}.\stepcounter{prob_num} #1
\par\nopagebreak[4]\medskip A.\ #2\hfill B.\ #3\hfill
C.\ #4\hfill D.\ #5\hfill E.\ NOTA}

\begin{document}

\prob{What is $2+2$?}{4}{5}{6}{7}

\prob{What is $\sqrt{100}$?}{81}{10}{9}{1}

\prob{Evaluate $\displaystyle\sum_{n=1}^\infty \frac{1}{n^2}$.}
{$\displaystyle\frac{1}{e}$} {$\displaystyle\frac{2}{\pi}$}
{$\displaystyle\frac{\pi^3}{8}$} {$\displaystyle\frac{\pi^2}{6}$}

\end{document}
In the example above, we create a new command called \prob. Each time we call \prob, we supply 5 arguments, one for the question and one for each of the multiple choices.
In the preamble and the definition of \prob, you'll see a few new LaTeX commands:
\newcounter{prob_num} creates a counter variable called prob_num
\setcounter{prob_num}{1} setsprob_num to equal 1.
In the definition of \prob, the \bigskip and \medskip commands create vertical space.
\arabic{prob_num} prints out the current value of the counter prob_num as an arabic numeral.
\stepcounter{prob_num} increments the counter prob_num by 1.
\nopagebreak[4] tells LaTeX not to break the page between the problem and the choices unless it really, really, really has to.
The \hfill commands put roughly equal space between the choices.
Once you build a body of custom commands that you will be using in many LaTeX documents, you should learn about creating your own package so you don't have to copy all your custom commands from document to document.

See Also