更新:2023/5/21
    掘金现在免费数据限制,已经弃用。想要免费数据,用极智量化,日线全部,分钟约近一年,tick数据3天。
    机智量化有个好处,能够直接读取价差的最高价,最低价(当然要是机智内的套利合约),自定义合约依然不能获取最高价,最低价。除非用tick数据合成。

用途:读取股票A股,期货,股指期货历史数据
版本3:
更新时间:2022-11-20
说明:类封装Sina

其他:
本人是小白,没有钱购买数据,推荐几个免费的数据读取。
掘金的期货数据相对来说比较多,支持最近3个月的tick数据,1996年至今的分钟数据,全部日频数据。
做分析可以,但读取速度不快,做界面的实时读取太慢,另一优点支持回测无限制,仅需注册一个账号。
另外比较不方便的是读取数据时终端必须打开。

天勤量化api编写较好,数据读写快,支持免费的实盘交易。另外做界面实时数据读取比较方便。
缺点是要想读取数据受限(8000根k线不是你想象中,当然收费的没这个限制),多数要收费;回测受限;
另外一个优点是直接调用api,比较方便,交易的建议使用

新浪财经的仅仅适合入门级的学习,数据读取受限

def get_calendar(cls):
    用途:获取新浪日期
def get_contract_inf_sina(cls, symbol='AP2101'):
    用途:查询期货合约详情
def get_main_name(cls):
    用途:获取国内期货连续合约的名称sina
def get_main_day(cls, symbol='V0', startdate='20220901', enddate=''):
    用途:新浪财经期货-主力连续日数据,不含今天数据-不稳定常报错
def get_realtimeprice(cls, symbol='V2209,V2211', market=''):
    用途:获取新浪-国内期货实时行情数据
def get_kline_day(cls, symbol="V2105"):
    用途:内盘-历史行情数据-新浪 新浪财经-期货-日频数据
def get_kline(cls, symbol='m2201', freq='d', market='期货', **kws):
    用途:获取sina股票期货指定周期的人历史1023个数据
        
def test_sina(sina):

版本3:类封装

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @Project:TcyQuantTrade
# @Module:futures_sina

# @Author:       tcy
# @Date:         2022/9/28  17:52
# @Emial:        3615693665@qq.com
# @Version:     2.0
# @Last Modified time:
# @City:           China Shanghai Songjiang Xiaokunshan
# @Company:  Weishi Machinery Manufacturing Priority

from datetime import datetime,date
import re
import akshare as ak
import pandas as pd
from urllib import request
import json


