Created
March 11, 2014 21:56
-
-
Save vincentjames501/9495976 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.commons.io.IOUtils; | |
import java.io.IOException; | |
import java.net.URL; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
import static java.util.AbstractMap.SimpleEntry; | |
public class Stocks { | |
public static void main(String[] args) { | |
List<String> symbols = Arrays.asList("AAPL", "GOOG", "IBM", "JAVA", "MSFT"); | |
int year = 2008; | |
SimpleEntry<String, Float> topStock = getTopStock(symbols, year); | |
System.out.println("Top stock of " + year + " is " + topStock.getKey() + " closing at price " + topStock.getValue()); | |
} | |
private static SimpleEntry<String, Float> getTopStock(List<String> symbols, int year) { | |
return symbols.parallelStream() | |
.map(symbol -> getYearEndClosing(symbol, year)) | |
.reduce((highest, price) -> price.getValue() > highest.getValue() ? price : highest) | |
.get(); | |
} | |
private static SimpleEntry<String, Float> getYearEndClosing(String symbol, int year) { | |
try { | |
String uri = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=11&b=01&c=" + year + "&d=11&e=31&f=" + year + "&g=m"; | |
List<String> data = IOUtils.readLines(new URL(uri).openStream()).stream().map(String::trim).collect(Collectors.toList()); | |
return new SimpleEntry<>(symbol, Float.parseFloat(data.get(1).split(",")[4])); | |
} catch (IOException e) { | |
return new SimpleEntry<>(symbol, 0F); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment