-
Notifications
You must be signed in to change notification settings - Fork 248
/
Copy pathurllib-request-python-2-vs-3.py
313 lines (250 loc) · 11 KB
/
urllib-request-python-2-vs-3.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
from __future__ import print_function
# https://forum.omz-software.com/topic/4214/urllib-request-python-2-vs-3/9
#!python2
import urllib
import time,datetime
class Quote(object):
DATE_FMT = '%Y-%m-%d'
TIME_FMT = '%H:%M:%S'
def __init__(self):
self.symbol = ''
self.date,self.time,self.open_,self.high,self.low,self.close,self.volume = ([] for _ in range(7))
def append(self,dt,open_,high,low,close,volume):
self.date.append(dt.date())
self.time.append(dt.time())
self.open_.append(float(open_))
self.high.append(float(high))
self.low.append(float(low))
self.close.append(float(close))
self.volume.append(int(volume))
def to_csv(self):
return ''.join(["{0},{1},{2},{3:.2f},{4:.2f},{5:.2f},{6:.2f},{7}\n".format(self.symbol,
self.date[bar].strftime('%Y-%m-%d'),self.time[bar].strftime('%H:%M:%S'),
self.open_[bar],self.high[bar],self.low[bar],self.close[bar],self.volume[bar])
for bar in xrange(len(self.close))])
def write_csv(self,filename):
with open(filename,'w') as f:
f.write(self.to_csv())
def read_csv(self,filename):
self.symbol = ''
self.date,self.time,self.open_,self.high,self.low,self.close,self.volume = ([] for _ in range(7))
for line in open(filename,'r'):
symbol,ds,ts,open_,high,low,close,volume = line.rstrip().split(',')
self.symbol = symbol
dt = datetime.datetime.strptime(ds+' '+ts,self.DATE_FMT+' '+self.TIME_FMT)
self.append(dt,open_,high,low,close,volume)
return True
def __repr__(self):
return self.to_csv()
class GoogleQuote(Quote):
''' Daily quotes from Google. Date format='yyyy-mm-dd' '''
def __init__(self,symbol,start_date,end_date=datetime.date.today().isoformat()):
super(GoogleQuote,self).__init__()
self.symbol = symbol.upper()
start = datetime.date(int(start_date[0:4]),int(start_date[5:7]),int(start_date[8:10]))
end = datetime.date(int(end_date[0:4]),int(end_date[5:7]),int(end_date[8:10]))
url_string = "http://www.google.com/finance/historical?q={0}".format(self.symbol)
url_string += "&startdate={0}&enddate={1}&output=csv".format(
start.strftime('%b %d, %Y'),end.strftime('%b %d, %Y'))
print(url_string)
csv = urllib.urlopen(url_string).readlines()
csv.reverse()
for bar in xrange(0,len(csv)-1):
ds,open_,high,low,close,volume = csv[bar].rstrip().split(',')
open_,high,low,close = [float(x) for x in [open_,high,low,close]]
dt = datetime.datetime.strptime(ds,'%d-%b-%y')
self.append(dt,open_,high,low,close,volume)
if __name__ == '__main__':
q = GoogleQuote('aapl','2011-01-01','2011-01-03') # download year to date Apple data
print(q) # print it out
# --------------------
#!python3
import urllib.request
import time,datetime
class Quote(object):
DATE_FMT = '%Y-%m-%d'
TIME_FMT = '%H:%M:%S'
def __init__(self):
self.symbol = ''
self.date,self.time,self.open_,self.high,self.low,self.close,self.volume = ([] for _ in range(7))
def append(self,dt,open_,high,low,close,volume):
self.date.append(dt.date())
self.time.append(dt.time())
self.open_.append(float(open_))
self.high.append(float(high))
self.low.append(float(low))
self.close.append(float(close))
self.volume.append(int(volume))
def to_csv(self):
return ''.join(["{0},{1},{2},{3:.2f},{4:.2f},{5:.2f},{6:.2f},{7}\n".format(self.symbol,
self.date[bar].strftime('%Y-%m-%d'),self.time[bar].strftime('%H:%M:%S'),
self.open_[bar],self.high[bar],self.low[bar],self.close[bar],self.volume[bar])
for bar in xrange(len(self.close))])
def write_csv(self,filename):
with open(filename,'w') as f:
f.write(self.to_csv())
def read_csv(self,filename):
self.symbol = ''
self.date,self.time,self.open_,self.high,self.low,self.close,self.volume = ([] for _ in range(7))
for line in open(filename,'r'):
symbol,ds,ts,open_,high,low,close,volume = line.rstrip().split(',')
self.symbol = symbol
dt = datetime.datetime.strptime(ds+' '+ts,self.DATE_FMT+' '+self.TIME_FMT)
self.append(dt,open_,high,low,close,volume)
return True
def __repr__(self):
return self.to_csv()
class GoogleQuote(Quote):
''' Daily quotes from Google. Date format='yyyy-mm-dd' '''
def __init__(self,symbol,start_date,end_date=datetime.date.today().isoformat()):
super(GoogleQuote,self).__init__()
self.symbol = symbol.upper()
start = datetime.date(int(start_date[0:4]),int(start_date[5:7]),int(start_date[8:10]))
end = datetime.date(int(end_date[0:4]),int(end_date[5:7]),int(end_date[8:10]))
url_string = "http://www.google.com/finance/historical?q={0}".format(self.symbol)
url_string += "&startdate={0}&enddate={1}&output=csv".format(
start.strftime('%b %d, %Y'),end.strftime('%b %d, %Y'))
print(url_string)
req = urllib.request.Request(url_string)
csv = urllib.request.urlopen(req).readlines()
csv.reverse()
for bar in xrange(0,len(csv)-1):
ds,open_,high,low,close,volume = csv[bar].rstrip().split(',')
open_,high,low,close = [float(x) for x in [open_,high,low,close]]
dt = datetime.datetime.strptime(ds,'%d-%b-%y')
self.append(dt,open_,high,low,close,volume)
if __name__ == '__main__':
q = GoogleQuote('aapl','2011-01-01','2011-01-03') # download year to date Apple data
print(q) # print it out
# --------------------
#!python3
import urllib.request
import time,datetime
class Quote(object):
DATE_FMT = '%Y-%m-%d'
TIME_FMT = '%H:%M:%S'
def __init__(self):
self.symbol = ''
self.date,self.time,self.open_,self.high,self.low,self.close,self.volume = ([] for _ in range(7))
def append(self,dt,open_,high,low,close,volume):
self.date.append(dt.date())
self.time.append(dt.time())
self.open_.append(float(open_))
self.high.append(float(high))
self.low.append(float(low))
self.close.append(float(close))
self.volume.append(int(volume))
def to_csv(self):
return ''.join(["{0},{1},{2},{3:.2f},{4:.2f},{5:.2f},{6:.2f},{7}\n".format(self.symbol,
self.date[bar].strftime('%Y-%m-%d'),self.time[bar].strftime('%H:%M:%S'),
self.open_[bar],self.high[bar],self.low[bar],self.close[bar],self.volume[bar])
for bar in range(len(self.close))])
def write_csv(self,filename):
with open(filename,'w') as f:
f.write(self.to_csv())
def read_csv(self,filename):
self.symbol = ''
self.date,self.time,self.open_,self.high,self.low,self.close,self.volume = ([] for _ in range(7))
for line in open(filename,'r'):
symbol,ds,ts,open_,high,low,close,volume = line.rstrip().split(',')
self.symbol = symbol
dt = datetime.datetime.strptime(ds+' '+ts,self.DATE_FMT+' '+self.TIME_FMT)
self.append(dt,open_,high,low,close,volume)
return True
def __repr__(self):
return self.to_csv()
class GoogleQuote(Quote):
''' Daily quotes from Google. Date format='yyyy-mm-dd' '''
def __init__(self,symbol,start_date,end_date=datetime.date.today().isoformat()):
super(GoogleQuote,self).__init__()
self.symbol = symbol.upper()
start = datetime.date(int(start_date[0:4]),int(start_date[5:7]),int(start_date[8:10]))
end = datetime.date(int(end_date[0:4]),int(end_date[5:7]),int(end_date[8:10]))
url_string = "http://www.google.com/finance/historical?q={0}".format(self.symbol)
url_string += "&startdate={0}&enddate={1}&output=csv".format(
start.strftime('%b %d, %Y'),end.strftime('%b %d, %Y'))
print(url_string)
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
headers = {'User-Agent': user_agent}
req = urllib.request.Request(url_string,data=None,headers=headers)
csv = urllib.request.urlopen(req).readlines()
csv.reverse()
for bar in range(0,len(csv)-1):
ds,open_,high,low,close,volume = csv[bar].rstrip().split(',')
open_,high,low,close = [float(x) for x in [open_,high,low,close]]
dt = datetime.datetime.strptime(ds,'%d-%b-%y')
self.append(dt,open_,high,low,close,volume)
if __name__ == '__main__':
q = GoogleQuote('aapl','2011-01-01','2011-01-03') # download year to date Apple data
print(q) # print it out
# --------------------
#!python2
import datetime
from collections import namedtuple
now = datetime.datetime.now()
# enhance the fmt string to avoid calls to strftime
FMT = '{},{:%Y-%m-%d},{:%H:%M:%S},{:.2f},{:.2f},{:.2f},{:.2f},{}'
print(FMT.format('AAPL', now, now, 1, 2, 3, 4, 5))
# Or define a namedtuple and a format to match
stock_info = namedtuple('stock_info', 'date time open high low close volume')
stock_record = stock_info(now, now, 1, 2, 3, 4, 5)
FMT = ('{},{date:%Y-%m-%d},{time:%H:%M:%S},{open:.2f},{high:.2f},{low:.2f},'
'{close:.2f},{volume}')
print(FMT.format('AAPL', **stock_record._asdict()))
# --------------------
#!python2
import urllib,time,datetime
class Quote(object):
DATE_FMT = '%Y-%m-%d'
TIME_FMT = '%H:%M:%S'
def __init__(self):
self.symbol = ''
self.date,self.time,self.open_,self.high,self.low,self.close,self.volume = ([] for _ in range(7))
def append(self,dt,open_,high,low,close,volume):
self.date.append(dt.date())
self.time.append(dt.time())
self.open_.append(float(open_))
self.high.append(float(high))
self.low.append(float(low))
self.close.append(float(close))
self.volume.append(int(volume))
def to_csv(self):
return ''.join(["{0},{1},{2},{3:.2f},{4:.2f},{5:.2f},{6:.2f},{7}\n".format(self.symbol,
self.date[bar].strftime('%Y-%m-%d'),self.time[bar].strftime('%H:%M:%S'),
self.open_[bar],self.high[bar],self.low[bar],self.close[bar],self.volume[bar])
for bar in xrange(len(self.close))])
def write_csv(self,filename):
with open(filename,'w') as f:
f.write(self.to_csv())
def read_csv(self,filename):
self.symbol = ''
self.date,self.time,self.open_,self.high,self.low,self.close,self.volume = ([] for _ in range(7))
for line in open(filename,'r'):
symbol,ds,ts,open_,high,low,close,volume = line.rstrip().split(',')
self.symbol = symbol
dt = datetime.datetime.strptime(ds+' '+ts,self.DATE_FMT+' '+self.TIME_FMT)
self.append(dt,open_,high,low,close,volume)
return True
def __repr__(self):
return self.to_csv()
class GoogleQuote(Quote):
''' Daily quotes from Google. Date format='yyyy-mm-dd' '''
def __init__(self,symbol,start_date,end_date=datetime.date.today().isoformat()):
super(GoogleQuote,self).__init__()
self.symbol = symbol.upper()
start = datetime.date(int(start_date[0:4]),int(start_date[5:7]),int(start_date[8:10]))
end = datetime.date(int(end_date[0:4]),int(end_date[5:7]),int(end_date[8:10]))
url_string = "http://www.google.com/finance/historical?q={0}".format(self.symbol)
url_string += "&startdate={0}&enddate={1}&output=csv".format(
start.strftime('%b %d, %Y'),end.strftime('%b %d, %Y'))
csv = urllib.urlopen(url_string).readlines()
csv.reverse()
for bar in xrange(0,len(csv)-1):
ds,open_,high,low,close,volume = csv[bar].rstrip().split(',')
open_,high,low,close = [float(x) for x in [open_,high,low,close]]
dt = datetime.datetime.strptime(ds,'%d-%b-%y')
self.append(dt,open_,high,low,close,volume)
#if __name__ == '__main__':
q = GoogleQuote('vti','2017-09-08','2017-09-12')
print(q)
# --------------------