Skip to content

Instantly share code, notes, and snippets.

@powerlim2
Created May 30, 2013 15:56
Show Gist options
  • Save powerlim2/5678993 to your computer and use it in GitHub Desktop.
Save powerlim2/5678993 to your computer and use it in GitHub Desktop.
Simple Moving Average by each stock
import java.io.*;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: joonhyunglim
* Date: 5/25/13
* Time: 6:34 PM
* To change this template use File | Settings | File Templates.
*/
public class SMAbyStock {
private final Queue<Double> window = new LinkedList<Double>(); // First in First Out
private final int period;
private double sum;
public SMAbyStock(int period) {
assert period > 0 : "Period must be a positive integer";
this.period = period;
}
public void newNum(double num) {
sum += num;
window.add(num);
if (window.size() > period) {
sum -= window.remove();
}
}
public double getAvg() {
if (window.size() != period) return 0; // technically the average is undefined
return sum / window.size();
}
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis(); // this is for measuring the computation time.
int[] windowSizes = {50,100,200};
for (int windSize : windowSizes) { // it will create number of files based on your windowsize specification.
// Writing the outcome for each window size.
File outfile = new File("/Users/joonhyunglim/Desktop/MSiA/MSiA431/data/NASDAQ_Moving_Average_"+windSize+".csv");
// you don't need to create the file previously, it will create the file if it does not exist
if (outfile.createNewFile()) {
System.out.println("File created");
} else {
System.out.println("I found the file. I am writing to the existing file");
}
BufferedWriter result = new BufferedWriter(new FileWriter(outfile));
// Reading all files in the folder
File folder = new File("/Users/joonhyunglim/Desktop/MSiA/MSiA431/data/NASDAQ/NASDAQ");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
BufferedReader Reader = new BufferedReader(new FileReader(file));
Reader.readLine(); // take out the column header
ArrayList<Double> Data = new ArrayList<Double>();
String line;
while ((line = Reader.readLine()) != null) {
String[] tokens = line.split(",");
Data.add(Double.parseDouble(tokens[6]));
}
System.out.println(Data.size());
Reader.close();
// Simple Moving Average
SMAbyStock ma = new SMAbyStock(windSize);
// sort the Hashtable by key and iterate them
for(Double x : Data) {
ma.newNum(x);
result.write(file.getName().split("\\.")[0]+","+x+"," + ma.getAvg()); // for each date, Left is a data point, and the right is a SMA.
result.newLine();
}
}
result.close();
}
long time = System.currentTimeMillis() - start;
System.out.println("\n**Execution Time is : "+time/1000+"seconds**");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment