-
Notifications
You must be signed in to change notification settings - Fork 19
/
server.py
97 lines (87 loc) · 2.94 KB
/
server.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
# -*- coding: UTF-8 -*-
import tornado.ioloop
import tornado.web
import time # 引入time模块
import json
import random as rd
import tushare as ts
import datetime
import requests
def floatHandle(num,point):
return ('%.{}f'.format(point))%num
def newPrice(code):
data = {}
url = "http://hq.sinajs.cn/list="+"sh"+code
dt = requests.get(url).text
data['price'] = dt.split(",")[3]
jsondata = json.dumps(data)
return jsondata
class MainHandler(tornado.web.RequestHandler):
def get(self):
symbol = self.get_argument("symbol")
jdata = newPrice(symbol)
self.write(str(jdata))
# 处理历史数据请求
class HistoryHandler(tornado.web.RequestHandler):
def get(self):
symbol = self.get_argument("symbol")#股票代码
period = self.get_argument("period")#时间周期,单位-分钟
period_allow_list = ["5","15","30","60","1440","M","W"]
if period not in period_allow_list:
return
data = None
if period =="1440":
data = ts.get_hist_data(symbol)
else:
data = ts.get_k_data(symbol,ktype=period)
print "=========",symbol,":",period
resultlist = []
lens = len(data)
for unit in data.iterrows():
obj = {}
dates = None
if period =="1440":
dates = unit[1].name
else:
dates = unit[1]['date']
print "len",len(dates)
# 长度等于10的是%Y-%m-%d格式,16的是%Y-%m-%d %H:%M 格式
dataformate = "%Y-%m-%d %H:%M"
date_len = len(dates)
if date_len == 10 :
dataformate = "%Y-%m-%d"
d=datetime.datetime.strptime(dates,dataformate)
obj["date"]=int(time.mktime(d.timetuple()))
obj["open"]=unit[1]['open']
obj["close"]=unit[1]['close']
obj["high"]=unit[1]['high']
obj["low"]=unit[1]['low']
obj["volume"]=unit[1]['volume']
resultlist.append(obj)
resultlist.sort(key=lambda obj:obj.get('date'), reverse=False)
s = json.dumps(resultlist)
self.write(s)
class TestHandler(tornado.web.RequestHandler):
def get(self):
data = {}
# 保留几位小数
point = 5
# 生成一个系统时间
ostime = time.time()
data['timestamp'] = int(ostime)
seed = rd.uniform(10, 20);
data['price'] = floatHandle(seed,point)
data['vol'] = rd.randint(500,10000);
jsondata = json.dumps(data)
self.write(str(jsondata))
# 设置
application = tornado.web.Application([
(r"/", MainHandler),
(r"/history", HistoryHandler),
(r"/test", TestHandler),
])
if __name__ == "__main__":
ports = 9080
application.listen(ports)
print "service run at prot:",ports
tornado.ioloop.IOLoop.instance().start()