我对如何实现福特收盘价的导入有点困惑。目前,我正在使用扫描仪,虽然有下一行,它应该继续循环下来。导入行后,我需要将其转换为双精度。我的问题是如何将整个文件导入字符串数组,然后将其转换为双精度,然后使用for循环通过双精度数组来计算给定方程的MACD。
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();
}
}}
为简洁起见,省略了文件读取代码—将添加价格List
的for循环替换为读取csv收盘价的while循环。
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;
}
}