class Sina(object):

    def __init__(self): pass

    @classmethod
    def get_calendar(cls):
        # type:()->pd.DataFrame
        """
        用途:获取新浪日期
        返回:
                    trade_date
            0     1990-12-19
            1     1990-12-20
                     ...
            7826  2022-12-29
            7827  2022-12-30
        """
        return ak.tool_trade_date_hist_sina()

    # 获取期货合约信息
    @classmethod
    def get_contract_inf_sina(cls, symbol='AP2101'):
        # type:(str)->pd.DataFrame
        """
        用途:查询期货合约详情
        参数:
         symbol: str 合约
         return: 期货合约详情  pd.DataFrame  columns=['item','value']
        网站:https://finance.sina.com.cn/futures/quotes/V2101.shtml

        -----------------------------------------------------------------------------------------
        实例:ak.futures_contract_detail()
        输出:
               item                     value
        0      交易品种            鲜苹果
        1      最小变动价位    1元/吨
        2      交易时间           上午 09:00-10:15 10:30-11:30 下午 13:30-15:00
        3      交割品级            符合《中华人民共和国国家标准 鲜苹果》
                                        (GB/T 10651-2008)(以下简称《苹果国标...
        4      交割方式            实物交割
        5      交易单位           10吨/手
        6      涨跌停板幅度    上一交易日结算价的±5%
        7      最后交易日        合约交割月份的第10个交易日
        8      最低交易保证金    合约价值的7%
        9      交易代码            AP
        10    报价单位           元(人民币)/吨
        11    合约交割月份    1、3、5、7、10、11、12月
        12    最后交割日       仓单交割:合约交割月份的第12个交易日 车(船)板交割:合约
        13    交易手续费        5.00 元/手,平今仓5.00元/手
        14    上市交易所        郑州商品交易所
        """
        return ak.futures_contract_detail(symbol)


    # sina期货连续合约名称
    @classmethod
    def get_main_name(cls):
        # type:()->pd.DataFrame
        """
        用途:获取国内期货连续合约的名称sina
        返回:pd.DataFrame cols=[symbol,exchange,name]

        实例:
        df = ak.futures_display_main_sina()
        df.columns #Index(['symbol', 'exchange', 'name'], dtype='object')
        df

           symbol exchange         name  code
        0      V0      dce        PVC连续      V
        1      P0      dce        棕榈油连续
        ..    ...      ...          ...
        63    IC0    cffex  中证500指数期货连续
        64    TS0    cffex    2年期国债期货连续
        """
        return ak.futures_display_main_sina()

    @classmethod
    def get_main_day(cls, symbol='V0', startdate='20220901', enddate=''):
        # type:(str,str,str)->pd.DataFrame
        """
        用途:新浪财经期货-主力连续日数据,不含今天数据-不稳定常报错
        参数:
        symbol: str 通过 ak.futures_display_main_sina() 函数获取 symbol
        start_date: str 开始时间
        end_date: str 结束时间

        返回: DataFrame主力连续日数据;日期为str,其他为int  cols=[
            [日期, 开盘价, 最高价, 最低价, 收盘价, 成交量, 持仓量, 动态结算价]
        说明:日期为str,其他为int

        原函数:
        ak.futures_main_sina(symbol: str = 'V0', start_date: str = '19900101',
            end_date: str = '22220101') -> 'DataFrame'

        实例:
        ak.futures_main_sina(
    symbol= 'V0',
    start_date = '19900101',
     end_date = '22220101')

                      日期   开盘价   最高价   最低价   收盘价      成交量     持仓量  动态结算价
        0     2009-05-25  6575  6630  6435  6490   107764   12278      0
        1     2009-05-26  6485  6540  6445  6460    38290   10562      0
                 ...   ...   ...   ...   ...      ...     ...    ...
        3237  2022-09-23  6230  6269  6088  6100  1144145  712168   6170
        3238  2022-09-26  6060  6122  6010  6104  1016829  691095   6075
        """
        enddate = enddate if enddate else date.today().strftime('%Y%m%d')
        return ak.futures_main_sina(symbol, startdate, enddate)

    # sina期货合约实时数据
    @classmethod
    def get_realtimeprice(cls, symbol='V2209,V2211', market=''):
        # type:(str,str)->pd.DataFrame
        """
        用途:获取新浪-国内期货实时行情数据
        参数:
        symbol:str 合约名称的组合'V2205, P2205, B2201, M2205',
        market:str  "CF"商品期货, "FF": 金融期货
        adjust	str	adjust='0'; adjust='1':
            返回合约、交易所和最小变动单位的实时数据, 返回数据会变慢

        返回:期货的实时行情数据 pd.DataFrame cols=[
            'symbol', 'time', 'open', 'high', 'low', 'current_price', 'bid_price',
            'ask_price', 'buy_vol', 'sell_vol', 'hold', 'volume', 'avg_price',
            'last_close', 'last_settle_price']

        原函数:
            futures_zh_spot(symbol: str = 'V2205, P2205, B2201, M2205',
                market: str = 'CF', adjust: str = '0') -> 'DataFrame'

        实例:
       a=ak.futures_zh_spot('V2209,V2211','CF')

        a

            symbol    time    open    high     low  current_price  bid_price  \
        0  PVC2209  151003  6503.0  6550.0  6400.0         6400.0     6400.0
        1  PVC2211  151014  6261.0  6283.0  6086.0         6205.0     6202.0

           ask_price  buy_vol  sell_vol     hold  volume  avg_price  last_close  \
        0     6700.0        7        20      0.0    1057     6756.0      6400.0
        1     6205.0        2         1  79253.0   64222     6176.0      6205.0

           last_settle_price
        0             6600.0
        1             6227.0

        a.dtypes

        symbol              object
        time                   object
        open                  float64
        high                   float64
        low                     float64
        current_price     float64
        bid_price            float64
        ask_price           float64
        buy_vol              int64
        sell_vol               int64
        hold                    float64
        volume               int64
        avg_price           float64
        last_close           float64
        last_settle_price float64
        dtype: object
        """
        market = market if market else 'CF'
        return ak.futures_zh_spot(symbol, market)

    # sina期货指定合约的历史数据-日频
    @classmethod
    def get_kline_day(cls, symbol="V2105"):
        # type:(str)->pd.DataFrame
        """
        用途:内盘-历史行情数据-新浪 新浪财经-期货-日频数据
        限量:单次返回指定 symbol 的所有日频数据
        参数:
            symbol: str	symbol="V2105";具体合约可以通过
            ak.match_main_contract(symbol="shfe") 获取或者访问网页

        接口: futures_zh_daily_sina
        目标地址: https://finance.sina.com.cn/futures/quotes/V2105.shtml

        输出:DataFrame cols=
        ['date', 'open', 'high', 'low', 'close', 'volume', 'hold', 'settle']

        名称	类型	  描述
        date	 object	      -
        open float64	开盘价
        high	 float64	最高价
        low	 float64	最低价
        close	float64	收盘价
        volume int64	成交量
        hold	     int64	持仓量
        settle	float64	结算价

        ------------------------------------------------------------------------------------------
        示例:
        import akshare as ak
        df = ak.futures_zh_daily_sina(symbol="V2105")

                   date       open       high  ... volume   hold     settle
        0    2021-01-08  29500.000  30680.000  ...  91045  14988  28290.000
        1    2021-01-11  26225.000  26720.000  ...  23026  17600  26260.000
        ..          ...        ...        ...  ...    ...    ...        ...
        144  2021-08-12  17000.000  17195.000  ...  11215  21211  17055.000
        145  2021-08-13  17000.000  17080.000  ...  10536  20793  16865.000
        """
        return ak.futures_zh_daily_sina(symbol)

    # sina 国内期货合约分时数据-速度快
    @classmethod
    def get_kline_min(cls, symbol="TF2009", period="1"):
        # type:(str,str)->pd.DataFrame
        """
        用途:内盘-分时行情数据(新浪财经-期货-分时数据)
        接口:futures_zh_minute_sina
        目标地址:http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_3
        限量:单次返回指定 symbol 和 period 的分时数据

        参数:
        symbol:str 具体合约(期货品种符号需要大写)如"IF2008"
            通过ak.match_main_contract(symbol="cffex") 获取,或访问网页
        period	str	period="1"; choice of {
            "1": "1分钟", "5": "5分钟", "15": "15分钟", "30": "30分钟", "60": "60分钟"}

        输出:DataFrame cols=
            ['datetime', 'open', 'high', 'low', 'close', 'volume', 'hold']

        名称	    类型    描述
        datetime	object	 -
        open	    float64	 -
        high	        float64  -
        low	        float64	 -
        close	    float64	 -
        volume	int64	 -
        hold	        int64	持仓量

        示例:
        import akshare as ak
        df = ak.futures_zh_minute_sina(symbol="TF2009", period="1")
        df
        结果:
                        datetime              open       high        low        close volume   hold
        0     2020-07-15 14:47:00  100.610  100.625  100.610  100.610     63  45082
        1     2020-07-15 14:48:00  100.610  100.615  100.595  100.605     45  45068
                           ...      ...      ...      ...      ...    ...    ...
        1021  2020-07-21 14:18:00  101.095  101.095  101.080  101.080  30  43938
        1022  2020-07-21 14:19:00  101.080  101.095  101.080  101.085  43  43941
        """
        return ak.futures_zh_minute_sina(symbol, period)

    # sina A股国内期货合约分时数据-速度快
    @classmethod
    def get_kline(cls, symbol='m2201', freq='d', market='期货', **kws):
        # type:(str,str,str,Any)->pd.DataFrame
        """
        用途:获取sina股票期货指定周期的人历史1023个数据
        返回:DataFrame  columns name [date,open,high,low,close,volume]
        参数:
        symbol: str 品种代码,
        freq: str 周期(5m,15m,30m,60m日线),d数据长度最大1023
        mode=['股票','期货','股指期货']
        kws:仅用于A股

        原函数:
        stock_zh_a_daily(symbol: str = 'sh603843', start_date: str = '19900101',
            end_date: str = '21000118', adjust: str = '') ->‘DataFrame’
        参数:
        start_date: str = '19900101',
        end_date: str = '21000118',
        adjust: str = '' 默认为空: 返回不复权的数据;
            qfq: 返回前复权后的数据; hfq: 返回后复权后的数据;
            hfq-factor: 返回后复权因子; hfq-factor: 返回前复

        实例:
        get_sina_kline(symbol='sh000001', freq='60m', market='股票')
        get_sina_kline(symbol='sh000001', freq='d', market='股票')
        get_sina_kline(symbol='rb1910', freq='60m', market='期货')
        get_sina_kline(symbol='rb1910', freq='d', market='期货')
        get_sina_kline(symbol='IF1908', freq='60m', market='股指期货')
        get_sina_kline(symbol='IF1908', freq='d', market='股指期货')

        说明:
        股票历史数据API:
        5分钟:https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=sh000001&scale=5&datalen=1023
        15分钟:https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=sh000001&scale=15&datalen=1023
        30分钟:https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=sh000001&scale=30&datalen=1023
        60分钟:https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=sh000001&scale=60&datalen=1023

        商品期货历史数据API:
        5分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesMiniKLine5m?symbol=rb1910
        15分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesMiniKLine15m?symbol=rb1910
        30分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesMiniKLine30m?symbol=rb1910
        60分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesMiniKLine60m?symbol=rb1910
        日K线:http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesDailyKLine?symbol=rb1910

        股指期货历史数据API:
        5分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesMiniKLine5m?symbol=IF1908
        15分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesMiniKLine15m?symbol=IF1908
        30分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesMiniKLine30m?symbol=IF1908
        60分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesMiniKLine60m?symbol=IF1908
        日线:http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesDailyKLine?symbol=IF1908
        """
        cols = ['date', 'open', 'high', 'low', 'close', 'volume']
        if market == '股票':
            if freq in ['5m', '15m', '30m', '60m']:
                url = 'https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=%s&scale=%s&datalen=1023' % (
                    symbol, freq[:-1])
            else:
                def data(
                    key, default): return kws[key] if key in kws else default
                start_date = data('start_date', '19900101')
                end_date = data('end_date', '20000101')
                adjust = data('adjust', '')
                df = ak.stock_zh_a_daily(symbol, start_date, end_date, adjust)
                return df[cols]

        elif market == '期货':
            if freq in ['5m', '15m', '30m', '60m']:
                url = 'http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesMiniKLine%s?symbol=%s' % (
                    freq, symbol)
            else:
                url = 'http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesDailyKLine?symbol=%s' % (
                    symbol)
        else:
            if freq in ['5m', '15m', '30m', '60m']:
                url = 'http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesMiniKLine%s?symbol=%s' % (
                    freq, symbol)
            else:
                url = 'http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesDailyKLine?symbol=%s' % (
                    symbol)

        req = request.Request(url)
        rsp = request.urlopen(req)
        res = rsp.read()
        res_json = json.loads(res)
        df = pd.DataFrame(res_json)
        if market == '股票':
            df.rename(columns={'day': 'date'}, inplace=True)
            df = df[cols]
        else:
            df.rename(columns=dict(zip(df.columns, cols)), inplace=True)
        return df


