太长不看版
- 预备知识:python,爬虫,sql
- python下载网易的数据
- 数据库不要用mysql,用PostgreSQL
概述
中国股市的历史数据里面有很多值得挖掘和分析的东西,比如:
- 追涨的成功率是多少
- 某一天涨幅达到多少时候,第二天回调的概率是多少
- 成交量和涨幅的相关性
对数据的分析,可以使用脚本,也可以使用SQL。
SQL作为dsl,很多时候有不可代替的优势。
同时,数据获取就是非常必要的。
数据获取
数据来源
我个人建议用163的数据,速度不错,快速稳定
http://quotes.money.163.com/service/chddata.html?code=%s%s&start=%s&end=%s&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP
解释一下参数:
沪市加0前缀,深市加1前缀;时间日期格式是 yyyymmdd
如:
600000
数据存储
我一开始使用mysql存贮,发现写入性能和查询性能都很差劲,换成了PostgreSQL以后发现性能极佳。推荐使用PostgreSQL。
代码片段
# 将日期格式化为163需要的格式
def formatDateAs163Param(d):
s = d.strftime('%Y%m%d')
return s
# 下载股票数据
# startDate,endDate : time class
# return dict
def snatchStockData(code, startDate,endDate):
if startDate is None:
startDate = datetime.datetime.strptime("2018-01-01", '%Y-%m-%d')
st = formatDateAs163Param(startDate)
et = formatDateAs163Param(endDate)
if (st == et):
return
print("snatchStockData ,code=[%s],startDate=%s,end=%s" % (code, st, et))
if code.startswith("60"):
pre = "0"
elif code.startswith("00"):
pre = "1"
elif code.startswith("30"):
pre = "1"
elif code.startswith("399"):
pre = "1"
else:
pre = "1"
u = url % (pre, code, st, et)
sock = urllib.request.urlopen(u)
s = sock.read().decode("gbk")
sock.close()
print("download " + code + " success");
lines = s.split("\n")
lineNumber = 0
for line in lines:
if line.strip() == '':
continue
lineNumber = lineNumber + 1
if lineNumber == 1:
continue
si = line2Stock(line)
#print("save : ")
#printStockObj(si)
if si["open"] == "0.0" and si["close"] == "0.0":
continue
return si
# 将文本解析为stock dict
def line2Stock(line):
line = line.strip()
t = {}
# print("line = %s"%(line))
ss = line.split(",")
idx = 0
t["date"] = ss[idx]
idx = idx + 1
t["code"] = ss[idx]
if t["code"].startswith("\'"):
t["code"] = t["code"][1:]
idx = idx + 1
t["name"] = ss[idx]
idx = idx + 1
t["close"] = ss[idx]
idx = idx + 1
t["high"] = ss[idx]
idx = idx + 1
t["low"] = ss[idx]
idx = idx + 1
t["open"] = ss[idx]
idx = idx + 1
t["last_close"] = ss[idx]
idx = idx + 1
t["change"] = ss[idx]
idx = idx + 1
t["increaseRate"] = ss[idx]
idx = idx + 1
t["turnoverRate"] = ss[idx]
idx = idx + 1
t["turnover"] = ss[idx]
idx = idx + 1
t["money"] = ss[idx]
idx = idx + 1
t["market_value"] = ss[idx]
idx = idx + 1
t["traded_market_value"] = ss[idx]
t["id"]=t["code"]+"_"+t["date"]
return t