# Path: kquant_data/wind/wset.py
# def write_constituent(path, df):
#     df.to_csv(path, encoding='utf-8-sig', date_format='%Y-%m-%d', index=False)
# 
# def read_constituent(path):
#     """
#     读取板块文件
#     :param path:
#     :return:
#     """
#     try:
#         df = pd.read_csv(path, encoding='utf-8-sig', parse_dates=True)
#     except Exception as e:
#         return None
#     try:
#         df['date'] = pd.to_datetime(df['date'])
#     except KeyError:
#         pass
#     return df
# 
# def download_sectorconstituent(w, date, sector, windcode, field='wind_code'):
#     """
#     板块成份
#     中信证券一级行业指数：时间好像没有必要，因为日历日也会查询出来
#     风险警示股票：日期就是查询的日期，股票也是最新名，没有啥用
# 
#     w.wset("sectorconstituent","date=2017-03-03;sectorid=a001010100000000;field=wind_code")
#     w.wset("sectorconstituent","date=2017-03-03;sectorid=a001010100000000")
#     w.wset("sectorconstituent","date=2017-03-03;windcode=000300.SH")
#     :param w:
#     :param sector:
#     :param date:
#     :return:
#     """
#     param = 'date=%s' % date
#     if sector:
#         param += ';sector=%s' % sector
#     if windcode:
#         param += ';windcode=%s' % windcode
#     if field:
#         param += ';field=%s' % field
# 
#     w.asDateTime = asDateTime
#     w_wset_data = w.wset("sectorconstituent", param)
#     df = pd.DataFrame(w_wset_data.Data)
#     df = df.T
#     df.columns = w_wset_data.Fields
#     try:
#         df['date'] = pd.to_datetime(df['date'])
#     except KeyError:
#         pass
#     return df
# 
# def download_indexconstituent(w, date, windcode, field='wind_code,i_weight'):
#     """
#     指数权重
#     如果指定日期不是交易日，会返回时前一个交易日的信息
#     :param w:
#     :param windcode:
#     :param date:
#     :return:
#     """
#     param = 'date=%s' % date
#     if windcode:
#         param += ';windcode=%s' % windcode
#     if field:
#         param += ';field=%s' % field
# 
#     w.asDateTime = asDateTime
#     w_wset_data = w.wset("indexconstituent", param)
#     df = pd.DataFrame(w_wset_data.Data)
#     df = df.T
#     df.columns = w_wset_data.Fields
#     return df
# 
# def download_futureoir(w, startdate, enddate, windcode):
#     """
#     品种持仓
#     是将多仓与空仓排名合并到一起，然后按多仓进行统一排名，所以对于空仓要使用时，需要自行重新排名
#     查询的跨度不要太长，一个月或三个月
#     :param w:
#     :param startdate:
#     :param enddate:
#     :return:
#     """
#     w.asDateTime = asDateTime
#     w_wset_data = w.wset("futureoir",
#                          "startdate=%s;enddate=%s;varity=%s;order_by=long;ranks=all;"
#                          "field=date,ranks,member_name,"
#                          "long_position,long_position_increase,long_potion_rate,"
#                          "short_position,short_position_increase,short_position_rate,"
#                          "vol,vol_increase,vol_rate,settle" % (startdate, enddate, windcode))
#     df = pd.DataFrame(w_wset_data.Data)
#     df = df.T
#     df.columns = w_wset_data.Fields
# 
#     try:
#         df['date'] = pd.to_datetime(df['date'])
#     except:
#         pass
# 
#     return df


import os
import shutil
import pandas as pd
from datetime import datetime
from ..wind.wset import write_constituent, read_constituent, download_sectorconstituent, download_indexconstituent, \
    download_futureoir
    move_constituent(foldpath, dst_path)


def download_index_weight(w, trading_days, wind_code, root_path):
    """
    下载指数成份和权重
    :param w:
    :param trading_days:
    :param wind_code:
    :param root_path:
    :return:
    """
    df = trading_days
    df['date_str'] = trading_days['date'].astype(str)

    foldpath = os.path.join(root_path, wind_code)
    file_download_constituent(w, df['date_str'], foldpath, '.csv',
                              sector=None, windcode=wind_code, field='wind_code,i_weight', is_indexconstituent=True)

    dst_path = os.path.join(root_path, "%s_move" % wind_code)
    move_constituent(foldpath, dst_path)


def download_index_weight2(w, dates, wind_code, root_path):
    for date in dates:
        path = os.path.join(root_path, wind_code, date.strftime('%Y-%m-%d.csv'))
        df = read_constituent(path)
        if df is None:
            print("下载权重", path)
            df = download_indexconstituent(w, date.strftime('%Y-%m-%d'), wind_code)

