I am a little stuck on how to implement the importing of the closing price of Ford. Currently, I am using the scanner that while there is a next line it should continue to loop down. After importing the line i need it to be converted to a double. My question is how can i import the entire file into a string array and then convert it to double and then use a for loop to cycle through the double array to compute the MACD by the 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 the first line
inputStream.next();
while (inputStream.hasNext())
{
//get the whole line
String data = inputStream.next();
//split the string into an array of strings
String [] values = data.split(",");
//convert to 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 for brevity - replace the for loop adding to the prices List
with the while loop reading the closing price from 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 i = 25; i < 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 be >= 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 be >= 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;
}
}