风火编程--python获取单只股票实时数据和历史数据

获取股票数据

这本来是专门为我的一个单一选股模型提供数据的类, 因此封装的只是模型中需要的数据. 如有其它需求可以自己扩展. 积分多的可以下载文件, 没积分的直接复制下面的代码是一样的. 代码不复杂, 一看就懂.
欢迎加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)

强烈推荐使用tushare 提供的的pro_api免费获取股票数据
tushare注册地址

import tushare as ts
pro = ts.pro_api("your_token")
# codes = pro.stock_basic()["ts_code"]
# for code in codes:
#     df = pro.daily()
df = pro.daily(ts_code="000001.SZ", start_date="20080302", enddate="20180202")
print(df.head())
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值