版权声明:风火编程, 欢迎指正. https://blog.csdn.net/weixin_42620314/article/details/83751563
获取股票数据
这本来是专门为我的一个单一选股模型提供数据的类, 因此封装的只是模型中需要的数据. 如有其它需求可以自己扩展. 积分多的可以下载文件, 没积分的直接复制下面的代码是一样的. 代码不复杂, 一看就懂.
欢迎加qq或微信(77245741)共同探讨.
# coding: utf-8
__author__ = "风火"
from datetime import datetime, date, timedelta
from lxml import etree
import requests
class Data():
"""
提供历史数据的类
"""
__history_url = 'http://vip.stock.finance.sina.com.cn/quotes_service/view/vMS_tradehistory.php?symbol={}&date={}'
__live_url = 'http://hq.sinajs.cn/list={}'
__headers = {'User-Agent': 'Mozilla/5.0(compatible;MSIE9.0;WindowsNT6.1;Trident/5.0;'}
def __init__(self, stockCode, days=0):
"""
初始化方法
:param stockCode: sh600001/ sz000001
:param days:回溯天数, 默认0,表示实时数据
"""
if __author__ == "风火":
self.stockCode = stockCode
self.today = date.today()
self.day = self.today
self.days = days
self.get_ref_date()
self.__get_data()
def get_ref_date(self):
if self.days:
for i in range(self.days):
self.day = self.day - timedelta(days=1)
while True:
if self.__get_open():
break
else:
self.day = self.day - timedelta(days=1)
def __get_open(self):
url = self.__history_url.format(self.stockCode, date.strftime(self.day, "%Y-%m-%d"))
resp = requests.get(url, headers=self.__headers)
html = etree.HTML(resp.content)
open = float(html.xpath('.//td[text()="开盘价:"]/following-sibling::td[1]//text()')[0])
return open
def __get_data(self):
"""
获取数据的方法
"""
if self.days:
url = self.__history_url.format(self.stockCode, self.day)
resp = requests.get(url, headers=self.__headers)
html = etree.HTML(resp.content)
self.open = float(html.xpath('//td[text()="开盘价:"]/following-sibling::td[1]//text()')[0])
self.close = float(html.xpath('//td[text()="收盘价:"]/following-sibling::td[1]//text()')[0])
self.high = float(html.xpath('//td[text()="最高价:"]/following-sibling::td[1]//text()')[0])
self.low = float(html.xpath('//td[text()="最低价:"]/following-sibling::td[1]//text()')[0])
self.amount = int(float(html.xpath('//td[text()="成交额(千元):"]/following-sibling::td[1]//text()')[0])/10)
else:
url = self.__live_url.format(self.stockCode)
resp = requests.get(url=url, headers=self.__headers)
data_list = resp.text.split(",")
self.open = float(data_list[1])
self.close = float(data_list[3])
self.high = float(data_list[4])
self.low = float(data_list[5])
self.amount = int(float(data_list[9])/10000)
@property
def fall(self):
"""
涨跌的属性
:return: 涨/跌, boolean False/True
"""
return True if self.close < self.open else False
@property
def now(self):
"""
用于与节点时间比较的当前时间
:return: h + m / 100, xx.xx
"""
t = datetime.now()
return t.hour + t.minute / 100
d = Data("sh601360") # 实时数据
d1 = Data("sh601360", 1) # 回溯1天的数据
d2 = Data("sh601360", 2) # 回溯两天的数据
print(d2.open)