GreatWebGuy Self-proclaimed greatness is a hard thing to prove.

17Aug/0826

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");
Comments (26) Trackbacks (0)
  1. Nice trick; I had done same thing using php; more of a functional approach.

  2. thank you very much!
    It is really usefully to my new poject.

  3. Does Google provide a similar service?

  4. Only in their iGoogle gadget API, no externally accessible service like Yahoo.

  5. 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?

  6. @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.

  7. 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.

  8. @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.

  9. how to use it in website can u pls explain it.

  10. 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

  11. @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

  12. Thanks Buddy, the info you sent is really helpful.

  13. 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.

  14. Thanks for your code. This really helped me. I was able to make this work flawlessly.

    Keep up the good work :)

  15. It is good program
    Thank you

  16. Fantastic article, thanks didn’t know this could be done with Java ! Very useful to my project as well.

    Thanks again,
    CV

  17. 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~!

  18. This is really helpfull code, I am using it to getrid of third party software that does the same thing for my company.

  19. 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?

  20. thank you brother. mind expanding to the usefulness of java.

  21. Hi,

    I am developing a software system in servlet& Jsp and I need to get the yahoo’s delayed-15 intraday (only forex) quotes and display in my jsp page. Is there any sample java code to fetch the quotes or any link to give details about realizing it?

    Thanks and Regards,
    Ramesh.

  22. hey, thanks a lot for this code. it has really helped me in moving forward with my project. :)

  23. Thanks so much! This really helped me on my project

  24. EXCELLENT! Can someone please help me on how I can expand this to get the high/low price of the share. I have spent a lot of time on doing this and I’m not getting anywhere! Any help will be appreciated!

  25. Webguy, I have a web dev that is having trouble with this. Can I just pay you to get it done?


Leave a comment

(required)

No trackbacks yet.