Jonathan Shobrook
Jonathan Shobrook

Reputation: 229

How to calculate the EMA of an array of numbers?

I have an array of daily closing prices for a stock (historical data) formatted as such:

var close = [39, 40.133, 38.23, .... , 45.38] 

these are in order chronologically by date. I am trying to make an array of EMA (exponential moving average) values of the closing price to correlate with the date chronologically.

I’m doing this in nodejs; any help would be greatly appreciated!

P.S. Here is something that I've tried:

var gauss = require('gauss');

var test = [39, 40.133, 38.23, 45.38, 43.83, 42.1, 48, 47, 44.12, 44.33, 46.9];
var vec = test.toVector();
var ma = vec.ema(10);

console.log(ma); // Outputs [ 43.2123, 43.88279090909091 ]

Why does it output this?

Upvotes: 2

Views: 2706

Answers (1)

Rodrigo Setti
Rodrigo Setti

Reputation: 180

The ema function returns a vector of the EMA of the previous N points. In your code, N is 10, and since your input vector test has 11 elements, it's possible to calculate 2 moving averages.

You can think of a moving average as a "window" of size N (10, in this case) that slides through your input vector. Starting from the last N elements, calculate the EMA, and then slide one element to the left, calculate, and keep doing until the window cannot move anymore (by reaching the beginning of the stream). In this case, the window can only move once, thus resulting in two averages.

[39, 40.133, 38.23, 45.38, 43.83, 42.1, 48, 47, 44.12, 44.33, 46.9];
     -----------------------------> 43.88279090909091 <-----------
 ----------------> 43.2123 <--------------------------------

See the documentation for more details: https://github.com/wayoutmind/gauss#vectorema

Upvotes: 1

Related Questions