forked from rohanag/StockMarketSentimentAnalysis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstockretriever.py
168 lines (108 loc) · 5.44 KB
/
stockretriever.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import sys, httplib, urllib
try: import simplejson as json
except ImportError: import json
PUBLIC_API_URL = 'http://query.yahooapis.com/v1/public/yql'
DATATABLES_URL = 'store://datatables.org/alltableswithkeys'
HISTORICAL_URL = 'http://ichart.finance.yahoo.com/table.csv?s='
RSS_URL = 'http://finance.yahoo.com/rss/headline?s='
FINANCE_TABLES = {'quotes': 'yahoo.finance.quotes',
'options': 'yahoo.finance.options',
'quoteslist': 'yahoo.finance.quoteslist',
'sectors': 'yahoo.finance.sectors',
'industry': 'yahoo.finance.industry'}
class YQLQuery(object):
def __init__(self):
self.connection = httplib.HTTPConnection('query.yahooapis.com')
def execute(self, yql):
queryString = urllib.urlencode({'q': yql, 'format': 'json', 'env': DATATABLES_URL})
self.connection.request('GET', PUBLIC_API_URL + '?' + queryString)
return json.loads(self.connection.getresponse().read())
class QueryError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class StockRetriever(YQLQuery):
"""A wrapper for the Yahoo! Finance YQL api."""
def __init__(self):
super(StockRetriever, self).__init__()
def __format_symbol_list(self, symbolList):
return ",".join(["\""+stock+"\"" for stock in symbolList])
def __is_valid_response(self, response, field):
return 'query' in response and 'results' in response['query'] \
and field in response['query']['results']
def __validate_response(self, response, tagToCheck):
if self.__is_valid_response(response, tagToCheck):
quoteInfo = response['query']['results'][tagToCheck]
else:
if 'error' in response:
raise QueryError('YQL query failed with error: "%s".'
% response['error']['description'])
else:
raise QueryError('YQL response malformed.')
return quoteInfo
def get_current_info(self, symbolList, columnsToRetrieve='*'):
"""Retrieves the latest data (15 minute delay) for the
provided symbols."""
columns = ','.join(columnsToRetrieve)
symbols = self.__format_symbol_list(symbolList)
yql = 'select %s from %s where symbol in (%s)' \
%(columns, FINANCE_TABLES['quotes'], symbols)
response = super(StockRetriever, self).execute(yql)
return self.__validate_response(response, 'quote')
def get_historical_info(self, symbol):
"""Retrieves historical stock data for the provided symbol.
Historical data includes date, open, close, high, low, volume,
and adjusted close."""
yql = 'select * from csv where url=\'%s\'' \
' and columns=\"Date,Open,High,Low,Close,Volume,AdjClose\"' \
% (HISTORICAL_URL + symbol)
results = super(StockRetriever, self).execute(yql)
# delete first row which contains column names
del results['query']['results']['row'][0]
return results['query']['results']['row']
def get_news_feed(self, symbol):
"""Retrieves the rss feed for the provided symbol."""
feedUrl = RSS_URL + symbol
yql = 'select title, link, description, pubDate from rss where url=\'%s\'' % feedUrl
response = super(StockRetriever, self).execute(yql)
if response['query']['results']['item'][0]['title'].find('not found') > 0:
raise QueryError('Feed for %s does not exist.' % symbol)
else:
return response['query']['results']['item']
def get_options_info(self, symbol, expiration='', columnsToRetrieve ='*'):
"""Retrieves options data for the provided symbol."""
columns = ','.join(columnsToRetrieve)
yql = 'select %s from %s where symbol = \'%s\'' \
% (columns, FINANCE_TABLES['options'], symbol)
if expiration != '':
yql += " and expiration='%s'" %(expiration)
response = super(StockRetriever, self).execute(yql)
return self.__validate_response(response, 'optionsChain')
def get_index_summary(self, index, columnsToRetrieve='*'):
columns = ','.join(columnsToRetrieve)
yql = 'select %s from %s where symbol = \'@%s\'' \
% (columns, FINANCE_TABLES['quoteslist'], index)
response = super(StockRetriever, self).execute(yql)
return self.__validate_response(response, 'quote')
def get_industry_ids(self):
"""retrieves all industry names and ids."""
yql = 'select * from %s' % FINANCE_TABLES['sectors']
response = super(StockRetriever, self).execute(yql)
return self.__validate_response(response, 'sector')
def get_industry_index(self, id):
"""retrieves all symbols that belong to an industry."""
yql = 'select * from %s where id =\'%s\'' \
% (FINANCE_TABLES['industry'], id)
response = super(StockRetriever, self).execute(yql)
return self.__validate_response(response, 'industry')
if __name__ == "__main__":
retriever = StockRetriever()
try:
retriever.get_current_info(sys.argv[1:])
#print retriever.get_industry_ids()
#print retriever.get_news_feed('yhoo')
except QueryError, e:
#print e
self.response.write('<p>%s</p>' %e)
sys.exit(2)