年度数据统计

def seg(data_input, testday):
    data_input['TRADE_DT'] = data_input['TRADE_DT'].astype('int')
    now_loc = data_input[data_input.TRADE_DT < testday].index.tolist()[-1]
    sixty_loc = now_loc - 60
    data_llt = data_input.iloc[(sixty_loc + 1):(now_loc + 1), :]
    data_llt = data_llt.reset_index(drop=True)
    return data_llt
def log_plot():
    plt.plot(
        xs,
        [math.log(x) for x in bt_value.net_value.astype(float)],
        label='net_value',
        linestyle='-',
        linewidth=1.0)
    plt.plot(
        xs,
        [math.log(x) for x in bt_value.benchmark.astype(float)],
        label='benchmark',
        color='y',
        linestyle='-',
        linewidth=1.0)
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m'))
    plt.gca().xaxis.set_major_locator(mdates.DayLocator(1))
    plt.gcf().autofmt_xdate()
    plt.title('策略净值走势(对数)', fontsize=24)
    plt.legend(loc='best')
    plt.grid(True)
    plt.show()
def Calriskfac(bt_value, begin_year, end_year):
    loc1 = bt_value[bt_value.date_bt.astype(
        'int') < begin_year].index.tolist()[-1]
    loc2 = bt_value[bt_value.date_bt.astype(
        'int') <= end_year].index.tolist()[-1]
    temporal_bt_value = bt_value.iloc[loc1:loc2 + 1].reset_index(drop=True)
    benchmark = np.array(temporal_bt_value.benchmark)
    net_value = np.array(temporal_bt_value.net_value)
    num_long = np.array(temporal_bt_value.num_long)
    num_short = np.array(temporal_bt_value.num_short)

    returns_benchmark = (benchmark[-1] - benchmark[0]) / benchmark[0]  # 基准收益
    annualized_returns_benchmark = (
        1 + returns_benchmark)**(250 / (len(benchmark) - 1)) - 1  # 基准年化收益
    returns = (net_value[-1] - net_value[0]) / net_value[0]   # 策略收益
    annualized_returns = (1 + returns)**(250 /
                                         (len(net_value) - 1)) - 1  # 策略年化收益
    # alpha、beta
    dp = [(net_value[i] - net_value[i - 1]) / net_value[i - 1]
          for i in range(1, len(net_value), 1)]
    dm = [(benchmark[i] - benchmark[i - 1]) / benchmark[i - 1]
          for i in range(1, len(benchmark), 1)]
    beta = np.cov(dp, dm)[0, 1] / np.var(dm)
    alpha = annualized_returns - \
        (0.04 + beta * (annualized_returns_benchmark - 0.04))
    # sharpe
    sharp_ratio = (annualized_returns - 0.04) / \
        (np.array(dp).std() * math.sqrt(len(net_value) - 1))
    # 最大回撤
    # net_value = np.array(net_value)
    i = np.argmax(np.maximum.accumulate(net_value) - net_value)
    j = np.argmax(net_value[:i])
    max_drawdown = (net_value[j] - net_value[i]) / net_value[j]
    # net_value = net_value.tolist()
    # trade_dt = trade_dt.tolist()
    # df
    risk_indicator = pd.DataFrame([[returns,
                                    returns_benchmark,
                                    alpha,
                                    beta,
                                    sharp_ratio,
                                    max_drawdown,
                                    num_long[-1] - num_long[0],
                                    num_short[-1] - num_short[0]]],
                                  columns=['策略收益',
                                           '基准收益',
                                           'alpha',
                                           'beta',
                                           '夏普率',
                                           '最大回撤',
                                           '开多次数',
                                           '开空次数'])
    return risk_indicator
risk_indicator = pd.concat(
    [
        Calriskfac(
            bt_value, 20150101, 20151231), Calriskfac(
                bt_value, 20160101, 20161231), Calriskfac(
                    bt_value, 20170101, 20171231), Calriskfac(
                        bt_value, 20180101, 20181231), Calriskfac(
                            bt_value, 20190101, end
        )])
risk_indicator['年份'] = ['2015', '2016', '2017', '2018', '2019']
risk_indicator = risk_indicator.reindex(
    columns=[
        '年份',
        '策略收益',
        '基准收益',
        'alpha',
        'beta',
        '夏普率',
        '最大回撤',
        '开多次数',
        '开空次数',
    '平仓次数']).reset_index(
            drop=True)

添加垂直线

# 
ax.axvline(
    datetime.datetime.strptime(
        '20150101',
        '%Y%m%d').date(),
    linewidth=2,
    linestyle='dashed',
    color='purple')

# 
ax2 = plt.subplot(212)
plt.plot(
    xs,
    [math.log(x) for x in bt_value.net_value.astype(float)],
    label='net_value',
    linestyle='-',
    linewidth=1.0)
plt.plot(
    xs,
    [math.log(x) for x in bt_value.benchmark.astype(float)],
    label='benchmark',
    color='y',
    linestyle='-',
    linewidth=1.0)

你可能感兴趣的:(年度数据统计)