Fourier Moving Average

View as Markdown

Indicator Tutorial 9

Tradovate Trader includes some third-party libraries that can be helpful for indicators.

Lodash is a very popular and high-performance library to work with arrays and objects. All you need to do is to include const lodash = require("lodash") in your module.

Another is a library for Fast Fourier Transform. Here is an example of how to apply this library to build a moving average that calculated as FFT of input data, a filter of high frequencies, and inverse FFT.

1const predef = require("./tools/predef");
2const FFT = require("fft");
3
4class fourierMA {
5 init() {
6 const period = this.props.period;
7 this.fft = FFT(period);
8 this.signal = new Array(period);
9 this.zero = new Array(period);
10 for(let i=0; i<period; ++i) {
11 this.zero[i] = 0.0;
12 }
13 this.lastIndex = -1;
14 }
15
16 map(d, index) {
17 const period = this.props.period;
18 const value = d.value();
19
20 if (index < period) {
21 this.signal[period - index - 1] = value;
22 }
23 else {
24 if (this.lastIndex < index) {
25 this.signal.pop();
26 this.signal.unshift(value);
27 }
28 else {
29 this.signal[0] = value;
30 }
31 }
32
33 this.lastIndex = index;
34
35 if (index >= period) {
36 const re = [].concat(this.signal);
37 const im = [].concat(this.zero);
38 this.fft.fft1d(re, im);
39
40 const middle = period / 2 + 1;
41 const startFreq = this.props.filterFreqStart;
42 for(let i=startFreq; i<middle; ++i) {
43 re[i] = im[i] = 0.0;
44 re[period - i] = im[period - i] = 0.0;
45 }
46 this.fft.ifft1d(re, im);
47
48 return re[0];
49 }
50 }
51}
52
53module.exports = {
54 name: "fourierMA",
55 description: "Fourier MA",
56 calculator: fourierMA,
57 params: {
58 period: predef.paramSpecs.period(64),
59 filterFreqStart: predef.paramSpecs.period(16),
60 },
61 tags: ["My Indicators"],
62};

FFT MA