def test_sina(sina):
    print()
    print('test sina futures func start...')

    names = sina.get_main_name()  # sina期货连续合约名称
    print('1.1.期货连续合约名=\n', names)
    try:
        df = sina.get_main_day()  # sina期货连续合约历史数据-不稳定常报错
        print('1.2.期货连续合约历史数据=\n', df)
    except Exception as e:
        print('err=\n', e)

    df = sina.get_realtimeprice()
    print('2.1.期货合约实时数据=\n', df)

    df = sina.get_kline_day()
    print('2.2.期货连续合约历史数据-日频=\n', df)

    df = sina.get_kline_min()  # sina A股国内期货合约分时数据-速度快
    print('2.3.A股期货合约分时数据=\n', df)

    df = sina.get_kline()
    print('2.4.期货合约分时数据=\n', df)

    """
    test sina futures func start...
    1.1.期货连续合约名=
        symbol exchange         name
    0      V0      dce        PVC连续
    1      P0      dce        棕榈油连续
    2      B0      dce         豆二连续
    3      M0      dce         豆粕连续
    4      I0      dce        铁矿石连续
    ..    ...      ...          ...
    61    TF0    cffex    5年期国债期货连续
    62    IH0    cffex   上证50指数期货连续
    63    IC0    cffex  中证500指数期货连续
    64    TS0    cffex    2年期国债期货连续
    65    IM0    cffex   中证连续指数期货连续
    
    [66 rows x 3 columns]
    1.2.期货连续合约历史数据=
                 日期   开盘价   最高价   最低价   收盘价      成交量     持仓量  动态结算价
    0   2022-09-01  6220  6350  6210  6302   804836  456624   6284
    1   2022-09-02  6281  6376  6160  6213  1047886  484266   6266
    2   2022-09-05  6267  6420  6243  6404  1146915  464630   6357
    3   2022-09-06  6404  6437  6347  6405   787150  479054   6388
    4   2022-09-07  6376  6466  6305  6362   949583  467781   6373
    5   2022-09-08  6380  6475  6342  6438   963735  469471   6398
    6   2022-09-09  6440  6583  6412  6559  1009380  486271   6489
    7   2022-09-13  6660  6674  6526  6541   611532  503629   6574
    8   2022-09-14  6517  6527  6319  6343  1154538  559391   6404
    9   2022-09-15  6350  6423  6281  6292  1034485  586004   6349
    10  2022-09-16  6270  6307  6230  6278   849857  598962   6269
    11  2022-09-19  6270  6320  6150  6156  1010248  676832   6237
    12  2022-09-20  6150  6226  6122  6133   938762  698700   6164
    13  2022-09-21  6130  6146  6035  6087  1098892  764709   6088
    14  2022-09-22  6082  6244  6042  6230  1199842  697233   6139
    15  2022-09-23  6230  6269  6088  6100  1144145  712168   6170
    16  2022-09-26  6060  6122  6010  6104  1016829  691095   6075
    17  2022-09-27  6099  6130  5951  6065  1212123  749351   6041
    2.1.期货合约实时数据=
         symbol    time    open  ...  avg_price  last_close  last_settle_price
    0  PVC2209  151003  6503.0  ...     6756.0      6400.0             6600.0
    1  PVC2211  151013  6201.0  ...     6225.0      6230.0             6176.0
    
    [2 rows x 15 columns]
    2.2.期货连续合约历史数据-日频=
                date    open    high     low   close  volume  hold  settle
    0    2020-05-20  5730.0  5920.0  5730.0  5880.0     176   134     0.0
    1    2020-05-21  5905.0  5980.0  5875.0  5955.0     287   284     0.0
    2    2020-05-22  5940.0  6025.0  5930.0  5980.0     801   888     0.0
    3    2020-05-25  6000.0  6075.0  5970.0  6020.0     391  1028     0.0
    4    2020-05-26  6030.0  6050.0  5990.0  6025.0     267  1141     0.0
    ..          ...     ...     ...     ...     ...     ...   ...     ...
    238  2021-05-13  9460.0  9640.0  9330.0  9330.0    1016  8384  9430.0
    239  2021-05-14  9430.0  9500.0  9300.0  9300.0     369  8061  9405.0
    240  2021-05-17  9320.0  9320.0  9320.0  9320.0     200  8061  9320.0
    241  2021-05-18  9500.0  9500.0  9500.0  9500.0      26  8035  9500.0
    242  2021-05-19  9995.0  9995.0  9995.0  9995.0     245     0  9375.0
    
    [243 rows x 8 columns]
    2.3.A股期货合约分时数据=
                      datetime     open     high      low    close  volume   hold
    0     2020-08-20 13:23:00  100.435  100.445  100.435  100.445       9  11527
    1     2020-08-20 13:24:00  100.445  100.445  100.435  100.435      11  11525
    2     2020-08-20 13:25:00  100.435  100.445  100.435  100.440      18  11531
    3     2020-08-20 13:26:00  100.445  100.445  100.445  100.445      14  11530
    4     2020-08-20 13:27:00  100.445  100.450  100.445  100.445      23  11516
    ...                   ...      ...      ...      ...      ...     ...    ...
    1018  2020-09-10 14:36:00  100.120  100.120  100.105  100.105      10    101
    1019  2020-09-10 14:38:00  100.105  100.105  100.105  100.105       4    104
    1020  2020-09-10 14:42:00  100.105  100.105  100.105  100.105       5    104
    1021  2020-09-10 14:47:00  100.105  100.105  100.095  100.095       5    105
    1022  2020-09-10 15:13:00  100.095  100.095  100.070  100.075      10    115
    
    [1023 rows x 7 columns]
    2.4.期货合约分时数据=
                date      open      high       low     close volume
    0    2021-01-18  3579.000  3580.000  3466.000  3503.000  34588
    1    2021-01-19  3495.000  3535.000  3480.000  3490.000  13491
    2    2021-01-20  3497.000  3499.000  3354.000  3380.000  32521
    3    2021-01-21  3380.000  3408.000  3361.000  3396.000  10622
    4    2021-01-22  3416.000  3416.000  3311.000  3326.000  16590
    ..          ...       ...       ...       ...       ...    ...
    239  2022-01-10  3483.000  3483.000  3483.000  3483.000     51
    240  2022-01-11  3492.000  3500.000  3288.000  3472.000   2074
    241  2022-01-12  3473.000  3473.000  3446.000  3446.000    367
    242  2022-01-13  3473.000  3473.000  3446.000  3483.000      0
    243  2022-01-14  3473.000  3473.000  3446.000  3483.000    367
    
    [244 rows x 6 columns]
    """
