YQL and Python
I used Python and Yahoo YQL to make queries about stocks and format the result in a shorter custom JSON object. Here is the code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import yahoo.yql
from pprint import pprint
def YahooFinance ():
response = yahoo.yql.YQLQuery().execute('select * from yahoo.finance.quote where symbol in ("YHOO","AAPL","GOOG","MSFT","TWTR")')
if 'error' in response :
print 'YQL query failed with error: "%s".' % response['error']['description']
return ''
elif ('query' not in response) or ('results' not in response['query']):
print 'YQL response malformed.'
return ''
stocks = {}
for stock in response['query']['results']['quote'] :
ticker = stock['symbol'];
change = stock['Change'];
price = stock['LastTradePriceOnly'];
stocks[ticker] = [price, change]
stocks_json = json.dumps(stocks)
return stocks_json
if __name__== '__main__':
pprint(YahooFinance())
Running the above code returns:
{
"GOOG":[
"1135.394",
"+28.474"
],
"TWTR":[
"63.47",
"+4.02"
],
"AAPL":[
"499.782",
"-0.968"
],
"YHOO":[
"35.31",
"+0.42"
],
"MSFT":[
"36.86",
"+0.20"
]
}