-
Notifications
You must be signed in to change notification settings - Fork 2
/
yahoo_finance.py
123 lines (102 loc) · 3.5 KB
/
yahoo_finance.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
##================================================[ IMPORTS MODULE ]================================================
import datetime
from peewee import *
import hashlib
from configobj import ConfigObj
import fail
import time
import requests
import dateutil.parser
import json
import pandas.io.data as web
##================================================[ GLOBAL DECLARATIONS ]===========================================
Config = json.loads(open('config.json', 'r').read())
##================================================[ CLASS DECLARATIONS ]============================================
class YahooFinanceConfig (Model):
ticker = CharField()
start = DateField()
end = DateField()
processing = BooleanField(default=False)
class Meta:
db = SqliteDatabase('db')
class YahooFinanceResult (Model):
identifier = CharField(64)
ticker = CharField()
date = DateField()
inserted = FloatField()
open = FloatField()
high = FloatField()
low = FloatField()
volume = FloatField()
close = FloatField()
class Meta:
db = SqliteDatabase('db')
##================================================[ MAIN CODING ]===================================================
def SplitDateIntoString(start_date):
if start_date.find("/") < 0:
if start_date.find("\\") < 0:
if start_date.find("-") < 0:
print "\nWrong date format!"
return "0"
else:
return start_date.split("-")
else:
return start_date.split("\\")
else:
return start_date.split("/")
# Imports a set of codes from an .ini file. This will also create the SQL tables needed to house the data
def FetchDataFromWeb ():
global Config
print "\nFetching data ..."
try:
code = YahooFinanceConfig.select().where(YahooFinanceConfig.processing != True).get()
except:
print "\nReturn false, there are no more records left"
return False
pass
else:
#code.processing = True
lStartDateList = SplitDateIntoString(raw_input("Enter the Start Date [in dd/mm/yyyy format] : "))
lEndDateList = SplitDateIntoString(raw_input("Enter the End Date [in dd/mm/yyyy format] : "))
code.start = unicode(datetime.date(int(lStartDateList[2]), int(lStartDateList[1]), int(lStartDateList[0])))
code.end = unicode(datetime.date(int(lEndDateList[2]), int(lEndDateList[1]), int(lEndDateList[0])))
#code.save()
delete_quary = YahooFinanceResult.delete().where(YahooFinanceConfig.processing != True)
delete_quary.execute()
f=web.DataReader(code.ticker, 'yahoo', code.start, code.end)
for date, _value in f.iterrows():
try:
value = {
'open': _value['Open'],
'high': _value['High'],
'low': _value['Low'],
'volume': _value['Volume'],
'close': _value['Close']
}
record = YahooFinanceResult.create(
identifier = hashlib.sha256(code.ticker + str(date) + code.start + code.end).hexdigest(),
ticker = code.ticker,
date = (dateutil.parser.parse(str(date))),
inserted = int(time.time() * 1000),
open = _value['Open'],
high = _value['High'],
low = _value['Low'],
volume = _value['Volume'],
close = _value['Close']
)
print code.ticker + "[" + str(date) + '] => ' + json.dumps(value)
except Exception as E:
error = fail.Error.create(query = code.ticker, timestamp = int(time.time() * 1000), error = str(E))
print str(E)
pass
return code
if __name__ == '__main__':
try:
YahooFinanceResult.create_table()
except Exception, e:
print "\nException: ", e
try:
YahooFinanceConfig.create_table()
except Exception, e:
print "\nException: ", e
FetchDataFromWeb()