Strategy · Pine Script v5 · On the chart

AQR TSMOM Pro Strategy

by cagriKarakulak

A Pine v5 strategy that applies time-series momentum, taking the sign of past returns over about one, three and twelve months and averaging them into a long or short score.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code167
Settings15inputs
LicenceMIT
Last update7 weeks ago10 Sep 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

167 lines of Pine Script v5 from tsmom_strategy.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

tsmom_strategy.pine
//@version=5
strategy("AQR TSMOM Pro Strategy", 
         shorttitle="AQR TSMOM", 
         overlay=true, 
         initial_capital=10000, 
         default_qty_type=strategy.cash, 
         default_qty_value=10000, 
         commission_type=strategy.commission.percent, 
         commission_value=0.06, 
         slippage=1, 
         pyramiding=20, 
         process_orders_on_close=true)

// =============================================================================
// AQR TSMOM TREND FOLLOWING (SSRN-2993026)
// =============================================================================

// -----------------------------------------------------------------------------
// 1. GİRDİLER (INPUTS)
// -----------------------------------------------------------------------------
grp1 = "1. Market Profile"
market_mode = input.string("Crypto", title="Market Type", 
              options=["Crypto", "Stocks", "Custom"], group=grp1)
custom_1m   = input.int(30, title="Custom 1M Bars", minval=1, group=grp1)
custom_3m   = input.int(90, title="Custom 3M Bars", minval=1, group=grp1)
custom_12m  = input.int(365, title="Custom 12M Bars", minval=1, group=grp1)
signal_lag  = input.int(0, title="Signal Lag (Bars)", minval=0, maxval=10, group=grp1)

grp2 = "2. Return Type & Risk-Free Rate"
rf_mode     = input.string("None", title="Return Mode", 
              options=["None", "Dynamic T-Bill", "Fixed Rate"], group=grp2)
fixed_rf    = input.float(3.0, title="Fixed Annual Rf %", minval=0.0, step=0.25, group=grp2)
tbill_sym   = input.symbol("US03MY", title="T-Bill Symbol", group=grp2)

grp3 = "3. Volatility Sizing"
target_vol  = input.float(0.10, title="Target Annual Vol", minval=0.01, step=0.01, group=grp3)
vol_mode    = input.string("3-Years", title="Vol Horizon", 
              options=["3-Years", "30-Days", "Custom"], group=grp3)
custom_vol  = input.int(365, title="Custom Vol Bars", minval=5, group=grp3)
max_lev     = input.float(3.0, title="Max Leverage Cap", minval=0.5, step=0.5, group=grp3)

grp4 = "4. Safety Management"
use_kill    = input.bool(false, title="Enable Kill-Switch", group=grp4)
kill_dd     = input.float(25.0, title="Kill-Switch DD %", minval=5.0, group=grp4)

grp5 = "5. Display"
show_hud    = input.bool(true, title="Show Dashboard", group=grp5)

// -----------------------------------------------------------------------------
// 2. HESAPLAMA MOTORU (BAR & ZAMAN AYARLARI)
// -----------------------------------------------------------------------------
bars_day = timeframe.isdaily ? 1.0 : timeframe.isminutes ? (1440.0 / timeframe.multiplier) : 1.0
days_yr  = market_mode == "Stocks" ? 252.0 : 365.0
bars_yr  = days_yr * bars_day

var int w_1m  = 30
var int w_3m  = 90
var int w_12m = 365

if market_mode == "Crypto"
    w_1m  := math.max(1, int(math.round(30 * bars_day)))
    w_3m  := math.max(1, int(math.round(90 * bars_day)))
    w_12m := math.max(1, int(math.round(365 * bars_day)))
else if market_mode == "Stocks"
    w_1m  := math.max(1, int(math.round(21 * bars_day)))
    w_3m  := math.max(1, int(math.round(63 * bars_day)))
    w_12m := math.max(1, int(math.round(252 * bars_day)))
else
    w_1m  := math.max(1, int(math.round(custom_1m * bars_day)))
    w_3m  := math.max(1, int(math.round(custom_3m * bars_day)))
    w_12m := math.max(1, int(math.round(custom_12m * bars_day)))

var int w_vol = 365
if vol_mode == "3-Years"
    w_vol := math.max(5, int(math.round(days_yr * 3 * bars_day)))
