0

Right now my my backtester tests a strategy buy simply taking profits at 0.025% and stop loss at 0.048%. I am trying to implement it activating a take profit above only after $27 has been surpassed. struggling to structure the code on this, help much appreciated, please see code below

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)

Andrewoca
  • 79
  • 6

1 Answers1

0

We need check whether TAKE_PROFIT * current BTC price is at least $27. Let me know if that is what you were looking for.

# 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
Rahul Chowdhury
  • 641
  • 1
  • 7
  • 16