1. 程式人生 > >風火程式設計--python獲取單隻股票實時資料和歷史資料

風火程式設計--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)