Skip to main content

Fetching Stock Data From Yahoo For iOS Applications

Yahoo! provides a great service called Yahoo! Query Language (YQL) which provides a SQL-like interface to a whole bunch of Web services. YQL queries can also be performed via REST. A wide range of services can be accessed through YQL including Yahoo! Finance.


A convenient way to play with YQL and explore the available Web services, is to use the YQL Console. The bottom right of the console lists all the data tables, grouped by provider. (Be sure to click "Show Community Tables" to view all the available tables.) The yahoo provider includes the data table yahoo.finance.quote. This table provides access to stock quotes from Yahoo! Finance. As an example, here's the YQL console showing a query for stock data for AAPL. The console helpfully shows the REST URL for the query at the bottom.


Armed with the REST URL, it is trivial to write code in Objective-C/iOS to fetch quote data. Here's some code that takes in an NSArray of ticker symbols (NSStrings) and returns a NSDictionary with tickers as keys and quotes (realtime bid) as values.


#define QUOTE_QUERY_PREFIX @"http://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20BidRealtime%20from%20yahoo.finance.quotes%20where%20symbol%20in%20("
#define QUOTE_QUERY_SUFFIX @")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="

+ (NSDictionary *)fetchQuotesFor:(NSArray *)tickers
{
NSMutableDictionary *quotes;
if (tickers && [tickers count] > 0) {
NSMutableString *query = [[NSMutableString alloc] init];
[query appendString:QUOTE_QUERY_PREFIX];
for (int i = 0; i < [tickers count]; i++) {
            NSString *ticker = [tickers objectAtIndex:i];
            [query appendFormat:@"%%22%@%%22", ticker];
            if (i != [tickers count] - 1) [query appendString:@"%2C"];
        }
        [query appendString:QUOTE_QUERY_SUFFIX];
        // NSLog(@"Query: %@", query);
        NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error = nil;
        NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error] : nil;
        if (error) NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
        // NSLog(@"[%@ %@] received %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), results);
        NSArray *quoteEntries = [results valueForKeyPath:@"query.results.quote"];
        quotes = [[NSMutableDictionary alloc] initWithCapacity:[quoteEntries count]];
        for (NSDictionary *quoteEntry in quoteEntries) {
            [quotes setValue:[quoteEntry valueForKey:@"BidRealtime"] forKey:[quoteEntry valueForKey:@"symbol"]];
        }
    }
    return quotes;
}

Comments

Popular posts from this blog

Migrating from Palm Calendar to Google Calendar and iPhone

Here are the free steps to migrate from Palm's date book (or Pimlico's DateBk6 ) calendar to Google calendar for full iPhone sync. First, sync Palm with Palm Desktop . Next, open Palm Desktop, select the Calendar view, navigate to File | Export, select Export Type as Date Book Archive, Range as All and provide a file name. This will export the calendar data as Date Book Archive (.dba). There's a paid tool called DBA2CSV that converts .dba files to .csv files. However this can be done for free using Yahoo Calendar. Login into Yahoo Calendar and via Settings/Import, import the .dba file. It helps to have an empty Yahoo Calendar. Via Settings/Export, export the calendar as .csv file. Login to Google Calendar (also works with Google Apps For Your Domain GAFYD Calendar) and import the .csv file into any of the calendars. It is a good idea to create a test calendar and test the import before importing into your real calendar. That way if anything goes wrong, you can delet...

AD-5526 Digital Multimeter

The AD-5526 is an ancient multimeter from A&D but for $10 one can’t complain. Has all the basic features one would expect from a multimeter and at 5.2 cm X 9.5 cm X 2.6 cm, it’s quite compact. Uses a LRV08 12V alkaline battery – not a common battery in the USA.

RTL-SDR, Raspberry Pi and Plane Spotting via ADS-B

Most modern aircraft carry an ADS-B ( Automatic Dependent Surveillance - Broadcast ) transmitter that puts out information about the aircraft's identification, geospatial location, speed, and heading. This information is received by ground stations and air traffic control and used as a replacement for radar-based tracking. ADS-B relies on line-of-sight communication via signals transmitted at 1090 Mhz and has a range of up to 250 nautical miles. Sites such as FlightAware , FlightRadar24 , Plane Finder , RadarBox24 , etc. collect ADS-B information using a vast array of ADS-B receivers, some of which are run by hobbyists, and present this information on maps with near-real-time updates. With the advent of cheap software-defined-radio (SDR) dongles, over the past few years, it has become extremely cheap and easy for amateurs to receive ADS-B signals, upload data to these sites and, in exchange, get access to premium features from these sites. This guide will walk you t...