A couple of months ago one of my readers asked me to build a stock quote class that would automatically update the quote. I forgot about it, but then I found the e-mail and decided to give it a go. I started looking for some free services that could provide the data in XML format or something similar that can be easy parsed. Apparently that does not exist. All the stock sites charge you for that information and I want something free, so that was not the way to go.

Then I read about the Yahoo financial website and that it could be screen scraped fairly easy, so that’s what the class will use. The class is actually very simple to both use and modify. If the class isn't exactly what you need, you can just use its screen scraping methods to create your own implementation.

Update:
I've got some comments pointing out that Yahoo can give you CSV files, so I took a look at it, and now it does not use screen scraping any more. Thanks for the comments.

Examples of use

To get the quote for a specific stock, you can call the static Execute method. In this example a text box is filled with the quote:

txtStockQuote.Text = StockEngine.Execute("MSFT").Value.ToString();

You can also hook into the automatic update event, so that you can update a text box every time an update occurs. By default it is every minute.

private StockEngine _Engine;

 

private void PrepareStockQuote()

{

  _Engine = new StockEngine("MSFT");

  _Engine.AutoUpdate = true;

  _Engine.UpdateInterval = 60000; // 1 minute

  _Engine.Updated += new EventHandler<EventArgs>(_Engine_Updated);

}

 

private void _Engine_Updated(object sender, EventArgs e)

{

  txtStockQuote.Text = _Engine.Value.ToString();

}

Download

StockEngine.zip (1,92 KB)

Comments


Comments are closed