if __name__ == '__main__':
    sina = Sina()
    test_sina(sina)

版本2: 

import numpy as np
import pandas as pd
import akshare as ak
import datetime
from urllib import request
import json

def get_sina_kline(symbol='m2201', period='d', market='期货',**kwargs) -> 'DataFrame':
    '''
    用途:获取sina股票期货指定周期的人历史1023个数据
    返回:DataFrame  columns name [date,open,high,low,close,volume]
    参数:
    symbol品种代码,
    period是周期(5m,15m,30m,60m日线),datalen是获取数据的长度,最大就是1023
    mode=['股票','期货','股指期货']
    kwargs:仅用于A股
    stock_zh_a_daily(symbol: str = 'sh603843', start_date: str = '19900101', end_date: str = '21000118', adjust: str = '') ->‘DataFrame’
    start_date: str = '19900101',
    end_date: str = '21000118',
    adjust: str = '' 默认为空: 返回不复权的数据;
        qfq: 返回前复权后的数据; hfq: 返回后复权后的数据; hfq-factor: 返回后复权因子; hfq-factor: 返回前复

    实例:
    get_sina_kline(symbol='sh000001', period='60m', market='股票')
    get_sina_kline(symbol='sh000001', period='d', market='股票')
    get_sina_kline(symbol='rb1910', period='60m', market='期货')
    get_sina_kline(symbol='rb1910', period='d', market='期货')
    get_sina_kline(symbol='IF1908', period='60m', market='股指期货')
    get_sina_kline(symbol='IF1908', period='d', market='股指期货')

    说明:
    股票历史数据API:
    5分钟:https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=sh000001&scale=5&datalen=1023
    15分钟:https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=sh000001&scale=15&datalen=1023
    30分钟:https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=sh000001&scale=30&datalen=1023
    60分钟:https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=sh000001&scale=60&datalen=1023

    商品期货历史数据API:
    5分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesMiniKLine5m?symbol=rb1910
    15分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesMiniKLine15m?symbol=rb1910
    30分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesMiniKLine30m?symbol=rb1910
    60分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesMiniKLine60m?symbol=rb1910
    日K线:http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesDailyKLine?symbol=rb1910

    股指期货历史数据API:
    5分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesMiniKLine5m?symbol=IF1908
    15分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesMiniKLine15m?symbol=IF1908
    30分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesMiniKLine30m?symbol=IF1908
    60分钟:http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesMiniKLine60m?symbol=IF1908
    日线:http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesDailyKLine?symbol=IF1908
    '''
    cols = ['date', 'open', 'high', 'low', 'close', 'volume']
    if market == '股票':
        if period in ['5m', '15m', '30m', '60m']:
            url = 'https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=%s&scale=%s&datalen=1023' % (
                symbol, period[:-1])
        else:
            data=lambda key,default:kwargs[key] if key in kwargs else default
            start_date=data('start_date', '19900101')
            end_date = data('end_date', '20000101')
            adjust = data('adjust', '')
            df= ak.stock_zh_a_daily(symbol, start_date, end_date, adjust)
            return df[cols]

    elif market=='期货':
        if period in ['5m', '15m', '30m', '60m']:
            url = 'http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesMiniKLine%s?symbol=%s' % (
                period, symbol)
        else:
            url = 'http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesDailyKLine?symbol=%s' % (
                symbol)
    else:
        if period in ['5m', '15m', '30m', '60m']:
            url = 'http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesMiniKLine%s?symbol=%s' % (
                period, symbol)
        else:
            url = 'http://stock2.finance.sina.com.cn/futures/api/json.php/CffexFuturesService.getCffexFuturesDailyKLine?symbol=%s' % (
                symbol)

    req = request.Request(url)
    rsp = request.urlopen(req)
    res = rsp.read()
    res_json = json.loads(res)
    df= pd.DataFrame(res_json)
    if market == '股票':
        df.rename(columns={'day':'date'}, inplace=True)
        df =df[cols]
    else:
        df.rename(columns=dict(zip(df.columns,cols)), inplace=True)
    return df