else if vol_mode == "30-Days"
    w_vol := math.max(5, int(math.round(30 * bars_day)))
else
    w_vol := math.max(5, int(math.round(custom_vol * bars_day)))

// -----------------------------------------------------------------------------
// 3. AŞIRI GETİRİ (EXCESS RETURN) & MOMENTUM
// -----------------------------------------------------------------------------
tbill_val = request.security(tbill_sym, "D", close, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
float rf_yr = 0.0

if rf_mode == "Dynamic T-Bill"
    rf_yr := nz(tbill_val, fixed_rf) / 100.0
else if rf_mode == "Fixed Rate"
    rf_yr := fixed_rf / 100.0
else
    rf_yr := 0.0

rf_1m  = math.pow(1.0 + rf_yr, (w_1m / bars_day) / days_yr) - 1.0
rf_3m  = math.pow(1.0 + rf_yr, (w_3m / bars_day) / days_yr) - 1.0
rf_12m = math.pow(1.0 + rf_yr, (w_12m / bars_day) / days_yr) - 1.0

ret_1m  = ((close - close[w_1m]) / close[w_1m]) - rf_1m
ret_3m  = ((close - close[w_3m]) / close[w_3m]) - rf_3m
ret_12m = ((close - close[w_12m]) / close[w_12m]) - rf_12m

sig_1m  = ret_1m > 0 ? 1.0 : (ret_1m < 0 ? -1.0 : 0.0)
sig_3m  = ret_3m > 0 ? 1.0 : (ret_3m < 0 ? -1.0 : 0.0)
sig_12m = ret_12m > 0 ? 1.0 : (ret_12m < 0 ? -1.0 : 0.0)

raw_sig = (sig_1m + sig_3m + sig_12m) / 3.0
comp_sig = signal_lag > 0 ? raw_sig[signal_lag] : raw_sig

// -----------------------------------------------------------------------------
// 4. VOLATİLİTE HEDEFLEME & BOYUTLANDIRMA
// -----------------------------------------------------------------------------
bar_ret = (close - close[1]) / close[1]
roll_std = ta.stdev(bar_ret, w_vol)
ann_vol = nz(roll_std * math.sqrt(bars_yr), 0.50)
safe_vol = math.max(ann_vol, 0.02)

raw_weight = (target_vol / safe_vol) * comp_sig
weight = math.min(math.abs(raw_weight), max_lev) * math.sign(raw_weight)

// -----------------------------------------------------------------------------
// 5. İŞLEM YÜRÜTME MOTORU (AYLIK REBALANCE)
// -----------------------------------------------------------------------------
is_rebal = ta.change(time("M")) != 0
has_bars = bar_index >= math.min(w_12m, 60)

var float peak_eq = strategy.initial_capital
peak_eq := math.max(peak_eq, strategy.equity)
dd_pct = peak_eq > 0 ? ((peak_eq - strategy.equity) / peak_eq) * 100.0 : 0.0

var bool killed = false
if use_kill and dd_pct >= kill_dd
    killed := true

target_usd = strategy.equity * weight
target_qty = close > 0 ? (target_usd / close) : 0.0
delta_qty  = target_qty - strategy.position_size

if killed
    strategy.close_all(comment="Kill-Switch")
else if has_bars and is_rebal
    if target_qty == 0.0
        strategy.close_all(comment="Flat")
    else if delta_qty > 0 and (delta_qty * close >= 10.0)
        strategy.order("TSMOM", strategy.long, qty=math.abs(delta_qty))
    else if delta_qty < 0 and (math.abs(delta_qty) * close >= 10.0)
        strategy.order("TSMOM", strategy.short, qty=math.abs(delta_qty))

// -----------------------------------------------------------------------------
// 6. DASHBOARD & GÖRSEL
// -----------------------------------------------------------------------------
bgcolor(comp_sig >= 0.66 ? color.new(color.teal, 92) : comp_sig <= -0.66 ? color.new(color.maroon, 92) : na)

var table hud = table.new(position.top_right, 2, 6, bgcolor=color.new(#0b0f19, 10), border_color=color.new(#00f0ff, 50), border_width=1)

if show_hud
    table.cell(hud, 0, 0, "Signal (S_t)", text_color=color.white)
    table.cell(hud, 1, 0, str.tostring(comp_sig, "#.##"), text_color=color.yellow)
    table.cell(hud, 0, 1, "1M/3M/12M", text_color=color.white)
    table.cell(hud, 1, 1, str.format("{0}/{1}/{2}", sig_1m > 0 ? "+1" : "-1", sig_3m > 0 ? "+1" : "-1", sig_12m > 0 ? "+1" : "-1"), text_color=color.white)
    table.cell(hud, 0, 2, "Realized Vol", text_color=color.white)
    table.cell(hud, 1, 2, str.tostring(ann_vol * 100.0, "#.#") + "%", text_color=color.white)
    table.cell(hud, 0, 3, "Leverage", text_color=color.white)
    table.cell(hud, 1, 3, str.tostring(weight, "#.##") + "x", text_color=color.aqua)
    table.cell(hud, 0, 4, "Current DD", text_color=color.white)
    table.cell(hud, 1, 4, str.tostring(dd_pct, "#.#") + "%", text_color=dd_pct > 15 ? color.red : color.white)
    table.cell(hud, 0, 5, "Kill-Switch", text_color=color.white)
    table.cell(hud, 1, 5, killed ? "HALTED" : (use_kill ? "ON" : "OFF"), text_color=killed ? color.red : color.gray)

Overview

Position size is scaled to a target annual volatility with a maximum leverage cap, with crypto, stocks or custom lookbacks and an optional cash-return adjustment mode. An optional kill-switch uses a drawdown percentage. There is no price stop loss, it allows up to twenty entries in one direction, and a dashboard is shown.

Details

Published by

cagriKarakulak on GitHub

Draws

On the price chart

Markets

Crypto, Stocks

Timeframes

H4 and above

Risk Notes

  • The strategy can add several entries in the same direction
  • The strategy enters trades without a stop loss

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Market TypestringCryptomarket_mode
Custom 1M Barsint30custom_1m
Custom 3M Barsint90custom_3m
Custom 12M Barsint365custom_12m
Signal Lag (Bars)int0signal_lag
Return ModestringNonerf_mode
Fixed Annual Rf %float3.0fixed_rf
T-Bill SymbolsymbolUS03MYtbill_sym
Target Annual Volfloat0.10target_vol
Vol Horizonstring3-Yearsvol_mode
Custom Vol Barsint365custom_vol
Max Leverage Capfloat3.0max_lev
Show all 15 settings
SettingTypeDefaultVariable
Enable Kill-Switchboolfalseuse_kill
Kill-Switch DD %float25.0kill_dd
Show Dashboardbooltrueshow_hud
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

13 stars

This strategy automates the TradingLatino methodology by evaluating Squeeze Momentum combined with the Average Directional Index (ADX). It executes long or short positions based on momentum shifts and directional strength. Risk management options include const

Strategy v5 Oscillators & momentumTrend
Updated 1 year ago · None stated GitHub repository of Ruckard Lupown TradingLatino A002

This long-only trend-following strategy combines Ichimoku Kinko Hyo components with higher timeframe moving average filters. It triggers long entries when price trades above a higher timeframe EMA and a bullish Tenkan-Sen cross above Kijun-Sen occurs under fav

Strategy v5 TrendOscillators & momentum
Updated 1 year ago · MPL-2.0 GitHub repository of Ichimoku Kinko Hyo Momentum Strategy
4 stars

Momentum Rotation (Top 3) ranks ten large-cap US tech stocks by their six-month returns using daily closes. It rebalances monthly and holds the top three performing stocks long only on the price chart. A ranking table shows the current order. Main settings adj

Strategy v6 Oscillators & momentumTrend
Updated 5 months ago · None stated GitHub repository of Momentum Rotation (Top 3)

This strategy calculates trend direction across three user-defined higher timeframes using dual Simple Moving Averages, filtered by On-Balance Volume and Commodity Channel Index conditions alongside fractal pivot swings. Entries trigger when multi-timeframe tr

Strategy v5 TrendMoving averages Repaints
Updated 5 months ago · None stated GitHub repository of Fractals with Pivot Trendlines Strategy

Backtester For Anything

by theupslidedown
2 stars

This strategy serves as a backtesting template for any trading system. It accepts external signals to trigger long or short entries and exits, with optional filters based on EMA and ADX indicators to refine conditions. Time-based restrictions limit trading to

Strategy v5 Screeners & dashboardsTrend Repaints
Updated 3 years ago · None stated GitHub repository of Backtester For Anything

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers