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'])


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-20-7376f88e29d3> in <module>()
      1 datadf = pd.read_json(data)
----> 2 set(datadf['date'])

c:\python27\lib\site-packages\pandas\core\frame.pyc in __getitem__(self, key)
   2057             return self._getitem_multilevel(key)
   2058         else:
-> 2059             return self._getitem_column(key)
   2060 
   2061     def _getitem_column(self, key):

c:\python27\lib\site-packages\pandas\core\frame.pyc in _getitem_column(self, key)
   2064         # get column
   2065         if self.columns.is_unique:
-> 2066             return self._get_item_cache(key)
   2067 
   2068         # duplicate columns & possible reduce dimensionality

c:\python27\lib\site-packages\pandas\core\generic.pyc in _get_item_cache(self, item)
   1384         res = cache.get(item)
   1385         if res is None:
-> 1386             values = self._data.get(item)
   1387             res = self._box_item_values(item, values)
   1388             cache[item] = res

c:\python27\lib\site-packages\pandas\core\internals.pyc in get(self, item, fastpath)
   3541 
   3542             if not isnull(item):
-> 3543                 loc = self.items.get_loc(item)
   3544             else:
   3545                 indexer = np.arange(len(self.items))[isnull(self.items)]

c:\python27\lib\site-packages\pandas\indexes\numeric.pyc in get_loc(self, key, method, tolerance)
    339             pass
    340         return super(Float64Index, self).get_loc(key, method=method,
--> 341                                                  tolerance=tolerance)
    342 
    343     @property

c:\python27\lib\site-packages\pandas\indexes\base.pyc in get_loc(self, key, method, tolerance)
   2134                 return self._engine.get_loc(key)
   2135             except KeyError:
-> 2136                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2137 
   2138         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)()

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4363)()

KeyError: '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