# global_gdp_radio_quarterly()
print(get_sina_kline(symbol='IF1908', period='d', market='股指期货'))

#-以下为老版本:

# Name:        新浪财经期货数据python读取
# Purpose:
#
# Author:      tcy shanghai yexie
#
# Created:     05/07/2018
# Copyright:   (c) tcy 2018

# 参考网址:     https://www.aliyun.com/jiaocheng/433081.html
#              http://blog.sina.com.cn/s/blog_7ed3ed3d0101gphj.html

#coding: utf-8


import requests
import sys
import numpy as np


#读实盘数据
#功能:  实时读取新浪财经期货数据
#参数:   请输入要读取的合约名称
#返回值:以数组的形式返回


def read_real_future_data(future_code):
    #    future_code ='M1809'
    #从新浪财经读数据
    url_str = ('http://hq.sinajs.cn/list=' +future_code)
    r = requests.get(url_str)
    #数据处理,保存在临时数组中
    b=list(r)
    str1=b[0].decode(encoding='gbk') +b[1].decode(encoding='gbk')
    str2=str1.split(',')
    str3=str2[0].split('_')[-1]
    str4=str3.split('=')

    ##-------------------------------------------------------------------------
    ##  2018/7/5 shanghai tcy python版本
    ##f=[0,0,0,0,0,0,0,0]
    ##f[0]=str4[0]             #code
    ##f[1]=str4[1].strip('"')  #name
    ##f[2]=str2[17]  #date
    ##f[3]=str2[2]   #open
    ##f[4]=str2[3]   #high
    ##f[5]=str2[4]   #low
    ##f[6]=str2[6]   #close
    ##f[7]=str2[14]  #vol
    ##--------------------------------------------------------------------------
    
    ## numpy版本运行速度快
    dt=np.dtype([('code','S10'),('name','U10'),('date','datetime64[D]'),('open',np.float32),
               ('high',np.float32),('low',np.float32),('close',np.float32),('vol',np.float32)])


    f=np.array([("","",'1970-01-01',0.0,0.0,0.0,0.0,0.0)],dtype=dt)
    f[0]['code']=str4[0]   #code
    f[0]['name']=str2[16]  #name
    f[0]['date']=str2[17]  #date
    f[0]['open']=str2[2]   #open
    f[0]['high']=str2[3]   #high
    f[0]['low']=str2[4]    #low
    f[0]['close']=str2[6]  #close
    f[0]['vol']=str2[14]   #vol


