Stock quote and chart from Yahoo in Java

I was recently in need of a stock quote web service in order to display quote information and charts for a corporate website I was working on, so I started looking around for something, free of course. I kept reading that the most common example of web as a service is the stock quote example, but I didn’t really find any examples that gave me a warm and fuzzy, everyone seemed to be scraping the html from a page. Doesn’t seem to be much out there, in the way of quote services for free, but I did come across a yahoo download service and a few half written examples, where you can fetch quote information from Yahoo in .csv format, with a 20 minute delay of course. I’ve also added a 1-day small chart and a 5-day large chart image by passing the symbol into Yahoo’s basic chart image url.
StockTickerDAO.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class StockTickerDAO {
private static final Log log = LogFactory.getLog(StockTickerDAO.class);
private static final StockTickerDAO stockDAO = new StockTickerDAO();
private static HashMap<String, StockBean> stocks = new HashMap<String, StockBean>();
private static final long TWENTY_MIN = 1200000;
private StockTickerDAO() {}
public static StockTickerDAO getInstance() {
return stockDAO;
}
/**
*
* @param symbol
* @return StockBean
* will return null if unable to retrieve information
*/
public StockBean getStockPrice(String symbol) {
StockBean stock;
long currentTime = (new Date()).getTime();
// Check last updated and only pull stock on average every 20 minutes
if (stocks.containsKey(symbol)) {
stock = stocks.get(symbol);
if(currentTime - stock.getLastUpdated() > TWENTY_MIN) {
stock = refreshStockInfo(symbol, currentTime);
}
} else {
stock = refreshStockInfo(symbol, currentTime);
}
return stock;
}
//This is synched so we only do one request at a time
//If yahoo doesn't return stock info we will try to return it from the map in memory
private synchronized StockBean refreshStockInfo(String symbol, long time) {
try {
URL yahoofin = new URL("http://finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=sl1d1t1c1ohgv&e=.csv");
URLConnection yc = yahoofin.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
String[] yahooStockInfo = inputLine.split(",");
StockBean stockInfo = new StockBean();
stockInfo.setTicker(yahooStockInfo[0].replaceAll("\"", ""));
stockInfo.setPrice(Float.valueOf(yahooStockInfo[1]));
stockInfo.setChange(Float.valueOf(yahooStockInfo[4]));
stockInfo.setChartUrlSmall("http://ichart.finance.yahoo.com/t?s=" + stockInfo.getTicker());
stockInfo.setChartUrlLarge("http://chart.finance.yahoo.com/w?s=" + stockInfo.getTicker());
stockInfo.setLastUpdated(time);
stocks.put(symbol, stockInfo);
break;
}
in.close();
} catch (Exception ex) {
log.error("Unable to get stockinfo for: " + symbol + ex);
}
return stocks.get(symbol);
}
}
StockBean.java
public class StockBean {
String ticker;
float price;
float change;
String chartUrlSmall;
String chartUrlLarge;
long lastUpdated;
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public float getChange() {
return change;
}
public void setChange(float change) {
this.change = change;
}
public String getChartUrlSmall() {
return chartUrlSmall;
}
public void setChartUrlSmall(String chartUrlSmall) {
this.chartUrlSmall = chartUrlSmall;
}
public String getChartUrlLarge() {
return chartUrlLarge;
}
public void setChartUrlLarge(String chartUrlLarge) {
this.chartUrlLarge = chartUrlLarge;
}
public long getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(long lastUpdated) {
this.lastUpdated = lastUpdated;
}
}
Using it
StockBean stock = StockTickerDAO.getInstance().getStockPrice("GOOG");
about 1 year ago
Nice trick; I had done same thing using php; more of a functional approach.
about 1 year ago
thank you very much!
It is really usefully to my new poject.
about 1 year ago
Does Google provide a similar service?
about 1 year ago
Only in their iGoogle gadget API, no externally accessible service like Yahoo.
about 1 year ago
I’ve been trawling the web for hours trying to find a stock ticker of some sort. I can’t find any that use the FTSE instead of NASDAQ though. With a change of the URL your code reads I can though!
Problem is, I’m not of a level to know how to use your code.
How would I go about embedding it into a web page with multiple stock quotes?
about 1 year ago
@G-Mo This is a server-side example written in Java, meaning you would need a Java Container, such as Tomcat to actually run the example and then you would need a JSP or similar view technology to display the quote information on the web page.
about 1 year ago
Thanks for the reply webdude. We run Windows boxes with .net and PHP 5.0 on Apache with no Tomcat (it’s a 3rd party shared box) so no joy there.
I’ll have to keep trawling. Appreciate your time.
about 1 year ago
@G-Mo You should ask Vishwajeet Singh http://www.singhvishwajeet.com/, he mentioned he pulled the yahoo stock quote CSV using PHP, he may be able to help.
about 1 year ago
how to use it in website can u pls explain it.
about 1 year ago
Really useful, thanks but how to get P/E I tried using all chars but did not get that particular.
Any info is appreciated.
Thanks
about 1 year ago
@Ani The quote service for Yahoo allows you to add several options in the f parameter of the url, if you add an r to the end, ex. http://finance.yahoo.com/d/quotes.csv?s=GOOG&f=sl1d1t1c1ohgvr&e=.csv you’ll get the P/E ratio in the last field. You could also limit the amount of data coming back to just the essential information. See the options at http://www.gummy-stuff.org/Yahoo-data.htm
about 1 year ago
Thanks Buddy, the info you sent is really helpful.
about 1 year ago
HI ,
This is very great program and very useful. Thanks for your coding.
I want to get the stock price of BSE, NSE, FTSE,DOW JONES, NASDAQ, NIKKEI,DAC & SHANGHAI.
how to get through coding?
Thanks in advance.
about 10 months ago
Thanks for your code. This really helped me. I was able to make this work flawlessly.
Keep up the good work
about 8 months ago
It is good program
Thank you
about 7 months ago
Fantastic article, thanks didn’t know this could be done with Java ! Very useful to my project as well.
Thanks again,
CV
about 7 months ago
Thanks. But somehow when I use the follow code in JSP
It shows an error “StockBean cannot be resolved to a type”
I put the bean correctly in corresponding directory… Anyone have any clue about it?
Thanks~!
about 5 months ago
This is really helpfull code, I am using it to getrid of third party software that does the same thing for my company.
about 1 week ago
Thanks for the useful information.
One question I have is that I was not able to pull correct foreign stock prices from Yahoo. For example, I typed in 7267:JP which is Honda Motors in Nikkei market and yahoo finance does not return any value. However, Bloomberg.com retrieves the stock price.
Do you know if it is possible to retrieve foreign stock prices from yahoo? If so, can you advise how?