Saturday, 13 December 2008

Download share price history from Yahoo Finance

This problem took me a little while to figure out so I'm pretty happy that I've finally managed to get it working, and with a pretty simple solution. The crux of the problem was how to fetch from the internet a share price history for any given stock over a period of days, months or even years. As it turns out yahoo.finance offers a HTTP page which nicely returns this information for you. The format of the page address looks something like this:

http://ichart.yahoo.com/table.csv?s=MSFT&a=01&b=00&c=2007&d=31&e=11&f=2008&g=d&ignore=.csv

where:

s=the stock code and stock index if outside the US (i.e. MSFT or TEL.NZ)

a=the day of the month for the start date

b=the month of the year for the start date. Note that months seem to start from 0 so Jan is 0 and 11 is Dec

c=the year of the start date

d=the day of the end date

e=the month of the end date (also convert to go from 00 to 11)

f=the year of the end date

This web query can be used in a browser to return a list of share price data for the named stock from the start date to the end date. The list will show the opening value, closing value, and other data for each day in comma separated format. You simply need to parse this result set in a loop and use it as required.

In the sample code below I've made use of the NSURL and NSData objects to grab the data. Note, this code is reference only. It won't actually work, it's just to give you an idea of how this is done:


httpString = [NSString stringWithFormat:@"http://ichart.yahoo.com/table.csv?s=%@&a=%@&b=%@&c=%@&d=%@&e=%@&f=%@&g=d&ignore=.csv", stockCode, firstMonth, firstDay, firstYear, lastMonth, lastDay, lastYear];

NSURL *url = [NSURL URLWithString:httpString];

NSData *data = [NSData dataWithContentsOfURL:url];

NSString *s = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

NSArray *lines = [s componentsSeparatedByString:@"\n"];

NSArray *line;

for(i=0;i<[lines count];i++) {

 sCurLine = [lines objectAtIndex:i];

 line = [sCurLine componentsSeparatedByString:@","];


 /* the download should always contain 7 fields, but yahoo might change this at any time */

 if([line count]==7) {

  thisDate = [NSCalendarDate dateWithString:[line objectAtIndex:0] calendarFormat:@"%Y-%m-%d"];

  thisPrice = [[line objectAtIndex:4] floatValue];


  /* thisDate and thisPrice should now contain the date and price for this entry in the download (most recent first) */

  }

}

2 comments:

Arno said...

Thanks for your detailed description!

I have now the following problem:
How do i get historic prizes of bonds being traded in Europe?
Yahoo does not seem to offer them. Is there another source i can use?

Yours, arno

Adrian Falvey said...

Sorry for the late reply. I think yahoo finance does support them. Check http://finance.yahoo.com/exchanges for the list of supported exchanges.

For example, to get Royal Bank of Scotland on the London exchange use "RBS.L".