#测试程序:
f= read_real_future_data('M1809')
print(f)




****************************************************************************
****************************************************************************
一。新浪实时数据读取


    例子
    http://hq.sinajs.cn/list=M0 #豆粕连续 M0


    返回值如下:
    var hq_str_M0="豆粕连续,145958,3170,3190,3145,3178,3153,3154,3154,3162,3169,
                   1325,223,1371608,1611074,连,豆粕,2013-06-28"...;


    ----------------------------------------------------------
    1.数据读出顺序


        0:豆粕连续,名字
        1:145958,数据读取时间
        2:3170,开盘价
        3:3190,最高价
        4:3145,最低价
        5:3178,昨日收盘价 (2018年6月27日)
        6:3153,买价,即“买一”报价
        7:3154,卖价,即“卖一”报价
        8:3154,最新价,即收盘价
        9:3162,结算价
        10:3169,昨结算
        11:1325,买  量
        12:223,卖  量
        13:1371608,持仓量
        14:1611074,成交量
        15:连,大连商品交易所简称
        16:豆粕,品种名简称
        17:2018-06-28,日期
    ----------------------------------------------


    2.新浪期货数据各品种代码(商品连续)如下

         RB0 螺纹钢
         AG0 白银
         AU0 黄金
         CU0 沪铜
         AL0 沪铝
         ZN0 沪锌
         PB0 沪铅
         RU0 橡胶
         FU0 燃油
         WR0 线材
         A0 大豆
         M0 豆粕
         Y0 豆油
         J0 焦炭
         C0 玉米
         L0 乙烯
         P0 棕油
         V0 PVC
         RS0 菜籽
         RM0 菜粕
         FG0 玻璃
         CF0 棉花
         WS0 强麦
         ER0 籼稻
         ME0 甲醇
         RO0 菜油
         TA0 甲酸
         CFF_RE_IF1307  股指期货


    3.使用方法
      3.1.品种名 + 0 (数字0),代表品种连续,如果是其他月份,请使用品种名 + YYYMM
          例如
              豆粕 2013年09月,M1309
              http://hq.sinajs.cn/list=M1309

      3.2.一次可以请求多个品种,例如


              http://hq.sinajs.cn/list=CFF_RE_IF1307,TA0,M0,CFF_RE_IF1306,RB1309,M1309,SR1309


