Search code examples
javadatefinance

Best way to convert ticks to minuts in Java (finance)


I've got a huge data base that contain for each day a text file with the following format : "HH:mm:ss xxxx.xx" for almost each second of each trading day, so I have thousands lines in each text's file. I'm looking for the best way to convert these lines into a HashMap where each key represents a new minute of the trading day.

For example I'd like to make theses few lines :

00:08:48    9819,9
00:09:10    9818,7
00:09:44    9819,9
00:09:51    9820,9
00:10:07    9822,1

looks like this in the HashMap :

myHashMap.put("00:09:00", 9818.7)

myHashMap.put("00:10:00", 9822.1)

PS : I know "00:09:00" is not a good Date format, it's just for the example !


Solution

  • If you're working with - Files#lines does a great job at that. The LocalTime class represents a time-of-day.

    WARNING : a OutOfMemoryError could be thrown if too much objects were to be created in memory.

    Map<LocalTime, Double> map = Files.lines(Paths.get("D:\\data.txt"))
                                      .map(x -> x.split(" "))
                                      .collect(Collectors.toMap(
                                                   x -> LocalTime.parse(x[0]), 
                                                   x -> Double.valueOf(x[1])));
    

    For a specific double format, you may use the following

    (Double)NumberFormat.getInstance(Locale.GERMANY).parse(x[1]))
    

    Monetary

    Since the data seems to be monetary, BigDecimal may be a better choice instead of a Double.

    Map<LocalTime, BigDecimal> map = Files.lines(Paths.get("D:\\data.txt"))
                                      .map(x -> x.split(" "))
                                      .collect(Collectors.toMap(
                                                   x -> LocalTime.parse(x[0]), 
                                                   x -> new BigDecimal(x[1])));