使用Python获取股票行情数据(中国个股/中国指数/全球指数)

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author: https://blog.csdn.net/bitquant
#中国股票数据

import urllib.request
import time, datetime
import re, json


class STOCK():

    _prefix_url = "https://hq.sinajs.cn/list="

    #中国指数
    def index(self, code):
        exchange = "sz" if (code[:3] == "399") else "sh"
        url = self._prefix_url + exchange + code       #http://hq.sinajs.cn/list=s_sh000001
        info = self.http_request(url)
        result = self.data_format(info)
        return result

    #美股,港股指数
    def index_world(self, ex_code):
        url = self._prefix_url + ex_code       #http://hq.sinajs.cn/list=s_sh000001
        info = self.http_request(url)
        result = self.data_format(info)
        return result

    #中国个股
    def individual(self, code):
        if ((code[:3] == "600") | (code[:3] == "900") | (code[:3] == "688")):   #上证A股600,上证B股900,科创板688
            exchange = "sh"
        elif ((code[:2] == "43") | (code[:2] == "83") | (code[:2] == "87")): #新三板43和83,87
            exchange = "sb"
        elif ((code[:3] == "000") | (code[:3] == "200")): #深证A股000,深证B股200
            exchange = "sz"
        elif ((code[:3] == "002")): #中小板002
            exchange = "sz"
        elif ((code[:3] == "300")): #创业板300
            exchange = "sz"
        # else:
            # exchange = "sz"        #其他默认sz
        url = self._prefix_url + exchange + code
        info = self.http_request(url)
        result = self.data_format(info)
        return result

    #数据标准化函数
    def data_format(self, data):
        rawdata = re.search('(")(.+)(")', data).group(2)
        stockdata = rawdata.split(",")
        if ((stockdata[0] == "道琼斯") | (stockdata[0] == "纳斯达克") | (stockdata[0] == "标普500指数")):
            ts = int(time.mktime(time.strptime(stockdata[3], "%Y-%m-%d %H:%M:%S")))
            dict = {
   'code': code,
                    'name': stockdata[0],
                    'open': float(stockdata[5]),
                    'high': 
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

比特量化

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值