from pathlib import Path

from A_Global import path_stock, args, path_index
import pandas as pd
from pandas import DataFrame
from metric_tool import IRR, SR, MDD, IRR_adj_day, IRR_acc_day, gen_metrics

def index_of_market(market):
    market = market.lower()
    path_base = path_index
    if market == 'nasdaq':
        return path_base / 'IXIC.GI' # 纳斯达克综合指数
    elif market == 'nyse':
        return path_base / 'SPX.GI' # 道琼斯综合平均指数
    elif market == 'hkex':
        return path_base / 'HSI.HI' # 恒生指数

def add_column_label(path):
    df = pd.read_csv(path, index_col=0)
    if 'label' not in df:
        print('label not in df, add ..')
        df['label'] = round(df.shift(-1)['OPEN'] / df['OPEN'], 3)
        df.to_csv(path)
    else:
        print('label in df')
    return df

def financials_std(path, start_date='2018-06-01', end_date='2019-05-31'):
    principal = 100000
    df = pd.read_csv(path,index_col=0)
    df = df.loc[start_date: end_date, 'label']
    financials = [principal]
    for i in df.values:
        financials.append(financials[-1] + round(principal * (i-1), 2))
        # financials.append(financials[-1] * i)
    print(financials[-1])
    return financials, list(df.index)

def gen_baseline_irrs_res(market, start_date=args['test_start'], end_date=args['test_end']):
    path_index = index_of_market(market)

    add_column_label(path_index)
    result_name = 'Base_Line'

    financials, date_index = financials_std(path_index, start_date=start_date, end_date=end_date)
    metrics = gen_metrics(financials)

    df_irrs     = pd.DataFrame(metrics['irr_list'], index=date_index, columns=[result_name])
    df_metrics  = pd.DataFrame([[round(metrics['IRR'], 3),
                                 round(metrics['SR'], 3),
                                 '%.1f%%' % (100 * metrics['MDD'][0])]],
                               index=[result_name], columns=['IRR', 'SR', 'MDD'])

    df_irrs.to_csv(Path('./') / 'z_irrs.csv')
    df_metrics.to_csv(Path('./') / 'z_result.csv')
    print(df_metrics)