# Path: kquant_data/wind/wset.py
# def write_constituent(path, df):
#     df.to_csv(path, encoding='utf-8-sig', date_format='%Y-%m-%d', index=False)
# 
# def read_constituent(path):
#     """
#     读取板块文件
#     :param path:
#     :return:
#     """
#     try:
#         df = pd.read_csv(path, encoding='utf-8-sig', parse_dates=True)
#     except Exception as e:
#         return None
#     try:
#         df['date'] = pd.to_datetime(df['date'])
#     except KeyError:
#         pass
#     return df
# 
# def download_sectorconstituent(w, date, sector, windcode, field='wind_code'):
#     """
#     板块成份
#     中信证券一级行业指数：时间好像没有必要，因为日历日也会查询出来
#     风险警示股票：日期就是查询的日期，股票也是最新名，没有啥用
# 
#     w.wset("sectorconstituent","date=2017-03-03;sectorid=a001010100000000;field=wind_code")
#     w.wset("sectorconstituent","date=2017-03-03;sectorid=a001010100000000")
#     w.wset("sectorconstituent","date=2017-03-03;windcode=000300.SH")
#     :param w:
#     :param sector:
#     :param date:
#     :return:
#     """
#     param = 'date=%s' % date
#     if sector:
#         param += ';sector=%s' % sector
#     if windcode:
#         param += ';windcode=%s' % windcode
#     if field:
#         param += ';field=%s' % field
# 
#     w.asDateTime = asDateTime
#     w_wset_data = w.wset("sectorconstituent", param)
#     df = pd.DataFrame(w_wset_data.Data)
#     df = df.T
#     df.columns = w_wset_data.Fields
#     try:
#         df['date'] = pd.to_datetime(df['date'])
#     except KeyError:
#         pass
#     return df
# 
# def download_indexconstituent(w, date, windcode, field='wind_code,i_weight'):
#     """
#     指数权重
#     如果指定日期不是交易日，会返回时前一个交易日的信息
#     :param w:
#     :param windcode:
#     :param date:
#     :return:
#     """
#     param = 'date=%s' % date
#     if windcode:
#         param += ';windcode=%s' % windcode
#     if field:
#         param += ';field=%s' % field
# 
#     w.asDateTime = asDateTime
#     w_wset_data = w.wset("indexconstituent", param)
#     df = pd.DataFrame(w_wset_data.Data)
#     df = df.T
#     df.columns = w_wset_data.Fields
#     return df
# 
# def download_futureoir(w, startdate, enddate, windcode):
#     """
#     品种持仓
#     是将多仓与空仓排名合并到一起，然后按多仓进行统一排名，所以对于空仓要使用时，需要自行重新排名
#     查询的跨度不要太长，一个月或三个月
#     :param w:
#     :param startdate:
#     :param enddate:
#     :return:
#     """
#     w.asDateTime = asDateTime
#     w_wset_data = w.wset("futureoir",
#                          "startdate=%s;enddate=%s;varity=%s;order_by=long;ranks=all;"
#                          "field=date,ranks,member_name,"
#                          "long_position,long_position_increase,long_potion_rate,"
#                          "short_position,short_position_increase,short_position_rate,"
#                          "vol,vol_increase,vol_rate,settle" % (startdate, enddate, windcode))
#     df = pd.DataFrame(w_wset_data.Data)
#     df = df.T
#     df.columns = w_wset_data.Fields
# 
#     try:
#         df['date'] = pd.to_datetime(df['date'])
#     except:
#         pass
# 
#     return df


# Path: kquant_data/wind_resume/wset.py
import os
import shutil
import pandas as pd
from datetime import datetime
from ..wind.wset import write_constituent, read_constituent, download_sectorconstituent, download_indexconstituent, \
    download_futureoir

    move_constituent(foldpath, dst_path)


def download_index_weight(w, trading_days, wind_code, root_path):
    """
    下载指数成份和权重
    :param w:
    :param trading_days:
    :param wind_code:
    :param root_path:
    :return:
    """
    df = trading_days
    df['date_str'] = trading_days['date'].astype(str)

    foldpath = os.path.join(root_path, wind_code)
    file_download_constituent(w, df['date_str'], foldpath, '.csv',
                              sector=None, windcode=wind_code, field='wind_code,i_weight', is_indexconstituent=True)

    dst_path = os.path.join(root_path, "%s_move" % wind_code)
    move_constituent(foldpath, dst_path)


def download_index_weight2(w, dates, wind_code, root_path):
    for date in dates:
        path = os.path.join(root_path, wind_code, date.strftime('%Y-%m-%d.csv'))
        df = read_constituent(path)
        if df is None:
            print("下载权重", path)
            df = download_indexconstituent(w, date.strftime('%Y-%m-%d'), wind_code)

            write_constituent(path, df)