Moving Average Convergence/Divergence

Technical Analysis Indicator: macd

Fork me on GitHub

Function Prototype

/* Moving Average Convergence/Divergence */
/* Type: indicator */
/* Input arrays: 1    Options: 3    Output arrays: 3 */
/* Inputs: real */
/* Options: short period, long period, signal period */
/* Outputs: macd, macd_signal, macd_histogram */
int ti_macd_start(TI_REAL const *options);
int ti_macd(int size,
      TI_REAL const *const *inputs,
      TI_REAL const *options,
      TI_REAL *const *outputs);

Description

This documentation is still a work in progress. It has omissions, and it probably has errors too. If you see any issues, or have any general feedback, please get in touch.

Moving Average Convergence/Divergence helps follow trends and has several uses.

It takes three parameter, a short period n, a long period m, and a signal period p.

Moving Average Convergence/Divergence is calculated as follows.

$$short_{t} = ema(n, input)$$
$$long_{t} = ema(m, input)$$
$$macd_{t} = short_{t} - long_{t}$$
$$signal_{t} = ema(p, macd_{t})$$
$$histogram_{t} = macd_{t} - signal_{t}$$

For historical reasons, if n is 12 and m is 26, then the Exponential Moving Average scaling factors are adjusted from 0.1538 and 0.0740 to 0.1500 and 0.0750 respectively.

See Also

References

Example Usage

Calling From C

/* Example usage of Moving Average Convergence/Divergence */
/* Assuming that 'input' is a pre-loaded array of size 'in_size'. */
TI_REAL *inputs[] = {input};
TI_REAL options[] = {2, 5, 9}; /* short period, long period, signal period */
TI_REAL *outputs[3]; /* macd, macd_signal, macd_histogram */

/* Determine how large the output size is for our options. */
const int out_size = in_size - ti_macd_start(options);

/* Allocate memory for each output. */
outputs[0] = malloc(sizeof(TI_REAL) * out_size); assert(outputs[0] != 0); /* macd */
outputs[1] = malloc(sizeof(TI_REAL) * out_size); assert(outputs[1] != 0); /* macd_signal */
outputs[2] = malloc(sizeof(TI_REAL) * out_size); assert(outputs[2] != 0); /* macd_histogram */

/* Run the actual calculation. */
const int ret = ti_macd(in_size, inputs, options, outputs);
assert(ret == TI_OKAY);

Calling From Lua (with Tulip Chart bindings)

-- Example usage of Moving Average Convergence/Divergence
macd, macd_signal, macd_histogram = ti.macd(input, 2, 5, 9)

Example Calculation

short period = 2, long period = 5, signal period = 9

dateinputmacdmacd_signalmacd_histogram
2005-11-0181.59
2005-11-0281.06
2005-11-0382.87
2005-11-0483.00
2005-11-0783.610.620.620.00
2005-11-0883.150.350.56-0.21
2005-11-0982.840.110.47-0.36
2005-11-1083.990.420.46-0.05
2005-11-1184.550.580.490.09
2005-11-1484.360.420.47-0.05
2005-11-1585.530.680.520.17
2005-11-1686.540.930.600.33
2005-11-1786.890.890.660.24
2005-11-1887.770.980.720.26
2005-11-2187.290.620.70-0.08

Chart

 

Other Indicators

Previous indicator: Vector Base-10 Log

Next indicator: Market Facilitation Index

Random indicator: Parabolic SAR