********************************************************************************************
二。历史数据读取

    商品期货
    http://stock2.finance.sina.com.cn/futures/api/json.php/
    IndexService.getInnerFuturesMiniKLineXm?symbol=CODE
    例子:
        http://stock2.finance.sina.com.cn/futures/api/json.php/
        IndexService.getInnerFuturesMiniKLine5m?symbol=M0
    5分钟
        http://stock2.finance.sina.com.cn/futures/api/json.php/
        IndexService.getInnerFuturesMiniKLine5m?symbol=M0
    15分钟
        http://stock2.finance.sina.com.cn/futures/api/json.php/
        IndexService.getInnerFuturesMiniKLine15m?symbol=M0
    30分钟
        http://stock2.finance.sina.com.cn/futures/api/json.php/
        IndexService.getInnerFuturesMiniKLine30m?symbol=M0
    60分钟
        http://stock2.finance.sina.com.cn/futures/api/json.php/
        IndexService.getInnerFuturesMiniKLine60m?symbol=M0
    日K线
        http://stock2.finance.sina.com.cn/futures/api/json.php/
        IndexService.getInnerFuturesDailyKLine?symbol=M0


    股指期货
    5分钟
    http://stock2.finance.sina.com.cn/futures/api/json.php/
    CffexFuturesService.getCffexFuturesMiniKLine5m?symbol=IF1306


    15
    http://stock2.finance.sina.com.cn/futures/api/json.php/
    CffexFuturesService.getCffexFuturesMiniKLine15m?symbol=IF1306
    30分钟
    http://stock2.finance.sina.com.cn/futures/api/json.php/
    CffexFuturesService.getCffexFuturesMiniKLine30m?symbol=IF1306


    60分钟
    http://stock2.finance.sina.com.cn/futures/api/json.php/
    CffexFuturesService.getCffexFuturesMiniKLine60m?symbol=IF1306


    日线
    http://stock2.finance.sina.com.cn/futures/api/json.php/
    CffexFuturesService.getCffexFuturesDailyKLine?symbol=IF1306
  ********************************************************************************************
  ********************************************************************************************

实例:
import requests
import sys
future_code = 'M1809'
url_str = ('http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesDailyKLine?symbol=' +
future_code)
r = requests.get(url_str)
r_json = r.json()
r_lists = list(r_json)
print('future_code,date,open,high,low,close,vol')


for r_list in r_lists:
    for v in r_list:
        print(v + ',',end='')
    print('\n')

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