如何为我的背部测试者实施美元追踪止损?

时间:2019-12-15 01:46:16

标签: python-3.x quantitative-finance algorithmic-trading trading back-testing

现在,我的测试者测试了一个策略买入,仅以0.025%的获利和0.048%的止损。我试图实现它,只有在超过27美元之后才能激活止盈。努力为此构建代码,非常感谢,请参阅下面的代码

BTC_TICKER = 'BTC'

END_DATE = dt.datetime(2019, 11, 1, 0, 0, 0)
START_DATE = dt.datetime(2018, 1, 1, 0, 0, 0)

# get ohlc
OHLC_BTC = get_ohlc_cryptocompare(BTC_TICKER, USD_TICKER, START_DATE,
                                  end_date=END_DATE, interval_key='hour')
OHLC_BTC = hlp.correct_ohlc_df(OHLC_BTC, frequency=TIMEFRAME)

# create dfs in format that Strategy requires
closes_df = pd.concat([OHLC_BTC['Close']],
                      axis=1, keys=[BTC_TICKER])

# use imported indicator to create weights
macd_df = technicals.macd(OHLC_BTC[['Close']])
weights_df = closes_df.copy()


`TAKE_PROFIT = 0.025
STOP_LOSS = -0.048
pnl = 0
pnl_dollars = 0

i = 0
for index, row in macd_df.iterrows():
    if i < 3:
        weights_df.at[index, BTC_TICKER] = 0

    # no positions cases
    elif weights_df.values[i-1] == 0:
        if (macd_df['MACDdiff_6_23'].values[i-2] < 0
                and macd_df['MACDdiff_6_23'].values[i-1] > 0):
            weights_df.at[index, BTC_TICKER] = 1
        else:
            weights_df.at[index, BTC_TICKER] = 0

    # exit from a position cases
    elif weights_df.values[i-1] == 1:
        if pnl <= STOP_LOSS:
            weights_df.at[index, BTC_TICKER] = 0
        elif pnl >= TAKE_PROFIT:
            weights_df.at[index, BTC_TICKER] = 0
        else:
            weights_df.at[index, BTC_TICKER] = 1

    # update pnl
    if weights_df.values[i] == 0:
        pnl = 0
    else:
        pnl += (OHLC_BTC['Close'].values[i] -
                OHLC_BTC['Close'].values[i-1])/OHLC_BTC['Close'].values[i-1]

    i += 1


# create strategy
s = Strategy(closes_df, weights_df, cash=100)

# run backtest, robust tests, calculate stats
s.run_all(delay=2, verify_data_integrity=True, instruments_drop=None,
          commissions_const=0, capitalization=False)

1 个答案:

答案 0 :(得分:0)

我们需要检查TAKE_PROFIT *当前的BTC价格是否至少为$ 27。让我知道这是否是您想要的。

# exit from a position cases
elif weights_df.values[i-1] == 1:
    if pnl <= STOP_LOSS:
        weights_df.at[index, BTC_TICKER] = 0
    elif TAKE_PROFIT * OHLC_BTC['Close'].values[i-1] > 27:            
        weights_df.at[index, BTC_TICKER] = 0            
    else:

        weights_df.at[index, BTC_TICKER] = 1