matlab与Python混合开发matlab数据API接口(实例)

这里由于开发一个matlab版本的API数据接口需要,经过matlab,的urlread、webread以及私人写的urlread2的无限折磨后依然决定放弃,继续用matlab写api接口。matlab的版本是2016b,据说2015版本以上才行,没有亲自试过(前提是在已安装组件包含python,查看方式matlab根目录/extern/engines/python)。
主要参考:matlab的官方帮助文档

基本

1.版本信息已经更改python版本
查看版本信息这里默认Python的环境变量设置是3.5版本(仅仅支持3.5、3.4、2.7)

>> pyversion

       version: '3.5'
    executable: 'C:\software\python3\python.EXE'
       library: 'C:\software\python3\python35.dll'
          home: 'C:\software\python3'
      isloaded: 0

下面改下默认环境变量,我这里Python2和python3同时存在一个目录下,环境变量设置了一个PYTHON_HOME:仅仅改下这里即可,方便省事。matlab需要重启才能生效!!!

matlab与Python混合开发matlab数据API接口(实例)_第1张图片
image.png
>> pyversion

       version: '2.7'
    executable: 'C:\software\python2\python.EXE'
       library: 'C:\Windows\system32\python27.dll'
          home: 'C:\software\python2'
      isloaded: 1

2.调用Python的module的方法或函数
调用Python的module很简单

import py.numpy.arange    %不建议
x = arange(3);                       
cal = py.calendar.TextCalendar;   %建议方法
% 重点是在于调用自定义的函数或者方法,并不能直接采用上面的方法
py.sys.path   % 查看Python的module搜寻路径

>> count(py.sys.path,'')

ans =

  int64

   1   % 已经添加当前目录,matlab从1开始计算index

>> insert(py.sys.path, int32(0), 'D:\PycharmProjects\SupwinPython2\API')  %插入指定的目录
%在该目录下创建了一个matlab.py文件
%a = 1
%b = 2
%c = a + b
>> py.matlab.a

ans =

  int64

   1

>> py.matlab.c

ans =

  int64

   3

实例

  • 版本

matlab版本 > =2015a
python = 2.7/3.4 / 3.5

  • 环境变量设置

需要在windows path中配置好对应Python的环境变量
example:
PYTHON_HOME: C:\software\python2
path中添加:%PYTHON_HOME%\Scripts、%PYTHON_HOME%\、%PYTHON_HOME%\Lib\

code

  • matlab 代码
classdef dataAPI
    %UNTITLED3 此处显示有关此类的摘要
    %   此处显示详细说明
    
    properties
        usr;
        passwd;
    end
    
    properties (Dependent)
      Token
   end
    
    methods
        % 初始化类
        function obj=dataAPI(usr, passwd)
            % 添加Python文件所在路径
            insert(py.sys.path, int32(0), 'D:\PycharmProjects\SupwinPython2\API');
            obj.usr=usr;
            obj.passwd=passwd;
        end
    end
    
    methods
        function token=get.Token(obj)
            token=py.api.API.getToken(py.str(obj.usr), py.str(obj.passwd));  % 返回token py.str
        end
        
        function res=get_factors(obj, date, factors)
            fields=py.list(factors);                                     % 将数据cell转化为list传入
            date=py.str(date);
            temp=cell(py.api.API.get_factor(obj.Token, date, fields));   % 返回值是一个包含
            nrow=numel(temp);
            ncol=3;
            res=cell(nrow, ncol);
            %按行转化数据
            for r=1:(nrow)
                temp_row=cell(temp{r});
                for c=1:(ncol)
                    value=temp_row{c};
                    res{r, c}=char(value);
                end
            end
        end
        
        function res=get_quotes(obj, codes, start_date, end_date)
            codes=py.list(codes);
            start_date=py.str(start_date);
            end_date=py.str(end_date);
            temp=py.api.API.getQuotes(obj.Token, codes, start_date, end_date);
            temp=cell(temp);
            nrow=numel(temp);
            ncol=numel(cell(temp{1}));
            res=cell(nrow, ncol);
            for r=1:(nrow)
                temp_row=cell(temp{r});
                for c=1:(ncol)
                    value=temp_row{c};
                    if isnumeric(value)
                        res{r, c}=value;
                    else
                        res{r, c}=char(value);
                    end
                end
            end
        end
        
        function res=get_tradeDays(obj, start_date, end_date, period)
            start_date=py.str(start_date);
            end_date=py.str(end_date);
            period=py.str(period);
            temp=py.api.API.tradeDays(obj.Token, start_date, end_date, period);
            temp=cell(temp);
            nrow=numel(temp);
            ncol=1;
            res=cell(nrow, ncol);
            for r=1:(nrow)
                value=temp{r};
                res{r, 1}=char(value);
            end
        end
        
        function res=get_original_finance(obj, codes, date)
            codes=py.list(codes);
            date=py.str(date);
            temp=py.api.API.getOriginalFinance(obj.Token, codes, date);
            temp=cell(temp);
            nrow=numel(temp);
            ncol=numel(cell(temp{1}));
            res=cell(nrow, ncol);
            for r=1:(nrow)
                temp_row=cell(temp{r});
                for c=1:(ncol)
                    value=temp_row{c};
                    res{r, c}=char(value);
                end
            end
        end
        
        function res=get_allFactors(obj)
            temp=py.api.API.getAllFactors(obj.Token);
            temp=cell(temp);
            nrow=numel(temp);
            ncol=numel(cell(temp{1}));
            res=cell(nrow, ncol);
            for r=1:(nrow)
                temp_row=cell(temp{r});
                for c=1:(ncol)
                    value=temp_row{c};
                    %value
                    if islogical(value)
                        res{r, c}=value;
                    else
                        res{r, c}=char(value);
                    end
                end
            end
        end
    end
    
