Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5

Reading CSV File
#1

Java is a powerful object oriented programming language. Java is widely used in algorithmic trading. Before you develop an algorithmic trading strategy with Java, you need to read the data. We can easily download the data from MT4 using Tools > History Center menu. I have a file DJ301440.csv that has daily open, high, low and close data for Dow Jones Industrial Average. I want to read it into Java. Below is the code that you will use to read the DJ301440.csv file with Java:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;


public class ReadCSV {

    public static void main(String[] args) {
// DJ301440 is the OHLC daily data for Dow Jones Index        
        File Data1 = new File("D:/Shared/MarketData/DJ301440.csv");
        try {//A Scanner in Java is a class that provides access to a resource
            //The resource is file in our case
            Scanner OHLC1= new Scanner(Data1);
            int count=1;
            //Initialize the delimiter
            OHLC1.useDelimiter(",|\r\n");
            while (OHLC1.hasNext()) {
            String column1 = OHLC1.next();
            String column2 = OHLC1.next();
            Double column3 = OHLC1.nextDouble();
            Double column4 = OHLC1.nextDouble();
            Double column5 = OHLC1.nextDouble();
            Double column6 = OHLC1.nextDouble();
            int    column7 = OHLC1.nextInt();
            count++;
            //Date: %s Time: %s Open: %f High: %f Low: %f Close: %f\n
            System.out.printf("%s %s %f %f %f %f %d\n",
                    column1, column2, column3,column4, column5,
                    column6, column7);
            }
            OHLC1.close();
            System.out.println(count);
        } catch (FileNotFoundException e) {
            System.out.println(e);
        }
    }
    
}

Java has the Scanner class that we will use to read the file DJ301440.csv. First we create new file OHLC1 and then read all the data from DJ301440.csv into it. We also print each line and use a count of how many rows were read using count variable. Below is the output:

2018.02.05 00:00 25248.000000 25474.000000 23794.000000 24074.000000 79670
2018.02.06 00:00 24074.000000 24157.000000 23049.000000 23690.000000 47768
2049

As you can see there were 2049 rows in the file. We don't need to print the rows. I did it just to make sure the java code was working correctly.

Subscribe My YouTube Channel:
https://www.youtube.com/channel/UCUE7VPo...F_BCoxFXIw

Join Our Million Dollar Trading Challenge:
https://www.doubledoji.com/million-dolla...challenge/
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)