# from scipy.stats import norm
import math

import pandas as pd
import re
from datetime import datetime

# Wind API
from WindPy import *


def get_wind_data():
    # 启动Wind
    w.start()

    # 获取本地时间
    dateNowTime = datetime.now()
    # 获取本地日期
    dateNow = dateNowTime.strftime('%Y/%m/%d')
    tradeDateNow = dateNowTime.strftime('%Y%m%d')
    # 从Wind取合约代码
    contract_list = w.wset("sectorconstituent", "date=%s;sectorid=1000032699000000" % (dateNow)).Data[1]
    contract_list1 = w.wset("sectorconstituent", "date=%s;sectorid=1000040838000000" % (dateNow)).Data[1]
    contract_list2 = w.wset("sectorconstituent", "date=%s;sectorid=1000043555000000" % (dateNow)).Data[1]
    contract_list3 = w.wset("sectorconstituent", "date=%s;sectorid=1000043560000000" % (dateNow)).Data[1]
    contract_list4 = w.wset("sectorconstituent", "date=%s;sectorid=1000043561000000" % (dateNow)).Data[1]
    contract_list.extend(contract_list1)
    contract_list.extend(contract_list2)
    contract_list.extend(contract_list3)
    contract_list.extend(contract_list4)
    bdfDeli = pd.DataFrame()
    for contractCode in contract_list:
        bond_lis = w.wset("conversionfactor", "windcode=" + contractCode)
        df = pd.DataFrame(bond_lis.Data)
        for index, row in df.iteritems():
            bond = w.wss(row[0],
                         "sec_name,term,ptmyear,carrydate,maturitydate,nxcupn,nxcupn2,couponrate,interestfrequency,actualbenchmark",
                         "tradeDate=%s" % (tradeDateNow))
            bondf = pd.DataFrame()
            bondf['secName'] = bond.Data[0]
            bondf['term'] = '%.4f' % bond.Data[1][0]
            bondf['ptmDay'] = '%.4f' % bond.Data[2][0]
            bondf['carryDate'] = bond.Data[3][0].strftime('%Y/%m/%d')
            bondf['maturityDate'] = bond.Data[4][0].strftime('%Y/%m/%d')
            bondf['nxcupn'] = bond.Data[5][0].strftime('%Y/%m/%d')
            bondf['nxcupn2'] = bond.Data[6]
            bondf['couponRate'] = '%.4f' % bond.Data[7][0]
            bondf['interestFrequency'] = bond.Data[8]
            bondf['actualBenchmark'] = bond.Data[9]
            contractCodeArr = re.split('_|\.', contractCode)
            if "P" in contractCode:
                bondf['contractType'] = contractCodeArr[0] + "_P"
                bondf['contractCode'] = contractCodeArr[1].strip('P')
            else:
                bondf['contractType'] = contractCodeArr[0]
                bondf['contractCode'] = contractCodeArr[1]
            bondf['tradeCode'] = row[0]
            bondf['cf'] = '%.4f' % row[1]
            bdfDeli = pd.concat([bondf, bdfDeli])
    print(bdfDeli.to_dict(orient="records"))


if __name__ == '__main__':
    get_wind_data()
