finance - MACD java Double array -
i little stuck on how implement importing of closing price of ford. currently, using scanner while there next line should continue loop down. after importing line need converted double. question how can import entire file string array , convert double , use loop cycle through double array compute macd given equations.
import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; public class importcsv { public static void main(string[] args) { //to import .csv file string filename = "ford.csv"; file file = new file(filename); try { scanner inputstream = new scanner(file); //ignore first line inputstream.next(); while (inputstream.hasnext()) { //get whole line string data = inputstream.next(); //split string array of strings string [] values = data.split(","); //convert double double closingprice = double.parsedouble(values[4]); // system.out.println(closingprice); final double ema_12_alpha = 2.0 / (1 + 12); final double ema_26_alpha = 2.0 / (1 + 26); double ema12 = 0; double ema26 = 0; double macd = 0; ema12 = ema_12_alpha * closingprice + (1 - ema_12_alpha) * ema12; ema26 = ema_26_alpha * closingprice + (1 - ema_26_alpha) * ema26; macd = ema12 - ema26; system.out.println(macd); } inputstream.close(); } catch (filenotfoundexception e) { // todo auto-generated catch block e.printstacktrace(); }
} }
file reading code has been omitted brevity - replace loop adding prices list
while loop reading closing price csv.
import java.util.*; public class macd { private static list<double> prices; private final static double ema_12_alpha = 2d / (1d + 12d); private final static double ema_26_alpha = 2d / (1d + 26d); public static void main(string []args){ prices = new arraylist<double>(); for(int i=0; i<100; i++) { prices.add(new double(i)); } for(int = 25; < prices.size(); i++) { final double macd = getema12(i) - getema26(i); system.out.println(macd); } } public static double getema12(int day) { if(day < 11) system.err.println("day must >= 11"); double ema12 = 0d; for(int i=day-10; i<=day; i++) { ema12 = ema_12_alpha * prices.get(i) + (1d - ema_12_alpha) * ema12; } return ema12; } public static double getema26(int day) { if(day < 25) system.err.println("day must >= 25"); double ema26 = 0d; for(int i=day-24; i<=day; i++) { ema26 = ema_26_alpha * prices.get(i) + (1d - ema_26_alpha) * ema26; } return ema26; } }
Comments
Post a Comment