In [1]:
#!/Tsan/bin/python
# -*- coding: utf-8 -*-
In [2]:
import httplib
import json
import urllib2
import pandas as pd
In [3]:
import datetime
In [4]:
def getAccessToken(username, userpassword):
headerdata = {"Content-Type":"application/x-www-form-urlencoded"}
requrl = "http://auth.yunkuanke.com/oauth/token?client_id=SDK&client_secret=17273824BE25482086172367DD7DF480&grant_type=password&scope=read&username="+username+"&password="+userpassword
conn = httplib.HTTPConnection("auth.yunkuanke.com")
conn.request(method="POST",url=requrl,body="",headers = headerdata)
response = conn.getresponse()
res= response.read()
data_json = json.loads(res)
data= data_json["data"]
token_dict = json.loads(data)
access_token = token_dict["access_token"]
return access_token
def getposition(accessToken, strategyId, assetType, startdate,enddate):
#查询持仓
#url
url= "http://tradeapi.yunkuanke.com/front/query/queryHistoryPositionList.do"
headerdata = {"access_token":accessToken,"Content-Type":"application/json; charset=utf-8"}
conn = httplib.HTTPConnection("tradeapi.yunkuanke.com")
#传入参数
body_data={"ProductID":strategyId,"AssetType":assetType,"StartDate":startdate, "EndDate":enddate}
body = json.dumps(body_data)
req = urllib2.Request(url, body, headerdata)
res_data = urllib2.urlopen(req)
res_header = res_data.info()
yread = res_data.read()
ystr = ""
if ('Content-Encoding' in res_header and res_header['Content-Encoding'] == 'gzip') or ('content-encoding' in res_header and res_header['content-encoding'] == 'gzip'):
import gzip
import StringIO
ydata = StringIO.StringIO(yread)
ygz = gzip.GzipFile(fileobj = ydata)
yread = ygz.read()
ygz.close()
ystr = yread
else:
ystr = yread
data_json = json.loads(ystr)
dataDetail = data_json["data"]
'''
for detail in dataDetail:
totalVolume = detail["totalVolume"]
orderType = detail["orderType"]
margin = detail["margin"]
code = detail["code"]
incomeBalance = detail["incomeBalance"]
optPosition = detail["optPosition"]
avgPrice = detail["avgPrice"]
floatingProfit = detail["floatingProfit"]
marketValue = detail["marketValue"]
profitRate = detail["profitRate"]
marketType = detail["marketType"]
assetType = detail["assetType"]
yesterdayVolume = detail["yesterdayVolume"]
todayPosition = detail["todayPosition"]
totalCost = detail["totalCost"]
subjectName = detail["subjectName"]
print subjectName'''
return dataDetail
In [33]:
def main():
startdate = "20160701"
enddate = "20170701"
username = "tip"
userpassword = "test123"
#策略ID
strategyId = "7F93F932A9234E989C4354D27617B9F1"
#AssetType
assetType = 1
#登录获取token
accessToken = getAccessToken(username, userpassword)
#查询持仓
return getposition(accessToken, strategyId, assetType,startdate,enddate)
In [34]:
data= main()
In [35]:
data
Out[35]:
In [19]:
data = json.dumps(data)
In [15]:
data
Out[15]:
In [20]:
datadf = pd.read_json(data)
set(datadf['date'])
In [ ]:
datadf
In [ ]:
date = datetime.date.today().isoweekday()
date
In [ ]:
# GET THE WEEKLY NET WORTH DATA OF EACH FUND
import mysql.connector
fundID = '22467' # fundID
tableName ='v2_fund_weekly_performance' # table to query
indexID = 'hs300' # benchmark
def get_fund_data(fundID,tableName =tableName):
cnx = mysql.connector.connect(user='simu_lzjf', password='7VjVNt5Cjw81DjHj',
host='106.75.45.237',port = 15333,
database='CUS_FUND_DB',charset = 'utf8')
try:
#sql_query='select id,name from student where age > %s'
cursor = cnx.cursor()
sql = "select fund_id,statistic_date,swanav from %s where fund_id = '%s'" % (tableName,fundID)
cursor.execute(sql)
result = cursor.fetchall()
finally:
cnx.close()
pdResult = pd.DataFrame(result,dtype =float)
pdResult.columns = ['fund_id','date','net_worth']
pdResult = pdResult.drop_duplicates().set_index('date')
pdResult = pdResult.dropna(axis=0)
pdResult = pdResult.fillna(method = 'ffill')
pdResult ['weekly_return'] = pdResult['net_worth'].pct_change()
return pdResult
In [ ]:
datadf = get_fund_data(fundID,tableName =tableName)
datadf.index[0].isoweekday()
In [ ]:
datadf.index.map(lambda x : x.isoweekday())
In [ ]:
datadf['whichday'] = datadf.index.map(lambda x : x.isoweekday())
datadf