# Path: kquant_data/xio/csv.py
# def write_data_dataframe(path, df, date_format='%Y-%m-%d'):
#     """
#     写入数据
#     :param path:
#     :param df:
#     :return:
#     """
#     df.to_csv(path, date_format=date_format, encoding='utf-8-sig')
# 
# def read_data_dataframe(path, sep=','):
#     """
#     读取季报的公告日
#     注意：有些股票多个季度一起发，一般是公司出问题了，特别是600878，四个报告同一天发布
#     年报与一季报很有可能一起发
#     :param path:
#     :param sep:
#     :return:
#     """
#     try:
#         df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep)
#     except (FileNotFoundError, OSError):
#         return None
# 
#     return df
# 
# Path: kquant_data/api.py
# def all_instruments(path=None, type=None):
#     """
#     得到合约列表
#     :param type:
#     :return:
#     """
#     if path is None:
#         path = os.path.join(__CONFIG_H5_STK_DIR__, "daily", 'Symbol.csv')
# 
#     df = pd.read_csv(path, dtype={'code': str})
# 
#     return df
# 
# Path: kquant_data/wind_resume/wsd.py
# def resume_download_daily_many_to_one_file(
#         w,
#         wind_codes,
#         field,
#         dtype,
#         enddate,
#         root_path,
#         option='unit=1;rptType=1;Period=Q;Days=Alldays',
#         default_start_date='2000-01-01'):
# def resume_download_daily_one_to_one_file(
#         w,
#         symbol,
#         ipo_date,
#         field,
#         trading_days,
#         root_path):
# def resume_download_daily_to_many_files(
#         w,
#         trading_days,
#         ipo_date,
#         root_path,
#         field='total_shares'):
# def resume_download_delist_date(
#         w,
#         wind_codes,
#         root_path,
#         field='delist_date',
#         dtype=np.datetime64):
# def combine_func(x1, x2):
# def resume_download_financial_report_data_daily_latest(
#         w,
#         wind_codes,
#         trading_days,
#         root_path,
#         field='total_shares',
#         date_str=datetime.today().strftime('%Y-%m-%d'),
#         option=""):
# def resume_download_financial_report_quarter(w, wind_codes, root_path, fields=['stm_issuingdate'], dtype=np.datetime64):
# 
# Path: kquant_data/config.py
# __CONFIG_H5_STK_FACTOR_DIR__ = os.path.join(__CONFIG_H5_STK_DIR__, 'factor')
# 
# __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK'


import os
import pandas as pd
from WindPy import w
from kquant_data.xio.csv import write_data_dataframe, read_data_dataframe
from kquant_data.api import all_instruments
from kquant_data.wind_resume.wsd import download_daily_at
from kquant_data.config import __CONFIG_H5_STK_FACTOR_DIR__, __CONFIG_H5_STK_DIR__
# -*- coding: utf-8 -*-
"""
下载财报一类的信息
"""


if __name__ == '__main__':
    w.start()

    path = os.path.join(__CONFIG_H5_STK_DIR__, '1day', 'Symbol.csv')
    Symbols = all_instruments(path)
    wind_codes = list(Symbols['wind_code'])

    # 下载多天数据,以另一数据做为标准来下载
    # 比如交易数据是10月8号，那就得取10月7号，然后再平移到8号，如果7号没有数据那就得9月30号
    path = os.path.join(__CONFIG_H5_STK_FACTOR_DIR__, 'roe.csv')
    date_index = read_data_dataframe(path)

    field = 'pb_lf'
    df = None
    for i in range(len(date_index)):
        print(date_index.index[i])

        date_str = date_index.index[i].strftime('%Y-%m-%d')
        df_new = download_daily_at(w, wind_codes, field, date_str, "Days=Alldays")
        if df is None:
            df = df_new
        else:
            df = pd.concat([df, df_new])


