com.candy.algo.SMA.java Source code

Java tutorial

Introduction

Here is the source code for com.candy.algo.SMA.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.candy.algo;

import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;

/**
 *
 * @author ruizhou
 */
public class SMA {
    //    public static double[] Average(double[] price, double displace, int lastBars) {
    //        int length = price.length;
    //        double[] sma = new double[length];
    //        for (int i = length-1; i >= lastBars; i--) {
    //            double total = 0;
    //            for (int j = 0; j < lastBars; j++) {
    //                total += price[i-j];
    //            }
    //            sma[i] = total/lastBars;
    //        }        
    //        return sma;
    //    }
    public static double[] Sma(double inputs[], int windowSize) {
        // Get a DescriptiveStatistics instance
        DescriptiveStatistics stats = new DescriptiveStatistics();
        stats.setWindowSize(windowSize);
        double[] sma = new double[inputs.length];
        for (int i = 0; i < inputs.length; i++) {
            stats.addValue(inputs[i]);
            if (i >= (windowSize - 1))
                sma[i] = stats.getMean();
            else
                sma[i] = Double.NaN;
        }
        return sma;
    }
}