-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetdata.py
executable file
·78 lines (63 loc) · 2.56 KB
/
getdata.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
import io, requests, os
import numpy as np, pandas as pd
import datetime as dtm
from itertools import product
from os import walk
from aux import *
from bisect import bisect_left
# -----------
# RETREIVE DATA
# -----------
def getdata(dtype, symb, date):
url0, url1, url2, url3 = 'http://hopey.netfonds.no/', 'dump.php?date=2016', '&paper=', '.N&csv_format=csv'
# read the files
url = url0 + dtype + url1 + date + url2 + symb + url3
df = requests.get(url).content
df = pd.read_csv(io.StringIO(df.decode('utf-8')))
if len(df) < 100:
# on weeekends and public holidays there is no data
print "--Empty Dataset"
return
# do some cleaning
df['time'] = pd.to_datetime(df['time'])
if dtype == 'pos':
df = df.drop(['bid_depth_total','offer_depth_total'], axis=1)
df.columns = ['time', 'bid_price', 'bid_qty', 'offer_price', 'offer_qty']
elif dtype == 'trade':
df = df.drop(['source','buyer','seller','initiator'], axis=1)
df.columns = ['time', 'trade_price', 'trade_qty']
# stop if the dataset doesn't exist
# maxtime = int(df['time'].apply(lambda x: x.hour).max())
# if maxtime < 22:
# # don't export if the maxtime doesn't exist
# return df
# export the file
if not os.path.exists('Datasets/' + date):
os.makedirs('Datasets/' + date)
print "Made Directory", date
df.to_csv('Datasets/' + date + '/' + symb + '_' + dtype + '.csv', index=False)
return df
def getinddata(ind='Major Banks', idate='1112'):
idate = dtm.date(year=2016, month=int(idate[:2]), day=int(idate[2:]))
cdate = dtm.date.today()
tickers = gettickers()
sect_tickers = tickers.reset_index().groupby('Sector')['Symbol'].agg(lambda x: list(x))
ind_tickers = tickers.reset_index().groupby('Industry')['Symbol'].agg(lambda x: list(x))
for date in datelist(idate, cdate): # or tickers.index for all industries
print "DATE:", date
for symb, dtype in product(ind_tickers[ind], ('pos','trade')):
if symb == 'BLW':
continue
if dtype == 'pos':
print symb
try:
getdata(dtype, symb, date)
except UnicodeDecodeError:
print '--NOT FOUND'
def gettickers():
tickers = pd.read_csv('Datasets/companylist.csv')
tickers = tickers.set_index('Symbol')[['Name','Industry','Sector','MarketCap']]
tickers = tickers[(tickers.MarketCap > 10**8) & (tickers.Sector != 'n/a')]
return tickers
# if __name__ == '__main__':
# getinddata(window=1)