0

现在,我的回测器测试了一个策略,即在 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)

4

1 回答 1

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
于 2019-12-17T23:43:55.560 回答