示例#1
0
def orig_long_trend_bt(df,
                       b_df,
                       st_date,
                       ed_date,
                       sigs=(20, 50, 150),
                       transaction_cost=0,
                       plot=False,
                       index_name=None):

    fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(10, 3.5), dpi=800)

    ax0s = []

    b_df = b_df[st_date:ed_date]
    ret_b = b_df.pct_change().fillna(0)

    port_ret = ret_b.rename('short').to_frame()

    port_ret['long'] = bt_tools.trend_trading(
        df, st_date, ed_date, sigs=sigs, transaction_cost=transaction_cost)

    port_ret = port_ret.fillna(0)

    ew_eq_curve = (port_ret + 1).cumprod()

    # print(port_ret['long'])

    ## Long/ Short Side Plot

    ax0s.append(ew_eq_curve['long'].plot(lw=0.75, ax=ax0, c='b'))
    ax0s.append(ew_eq_curve['short'].plot(lw=0.75, ax=ax0, c='r'))
    # plt.title(f"Long Short {index_name} Portfolio")

    ## combined PnL
    combined_PnL = (port_ret['long'] - port_ret['short'] + 1).cumprod()
    ax0s.append(combined_PnL.plot(lw=0.75, ax=ax1, c='g'))

    if plot:
        custom_lines = [
            Line2D([0], [0], color='b', lw=0.75),
            Line2D([0], [0], color='r', lw=0.75),
            Line2D([0], [0], color='g', lw=0.75)
        ]

        fig.legend(custom_lines, ['long', 'short', 'combined'],
                   ncol=len(custom_lines),
                   loc="upper center")
        plt.setp(ax0s, ylabel='Cumulative Return')

        plt.savefig(f"other_indices/{index_name}/pnls.png",
                    bbox_inches='tight')  #
    plt.close()

    return ew_eq_curve['long'], ew_eq_curve['short']
def coherent_evolve(transaction_cost=0):
    bt_st_date = "2020-09-13"

    bt_date_range = [
        "-".join([
            str(pd.to_datetime(bt_st_date).year - i),
            str(pd.to_datetime(bt_st_date).month),
            str(pd.to_datetime(bt_st_date).day)
        ]) for i in range(0, 21, 5)
    ]

    fig, axs = plt.subplots(4, 2, figsize=(10, 14), dpi=800)
    cmaps = sns.diverging_palette(220, 20, center="dark", n=2)

    ax0s = []

    labels = []

    perfs = pd.DataFrame(columns=pd.MultiIndex.from_product(
        [['2020', '2015', '2010', '2005'], [(20, 50, 150), (30, 60, 160)]],
        names=['end_year', 'trading_rules']))

    for i, end_date in enumerate(bt_date_range[:-1]):

        st_date = bt_date_range[i + 1]
        start_bt_date_1yr_plus = "-".join([
            str(pd.to_datetime(st_date).year - 1),
            str(pd.to_datetime(st_date).month),
            str(pd.to_datetime(st_date).day)
        ])

        df, b_df = get_df_stoxx600(start_bt_date_1yr_plus, end_date)

        b_df = b_df[st_date:end_date]
        ret_b = b_df.pct_change().fillna(0)

        port_ret = ret_b.rename('short').to_frame()

        ## index

        ew_eq_curve = (1 + ret_b).cumprod().rename('short').to_frame()

        ax0s.append(ew_eq_curve['short'].plot(ax=axs[i, 0],
                                              lw=0.75,
                                              c='g',
                                              label='index'))

        for s, sigs in enumerate([(20, 50, 150), (30, 60, 160)]):

            port_ret['long'] = trend_trading(df,
                                             st_date,
                                             end_date,
                                             sigs=sigs,
                                             transaction_cost=0)

            port_ret = port_ret.fillna(0)

            ew_eq_curve = (port_ret + 1).cumprod()

            ax0s.append(ew_eq_curve['long'].plot(ax=axs[i, 0],
                                                 lw=0.75,
                                                 c=cmaps[s]))

            ## combined PnL

            combined_PnL = (port_ret['long'] - port_ret['short'] + 1).cumprod()
            combined_PnL.plot(ax=axs[i, 1], c=cmaps[s])

            perfs[(end_date[:4], sigs)] = port_stats(ew_eq_curve['long'],
                                                     ew_eq_curve['short'])

            # print(port_ret['long'])

            # print(port_stats(ew_eq_curve['long'], ew_eq_curve['short']))

    custom_lines = [
        Line2D([0], [0], color=cmaps[0], lw=0.75),
        Line2D([0], [0], color=cmaps[1], lw=0.75),
        Line2D([0], [0], color='g', lw=0.75)
    ]

    fig.legend(custom_lines,
               ['long (20,50,150)', 'long (30,60,160)', 'short index'],
               ncol=len(custom_lines),
               loc="upper center")
    plt.setp(ax0s, ylabel='Cumulative Return')
    # plt.show()
    plt.savefig(f"stress_trend_follow/coherent_evolve.png",
                bbox_inches='tight')  #
    plt.close()
    # perfs = perfs.T

    with pd.option_context('display.max_rows', None, 'display.max_columns',
                           None):

        print(perfs.T.to_latex())

        r1 = perfs.iloc[:,
                        perfs.columns.get_level_values(1) == (
                            30, 60, 160)].droplevel('trading_rules', axis=1)
        r2 = perfs.iloc[:,
                        perfs.columns.get_level_values(1) == (
                            20, 50, 150)].droplevel('trading_rules', axis=1)

        print((r1 - r2).sort_index(axis=1).to_latex())
