-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlive_data_analysis.py
99 lines (84 loc) · 2.19 KB
/
live_data_analysis.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Collects data for testing
import sys
import socket
import sqlite3 as s
import argparse
from purple.finance import Trade
# Main table
TABLE = '''
DROP TABLE IF EXISTS trades;
CREATE TABLE trades(
price NUMERIC,
size NUMERIC,
bid NUMERIC,
ask NUMERIC,
time TEXT,
buyer TEXT,
seller TEXT,
symbol TEXT,
sector TEXT
);'''
# connect to sqlite
conn = s.connect('data.db')
def create_tables(cur):
try:
cur.executescript(TABLE)
conn.commit()
except s.Error, e:
if conn:
conn.rollback()
print "Error: %s" % e.args[0]
sys.exit(1)
def insert_trade(cur, t):
global conn
cur.execute((
'INSERT INTO '
'trades (price, size, bid, ask, time, buyer, seller, symbol, sector) '
'VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?);'
), (
t.price, t.size, t.bid, t.ask,
t.time, t.seller, t.buyer,
t.symbol, t.sector
))
if conn:
conn.commit()
def main():
global conn
parser = argparse.ArgumentParser()
parser.add_argument('--init', action='store_true')
args = parser.parse_args()
with conn:
# get db cursor
cur = conn.cursor()
# create tables if required
if (args.init):
create_tables(cur)
# Open socket with given paramaters
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('cs261.dcs.warwick.ac.uk', 80))
except socket.error, e:
# Oopsy, couldn't connect
print e
sys.exit(1)
line = ''
firstline = True
# read character by character until new line '\n'
# is found. Parse line at that time and continue.
while 1:
# read character
char = sock.recv(1)
if char == '\n':
if firstline:
firstline = False
else:
t = Trade(line)
if not t.parse_err:
insert_trade(cur, t)
line = ''
else:
line = line + char
if __name__ == '__main__':
main()