Market sentiment is high when everyone is profit on paper, and vice versa. Can we use this as an indicator to trade?
When there is a long bear market in the time series, the long short strategy will usually benefit in that period. However, in reality a trader cannot predict a bull or bear market from happening, not to mention how long it will last. Moreover, short selling is high risk because the volatility is usually higher in the bear market, especially during the panic selling period.
from btbox import *
from pandas import Series
SYMBOL = 'QQQ'
START = '2001-01-01'
WINDOW = 365
INTERVAL = 5
dfs = {SYMBOL: import_yahoo_csv(f'../../_data_/{SYMBOL}_bar1d.csv')}
class BM_AllInAndForget(Strategy):
def initial(self, b: Broker):
b.portfolio.trade_target_weight(SYMBOL, 1)
class BM_KeepAtHalf(Strategy):
@interval(INTERVAL)
def step(self, b: Broker):
b.portfolio.trade_target_weight(SYMBOL, 0.5)
def pnl_ratio(win: Series) -> float:
pnlr = win.rank(pct=True)
return pnlr[-1]
def ST_LongShortPnL(min, max):
offset = max - min
class ST(Strategy):
name = f'ST_LongShortPnl_range[{min},{max}]'
@interval(INTERVAL)
def step(self, b: Broker):
win = b.market.get_close_window(SYMBOL)
pnlr = pnl_ratio(win)
weight = min + offset * pnlr
b.portfolio.trade_target_weight(SYMBOL, weight)
self.journal.mark(weight, 'weight')
return ST
bt = create_backtest(
[
BM_AllInAndForget,
BM_KeepAtHalf,
ST_LongShortPnL(0, 1),
ST_LongShortPnL(-0.2, 1),
ST_LongShortPnL(-0.2, 1.5),
ST_LongShortPnL(-0.5, 1.5),
],
dfs,
start=START,
window=WINDOW,
)
results = bt.run()
results.dashboard_pretty()
return | cagr | mu | sigma | mdd | duration | sharpe | calmar | |
---|---|---|---|---|---|---|---|---|
BM_AllInAndForget | 522.9% | 8.71% | 11.54% | 25.33% | -70.40% | 624 days 00:00 | 0.456 | 0.164 |
BM_KeepAtHalf | 188.1% | 4.95% | 5.62% | 12.61% | -43.48% | 624 days 00:00 | 0.446 | 0.129 |
ST_LongShortPnl_range[0,1] | 544.0% | 8.87% | 9.53% | 14.38% | -25.57% | 26 days 00:00 | 0.663 | 0.373 |
ST_LongShortPnl_range[-0.2,1] | 507.9% | 8.59% | 9.21% | 13.98% | -24.97% | 26 days 00:00 | 0.659 | 0.369 |
ST_LongShortPnl_range[-0.2,1.5] | 1,242.7% | 12.59% | 14.08% | 21.12% | -36.07% | 26 days 00:00 | 0.667 | 0.390 |
ST_LongShortPnl_range[-0.5,1.5] | 1,102.2% | 12.02% | 13.64% | 21.39% | -35.24% | 26 days 00:00 | 0.638 | 0.387 |
results.plot(log_y=True)
results['ST_LongShortPnl_range[-0.2,1.5]'].journals['weight'].ffill.plot_line_under_price(SYMBOL)