這里由于開發(fā)一個(gè)matlab版本的API數(shù)據(jù)接口需要,經(jīng)過matlab理张,的urlread、webread以及私人寫的urlread2的無限折磨后依然決定放棄悟耘,繼續(xù)用matlab寫api接口暂幼。matlab的版本是2016b移迫,據(jù)說2015版本以上才行厨埋,沒有親自試過(前提是在已安裝組件包含python,查看方式matlab根目錄/extern/engines/python)雨效。
主要參考:matlab的官方幫助文檔
基本
1.版本信息已經(jīng)更改python版本
查看版本信息這里默認(rèn)Python的環(huán)境變量設(shè)置是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
下面改下默認(rèn)環(huán)境變量渣蜗,我這里Python2和python3同時(shí)存在一個(gè)目錄下耕拷,環(huán)境變量設(shè)置了一個(gè)PYTHON_HOME:僅僅改下這里即可,方便省事浸赫。matlab需要重啟才能生效T甙怼1滩椤校仑!
>> pyversion
version: '2.7'
executable: 'C:\software\python2\python.EXE'
library: 'C:\Windows\system32\python27.dll'
home: 'C:\software\python2'
isloaded: 1
2.調(diào)用Python的module的方法或函數(shù)
調(diào)用Python的module很簡(jiǎn)單
import py.numpy.arange %不建議
x = arange(3);
cal = py.calendar.TextCalendar; %建議方法
% 重點(diǎn)是在于調(diào)用自定義的函數(shù)或者方法羊瘩,并不能直接采用上面的方法
py.sys.path % 查看Python的module搜尋路徑
>> count(py.sys.path,'')
ans =
int64
1 % 已經(jīng)添加當(dāng)前目錄盼砍,matlab從1開始計(jì)算index
>> insert(py.sys.path, int32(0), 'D:\PycharmProjects\SupwinPython2\API') %插入指定的目錄
%在該目錄下創(chuàng)建了一個(gè)matlab.py文件
%a = 1
%b = 2
%c = a + b
>> py.matlab.a
ans =
int64
1
>> py.matlab.c
ans =
int64
3
實(shí)例
- 版本
matlab版本 > =2015a
python = 2.7/3.4 / 3.5
- 環(huán)境變量設(shè)置
需要在windows path中配置好對(duì)應(yīng)Python的環(huán)境變量
example:
PYTHON_HOME: C:\software\python2
path中添加:%PYTHON_HOME%\Scripts浇坐、%PYTHON_HOME%\睬捶、%PYTHON_HOME%\Lib\
code
- matlab 代碼
classdef dataAPI
%UNTITLED3 此處顯示有關(guān)此類的摘要
% 此處顯示詳細(xì)說明
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); % 將數(shù)據(jù)cell轉(zhuǎn)化為list傳入
date=py.str(date);
temp=cell(py.api.API.get_factor(obj.Token, date, fields)); % 返回值是一個(gè)包含
nrow=numel(temp);
ncol=3;
res=cell(nrow, ncol);
%按行轉(zhuǎn)化數(shù)據(jù)
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: lichaolfm@163.com
@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: 指定因子(可輸入多個(gè)因子)
"""
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'} # 生成用于獲取數(shù)據(jù)的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'} # 生成用于獲取數(shù)據(jù)的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)