Pages

Friday, January 1, 2010

Using Yahoo to retrieve stock market data

Let's start playing with the Yahoo to retrieve stock market data.

This simple code will retrieve 1 year quotes values for Google's stock:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Date;

public class YahooQuote {
public static void main(String[] args) {
try {
Calendar oneYearAgo = Calendar.getInstance();
oneYearAgo.add(Calendar.DATE, -366);
Date now = new Date();
URL yahoo = new URL(getFeederURL("GOOG", new Date(oneYearAgo
.getTimeInMillis()), now));
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc
.getInputStream()));
String inputLine;

while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public static String getFeederURL(String symbol, Date from, Date to) {

Calendar fromDate = Calendar.getInstance();
fromDate.setTime(from);

Calendar toDate = Calendar.getInstance();
toDate.setTime(to);
return "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a="
+ String.valueOf(fromDate.get(Calendar.MONTH)) + "&b="
+ String.valueOf(fromDate.get(Calendar.DAY_OF_MONTH)) + "&c="
+ String.valueOf(fromDate.get(Calendar.YEAR)) + "&d="
+ String.valueOf(toDate.get(Calendar.MONTH)) + "&e="
+ String.valueOf(toDate.get(Calendar.DAY_OF_MONTH)) + "&f="
+ String.valueOf(toDate.get(Calendar.YEAR)) + "&g=d"
+ "&ignore=.csv";

}
}


Now we have the data! Let's work to generate an information.

No comments :