指数移動平均を作る


ver1.8.4.0よりカスタムインジケーター作成とストレタジーテスターは個人利用データ使用時のみ可能になりました。 FXCM配信データを使っている場合はご利用いただけません。

概要

指数移動平均(ema)の作成方法を説明します。単純移動平均を作るの理解を前提にしています。

emaの計算方法は下記です。

初日の計算 単純移動平均の値を採用
2日目以降の計算 EMA(n)=EMA(n-1)+α×{価格(0)-EMA(n-1)}
n:対象期間 α(平滑化定数)=2/(n+1)価格(0):当日の価格
引用: ヒロセ通商 指数平滑移動平均線
export default (): ItemIndicator<{
    period: number
    lineColor: string
    lineWidth: number
    lineDash: number[]
}, {
    emaBuffer: IndicatorBuffer
}> => {
    return {
        type: "i",
        name: "tutor.EMA",
        onInit() {
            const { period, ...emaParams } = this.params;
            const lineBuffer = this.emaBuffer = this.addLineBuffer(emaParams);
            this.shortName = "EMA"
            this.onChartChange = ({ index, closes }) => {
                const emaBuffer = this.emaBuffer;
                if (index === closes.getContinuousDataFirstIndex(index) + period - 1) { //1
                    closes.sma(emaBuffer, period, index);
                } else {
                    const prevEma = emaBuffer.get(index - 1);
                    const currentClose = closes.get(index);
                    const alpha = 2 / (period + 1);
                    const emaVal = Math.round(prevEma + alpha * (currentClose - prevEma));
                    emaBuffer.set(index, emaVal);
                }
            }
            this.getDisplayData = (index) => {
                return { ema: lineBuffer.get(index) }
            }
        },
        params:
        {
            period: 25,
            lineColor: "green",
            lineWidth: 2,
            lineDash: [3, 3]
        },
    }
}

               
1

emaはデータの先頭を求める必要がありますが、JSTraderでは原則表示した期間のデータしか保持していません。 その為、保持している連続したデータの先頭を使ってemaを計算をします。 連続したデータの先頭を取得するにはIndicatorBufferのgetContinuousDataFirstIndexメソッドを使用します。

このように過去の値に依存するインジケーターは、表示中よりも過去のチャートを表示した場合、データの先頭が変わる為価格が変わることがあります。

EMAの計算はIndocatorBufferのemaメソッドを使うこともできます。

this.onChartChange = ({ index, closes }) => {
    closes.ema(emaBuffer, period, index); 
}