# Path: kquant_data/xio/csv.py
# def write_data_dataframe(path, df, date_format='%Y-%m-%d'):
#     """
#     写入数据
#     :param path:
#     :param df:
#     :return:
#     """
#     df.to_csv(path, date_format=date_format, encoding='utf-8-sig')
# 
# def read_data_dataframe(path, sep=','):
#     """
#     读取季报的公告日
#     注意：有些股票多个季度一起发，一般是公司出问题了，特别是600878，四个报告同一天发布
#     年报与一季报很有可能一起发
#     :param path:
#     :param sep:
#     :return:
#     """
#     try:
#         df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep)
#     except (FileNotFoundError, OSError):
#         return None
# 
#     return df
# 
# Path: kquant_data/api.py
# def all_instruments(path=None, type=None):
#     """
#     得到合约列表
#     :param type:
#     :return:
#     """
#     if path is None:
#         path = os.path.join(__CONFIG_H5_STK_DIR__, "daily", 'Symbol.csv')
# 
#     df = pd.read_csv(path, dtype={'code': str})
# 
#     return df
# 
# Path: kquant_data/wind_resume/wsd.py
# def resume_download_daily_many_to_one_file(
#         w,
#         wind_codes,
#         field,
#         dtype,
#         enddate,
#         root_path,
#         option='unit=1;rptType=1;Period=Q;Days=Alldays',
#         default_start_date='2000-01-01'):
# def resume_download_daily_one_to_one_file(
#         w,
#         symbol,
#         ipo_date,
#         field,
#         trading_days,
#         root_path):
# def resume_download_daily_to_many_files(
#         w,
#         trading_days,
#         ipo_date,
#         root_path,
#         field='total_shares'):
# def resume_download_delist_date(
#         w,
#         wind_codes,
#         root_path,
#         field='delist_date',
#         dtype=np.datetime64):
# def combine_func(x1, x2):
# def resume_download_financial_report_data_daily_latest(
#         w,
#         wind_codes,
#         trading_days,
#         root_path,
#         field='total_shares',
#         date_str=datetime.today().strftime('%Y-%m-%d'),
#         option=""):
# def resume_download_financial_report_quarter(w, wind_codes, root_path, fields=['stm_issuingdate'], dtype=np.datetime64):
# 
# Path: kquant_data/config.py
# __CONFIG_H5_STK_FACTOR_DIR__ = os.path.join(__CONFIG_H5_STK_DIR__, 'factor')
# 
# __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK'


# Path: demo_stock/A_1day/D04_download_pb_lf.py
import os
import pandas as pd
from WindPy import w
from kquant_data.xio.csv import write_data_dataframe, read_data_dataframe
from kquant_data.api import all_instruments
from kquant_data.wind_resume.wsd import download_daily_at
from kquant_data.config import __CONFIG_H5_STK_FACTOR_DIR__, __CONFIG_H5_STK_DIR__

# -*- coding: utf-8 -*-
"""
下载财报一类的信息
"""


if __name__ == '__main__':
    w.start()

    path = os.path.join(__CONFIG_H5_STK_DIR__, '1day', 'Symbol.csv')
    Symbols = all_instruments(path)
    wind_codes = list(Symbols['wind_code'])

    # 下载多天数据,以另一数据做为标准来下载
    # 比如交易数据是10月8号，那就得取10月7号，然后再平移到8号，如果7号没有数据那就得9月30号
    path = os.path.join(__CONFIG_H5_STK_FACTOR_DIR__, 'roe.csv')
    date_index = read_data_dataframe(path)

    field = 'pb_lf'
    df = None
    for i in range(len(date_index)):
        print(date_index.index[i])

        date_str = date_index.index[i].strftime('%Y-%m-%d')
        df_new = download_daily_at(w, wind_codes, field, date_str, "Days=Alldays")
        if df is None:
            df = df_new
        else:
            df = pd.concat([df, df_new])


    path = os.path.join(__CONFIG_H5_STK_FACTOR_DIR__, '%s.csv' % field)