end
  • python2 代码
# encoding: utf-8

"""
@author: kaenlee  @contact: [email protected]
@software: PyCharm Community Edition
@time: 2017/9/2 14:46
purpose:
"""

import requests
import json
import base64





class API(object):
    @staticmethod
    def getToken(usr, passwd):
        """
        :param usr: 用户
        :param passwd: 密码
        :return:
        """
        body_value = "username=" + usr + "&password=" + passwd + "&grant_type=password&scope=api1 openid"
        clientId = "xxxx"
        clientSecret = "xxxx"
        # 加密操作
        Authorization = 'Basic ' + base64.encodestring(clientId + ':' + clientSecret)[:-1]

        print(Authorization)
        headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': Authorization,
                   'Accept-Language': 'zh-CN,zh;q=0.8', 'Accept': 'application/json, text/plain, */*',
                   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
        url = "http://1505.supwin.com:5000/connect/token"
        result = requests.post(url, headers=headers, data=body_value)
        print(result)
        token = json.loads(result.content)
        token = "Bearer " + token['access_token']
        return token

    @staticmethod
    def get_factor(token, date='20161230', config=["Cap_Supwin", 'BP_MRQ'], marketRegion=0, format=0):
        """
        :param date: 指定日期
        :param config: 指定因子(可输入多个因子)
        """
        url = "xxx.com?date=" + date + "&marketRegion=" + \
              str(marketRegion) + "&format=" + str(format)
        newhead = {'Content-Type': 'application/json; charset=gb2312', 'Authorization': token,
                   'Accept': 'application/json; charset=gb2312'}
        data = requests.post(url, headers=newhead, data=json.dumps(config))

        data = data.json()["result"]
        data = [list(r.values()) for r in data]
        return data

    @staticmethod
    def getQuotes(token, code, start_date, end_date, marketRegion=0, format=0):
        url = "xxx.com?startDate=" + start_date + "&endDate=" + end_date + \
              "&marketRegion=" + str(marketRegion) + "&format=" + str(format)
        newhead = {'Content-Type': 'application/json; charset=gb2312', 'Authorization': token,
                   'Accept': 'application/json; charset=gb2312'}
        data = requests.post(url, headers=newhead, data=json.dumps(code)).json()["result"]
        res = [list(data[0].keys())]
        [res.append(list(r.values())) for r in data]
        return res

    @staticmethod
    def tradeDays(token, start_date, end_date, period, marketRegion=0, format=0):
        url = "xxx.com?endDate=" + end_date + \
              "&startDate=" + start_date + "&period=" + period + "&marketRegion=" + str(
            marketRegion) + "&format=" + str(format)
        newhead = {'Content-Type': 'application/json; charset=gb2312', 'Authorization': token,
                   'Accept': 'application/json; charset=gb2312'}  # 生成用于获取数据的newhead
        data = requests.get(url, headers=newhead).json()["result"]
        res = [j.split(' ')[0].encode('utf-8') for i in data for j in i.values()]
        return res

    @staticmethod
    def getOriginalFinance(token, code, date, marketRegion=0, format=0):
        url = "xxx.com?date=" + date + \
              "&marketRegion=" + str(marketRegion) + "&format=" + str(format)
        newhead = {'Content-Type': 'application/json; charset=gb2312', 'Authorization': token,
                   'Accept': 'application/json; charset=gb2312'}
        data = requests.post(url, headers=newhead, data=json.dumps(code)).json()["result"]
        cols = list(data[0].keys())
        res = [cols]
        [res.append(list(r.values())) for r in data]
        return res

    @staticmethod
    def getAllFactors(token, marketRegion=0, format=0):
        url = "xxx.com?&marketRegion=" + str(marketRegion) + "&format=" + str(
            format)
        newhead = {'Content-Type': 'application/json; charset=gb2312', 'Authorization': token,
                   'Accept': 'application/json; charset=gb2312'}  # 生成用于获取数据的newhead
        #data = requests.get(url, headers=newhead).json()["result"]
        temp=requests.get(url, headers=newhead)
        data=temp.json()["result"]
        cols = list(data[0].keys())
        res = [cols]
        [res.append(list(r.values())) for r in data]
        return res


if __name__ == '__main__':
    username = "xxx";
    password = "xxx"
    token = API.getToken(username, password)
    # data = API.get_factor(token)
    # data = API.getQuotes(token, ['000001.SZ', '00000.SZ'], '20161201', '20161230')
    # data = API.tradeDays(token, '20161201', '20161230', 'D')
    # data = API.getOriginalFinance(token, ['000001.SZ', '000002.SZ'], '20161230')
    # data = API.getAllFactors(token)
    print(token)
    # print(data)

你可能感兴趣的:(matlab与Python混合开发matlab数据API接口(实例))