# -*- coding: utf-8 -*-
"""
Created on 20180309

@author: zhoushuai
"""

import pandas as pd
import pyodbc
import ky


sdk = ky.Api("http://data-api.kuaiyutech.com/api.rpc")

import logging
logger = logging.getLogger(__name__)
try:
    from ..BT.stock import Stock
    from ..BT.index import Index 
    logger.setLevel(logging.CRITICAL)
    from ..util.kySDK import *
    from .apiParent import ApiParent
except:
    import sys   
    #D:\Project\益盟\回测框架\KYBT\BT
    sys.path.insert(0, 'D:/Project/YM/BackTesting Frame/KYBT/BT') 
    sys.path.insert(0, 'D:/Project/YM/BackTesting Frame/KYBT/util')
    print(sys.path)
    from stock import Stock 
    from index import Index
    from kySDK import *
    from apiParent import ApiParent
    logger.setLevel(logging.WARNING)


class API(ApiParent):

    def __init__(self,DSN): 
        super().__init__(DSN)

    def getGrowthRateOperatingRevenue(self,date,stock,option,range):
        '''
        主营业务收入增长率  
         
        date: str '2017-01-01'
        stock: list ## [600000,000002]
        range float, ## 大于30%, 30%~20%, 20%~15%, 15%~10%, 10%~7.5%, 7.5%~5%, 5%~2.5%, 2.5%~0, 小于0,
        option 'recent period'|'recent year'|'recent three year' ## 最近一期,最近一年,最近三年  
        '''
        itemString = 'SecuCode,SecuAbbr,TradeDate,TradeStatus,PreClosePrice,OpenPrice,ClosePrice,HighPrice,LowPrice,TurnoverVolume,TurnoverValue,ChangeRatio'
        
    
        query = "SELECT %s FROM [dbo].[CY_FinacialRatio_RP] where SecuCode = %s ORDER BY EndDate DESC "
        #print(query)
        self.cursor.execute(query)

        raw = self.cursor.fetchall()
        logger.info('raw :',raw)

        if not raw:
            logger.critical( 'index market value has no data, return None')
            return None
        
        indexPD = self.pandaData(raw,itemString)
        indexPD.fillna(value=0, inplace=True) # to replace None with value 0
        return self.pdToIndexObjectList(indexPD)


if __name__ == '__main__':
    logger.warn(__file__)
    myAPI = API('BTEMmidd2')
    myAPI.init()
    y = myAPI.getGrowthRateOperatingRevenue('2017-05-05','600000','recent period',0.3,)
    print(y)