示例#3
0
plt.close()


sigs=(20,50,150)
transaction_cost=0

# fig, (ax0,ax1) = plt.subplots(2, 1, figsize=(5, 3.5), dpi=800)
fig, ax1 = plt.subplots(1, 1, figsize=(5, 3.5), dpi=800)


b_df = b_df[st_date:ed_date]
ret_b = b_df.pct_change().fillna(0)

port_ret = ret_b.rename('sp500').to_frame()

port_ret['trend_cap_w'] = bt_tools.trend_trading(df,st_date, ed_date, sigs=sigs, transaction_cost=transaction_cost,w=w, signal_type='all')
port_ret['trend_ew'] = bt_tools.trend_trading(df,st_date, ed_date, sigs=sigs, transaction_cost=transaction_cost,w=None, signal_type='all')

# port_ret['mom'] = bt_tools.momentum_trading(df,st_date, ed_date)


port_ret = port_ret.fillna(0)

port_ret['sp500_cap_w'] = df.pct_change().mul(w).sum(axis=1)


port_ret['sp500_ew'] = df.pct_change().mean(axis=1)


ew_eq_curve = (port_ret + 1).cumprod()
import bt_tools
import pandas as pd

ed_date = '2020-09-13'
st_date = '2015-09-13'
start_bt_date_1yr_plus = '2012-09-13'

df = pd.DataFrame(
    {
        'A': [100, 101, 105, 106, 108],
        'B': [101, 102, 106, 107, 105]
    },
    index=range(0, 5))
df.index.name = 'Date'
binary_signal = pd.DataFrame({
    'A': [0, 1, 0, 1, 1],
    'B': [0, 0, 0, 1, 1]
},
                             index=df.index)
ret = bt_tools.trend_trading(df, None, None, binary_signal=binary_signal)

print(ret)
def long_short_trend(transaction_cost=0.0000, plot=False):
    start_bt_date_1yr_plus = '2014-09-13'
    start_bt_date = '2015-09-13'
    end_bt_date = '2020-09-13'
    df, stoxx600 = get_df_stoxx600(
        start_bt_date_1yr_plus=start_bt_date_1yr_plus, end_bt_date=end_bt_date)
    # df, stoxx600 = get_df_sp500(start_bt_date_1yr_plus=start_bt_date_1yr_plus, end_bt_date=end_bt_date)

    ## short index

    port_ret = stoxx600.loc[start_bt_date:end_bt_date].pct_change().rename(
        'short_index').to_frame()

    ## sides return
    port_ret['long'] = trend_trading(df,
                                     start_bt_date,
                                     end_bt_date,
                                     sigs=(20, 50, 150),
                                     transaction_cost=0)
    port_ret['short_trend'] = trend_trading(df,
                                            start_bt_date,
                                            end_bt_date,
                                            sigs=(20, 50, 150),
                                            transaction_cost=0,
                                            direction='short')
    port_ret = port_ret.fillna(0)

    ## short trend side

    plt.rcParams["figure.dpi"] = 800

    with pd.option_context('display.max_rows', None, 'display.max_columns',
                           None):
        print(port_ret['short_trend'].sort_values(ascending=False))
    (-port_ret['short_trend'].fillna(0) + 1).cumprod().plot(
        figsize=(5, 3.5), legend=True, lw=0.75, fontsize=10).legend(loc=2)
    plt.ylabel('Cumulative Return')
    plt.savefig("short_trend_follow/short_side_pnl.png")
    plt.close()

    ## ew_eq_curves
    eq_eq_curves = (port_ret + 1).cumprod()

    plt.rcParams["figure.dpi"] = 800

    eq_eq_curves.plot(figsize=(5, 3.5), legend=True, lw=0.75,
                      fontsize=10).legend(loc=2)
    plt.ylabel('Cumulative Return')
    plt.savefig("short_trend_follow/pnls")
    plt.close()

    ## combined Pnl

    plt.rcParams["figure.dpi"] = 800
    combined_PnL = (
        port_ret['long'] -
        port_ret['short_trend']).rename('long_short_trend').to_frame()
    combined_PnL['benchmark'] = (port_ret['long'] - port_ret['short_index'])
    combined_PnL = (combined_PnL.fillna(0) + 1).cumprod()
    combined_PnL.plot(figsize=(5, 3.5), legend=True, lw=0.75,
                      fontsize=10).legend(loc=2)
    plt.ylabel('Cumulative Return')
    plt.savefig("short_trend_follow/combined_pnl")
    plt.close()

    # eq_eq_curves['long'] = (port_ret['long'] +1).cumprod()
    # eq_eq_curves['short'] = (port_ret['short'] +1).cumprod()
    ## performance_analysis

    performance_analysis(eq_eq_curves['long'], eq_eq_curves['short_trend'])

    ## portfolio analysis

    return pd.DataFrame({
        'benchmark':
        port_stats(eq_eq_curves['long'], eq_eq_curves['short_index']),
        'long_short_trend':
        port_stats(eq_eq_curves['long'], eq_eq_curves['short_trend'])
    })