YahooFinanceWebClient implements ContractDataSource<FundamentalData>, HistoricalDataSource { public OHLC[] getHistoricalData(Contract contract, Date endDate, int numPeriods, int periodUnit) throws IOException { if (!(periodUnit == HistoricalDataSource.PERIOD_1_DAY || periodUnit == HistoricalDataSource.PERIOD_1_WEEK || periodUnit == HistoricalDataSource.PERIOD_1_MONTH)) throw new IllegalArgumentException("Must specify a period of day, week, or month."); GregorianCalendar start = new GregorianCalendar(); start.setTime(endDate); if (periodUnit == HistoricalDataSource.PERIOD_1_DAY) start.add(Calendar.DATE, -numPeriods); else if (periodUnit == HistoricalDataSource.PERIOD_1_WEEK) start.add(Calendar.WEEK_OF_YEAR, -numPeriods); else if (periodUnit == HistoricalDataSource.PERIOD_1_MONTH) start.add(Calendar.WEEK_OF_YEAR, -numPeriods); GregorianCalendar end = new GregorianCalendar(); end.setTime(endDate); StringBuilder reqUrl = new StringBuilder(historicalDataUrl); reqUrl.append("?s=").append(contract.getSymbol()); reqUrl.append("&a=").append(start.get(Calendar.MONTH)); reqUrl.append("&b=").append(start.get(Calendar.DAY_OF_MONTH)); reqUrl.append("&c=").append(start.get(Calendar.YEAR)); reqUrl.append("&d=").append(end.get(Calendar.MONTH)); reqUrl.append("&e=").append(end.get(Calendar.DAY_OF_MONTH)); reqUrl.append("&f=").append(end.get(Calendar.YEAR)); reqUrl.append("&g="); if (periodUnit == HistoricalDataSource.PERIOD_1_DAY) reqUrl.append("d"); else if (periodUnit == HistoricalDataSource.PERIOD_1_WEEK) reqUrl.append("w"); else reqUrl.append("m"); reqUrl.append("&ignore=.csv"); ArrayList<OHLC> prices = new ArrayList<OHLC>(); BufferedReader content = new BufferedReader(new InputStreamReader(new URL(reqUrl.toString()).openStream())); String line; for (line = content.readLine(); line != null; line = content.readLine()) { String fields[] = line.split(","); if (fields.length >= 7) { try { SimpleOHLC ohlc = new SimpleOHLC(); ohlc.setDate(df.parse(fields[0])); ohlc.setOpen(Double.parseDouble(fields[1])); ohlc.setHigh(Double.parseDouble(fields[2])); ohlc.setLow(Double.parseDouble(fields[3])); ohlc.setClose(Double.parseDouble(fields[4])); ohlc.setVolume(Long.parseLong(fields[5])); prices.add(ohlc); } catch (ParseException e) { } } } while (line != null); content.close(); return prices.toArray(new OHLC[0]); }  FundamentalData getDataSnapshot(Contract contract); OHLC[] getHistoricalData(Contract contract, Date endDate, int numPeriods, int periodUnit); void close();  }
@Test public void testHistoricalData() throws Exception { OHLC data[] = client.getHistoricalData(Contract.stock("MSFT"), new Date(), 20, HistoricalDataSource.PERIOD_1_DAY); assertNotNull(data); assertTrue(data.length > 10); for (OHLC ohlc : data) assertValidOHLC(ohlc); data = client.getHistoricalData(Contract.stock("GOOG"), new Date(), 5, HistoricalDataSource.PERIOD_1_WEEK); assertNotNull(data); assertEquals(5, data.length, 2); for (OHLC ohlc : data) assertValidOHLC(ohlc); }