HerramientasTools & Technology

Backtesting: La Única Manera Honesta de Saber Si tu Estrategia Funciona

Backtesting: The Only Honest Way to Know If Your Strategy Works

Por Mario Maldonado · Lectura: 9 min By Mario Maldonado · Read time: 9 min


Por Qué la Mayoría Evita el Backtesting

El backtesting es el proceso de validar una estrategia de trading aplicándola a datos históricos para medir su rentabilidad real antes de arriesgar capital. Sin backtesting, operas con una hipótesis, no con evidencia. Implica revisar cientos de charts históricos, registrar cada trade en una hoja de cálculo y enfrentar la posibilidad de que tu estrategia — en la que llevas semanas trabajando — simplemente no tiene edge. Eso duele. Entonces la mayoría de los traders lo evita y opera con estrategias que "parecen buenas" basadas en anécdotas recientes.

Resultado: el 85% de los traders pierde dinero dentro de los primeros 2 años. No porque el mercado sea imposible de ganar — sino porque operan sin evidencia de que su approach funciona.

Backtesting Manual vs Automatizado

Hay dos formas de hacer backtesting, y cada una tiene sus ventajas:

Manual: Tú mismo revisas charts históricos, bar a bar, como si estuvieras viendo el mercado en tiempo real. Registras cada señal de entrada, cada salida, cada stop hit. Es lento (30-60 segundos por chart, 100+ trades = varias horas) pero es el más educativo. Cuando terminas el manual backtesting de 100 trades, entiendes tu estrategia mejor de lo que jamás podrías con una hoja de cálculo sola.

Automatizado: Programas las reglas de tu estrategia en una plataforma (TradingView Pine Script, Python con Backtrader, Quantopian-style) y la computadora prueba miles de trades en segundos. Es más rápido pero más propenso a errores de programación y a los sesgos que voy a describir abajo.

Mi recomendación: siempre empieza con manual. Hazlo en 100 trades primero. Después, si quieres escalar la muestra a 1,000+ trades, automatiza con las mismas reglas que ya validaste manualmente.

Tamaño de Muestra Mínimo

  • 100 trades: Mínimo absoluto. Con 100 trades puedes ver patrones, pero la varianza estadística es alta.
  • 200-300 trades: Donde empieza a emerger el edge real. Suficiente para ver la distribución de P&L y los drawdowns.
  • 500+ trades: Confianza estadística robusta. Si tienes edge con 500 trades, es real.
Fórmula: Z-Score de Significancia Estadística
Z = (Win Rate observado − 0.50) ÷ √(0.25 ÷ N)
Ejemplo
Win rate = 58% en 100 trades (N=100)
Z = (0.58 − 0.50) ÷ √(0.25 ÷ 100)
Z = 0.08 ÷ 0.05 = 1.6
Un Z > 1.96 indica 95% de confianza estadística. Con 100 trades al 58%, el edge es sugerido pero no estadísticamente confirmado.
Con 200 trades al mismo 58%: Z = 0.08 ÷ 0.0354 = 2.26 → Edge estadísticamente significativo.

Los 4 Errores Fatales de Backtesting

1. Survivorship Bias

Si backtesteás tu estrategia solo en stocks que todavía existen hoy y que tuvieron grandes movimientos, estás estudiando el 5% ganador del mercado. Los stocks que quebraron, las compañías que fueron deslistadas, los gaps que no continuaron — esos no aparecen en tu muestra. Resultado: tu win rate histórico es inflado.

Solución: trabaja con bases de datos de datos históricos que incluyan todos los stocks, incluso los que ya no existen (Compustat, Sharadar).

2. Look-Ahead Bias

Usar información que no estaba disponible en el momento del trade. Ejemplo: "entré porque el stock estaba en el mínimo del día" — el mínimo del día solo lo sabes al cierre del día, no al momento de la entrada. En backtesting manual, siempre cubres las barras futuras y avanzas solo una barra a la vez.

3. Overfitting (Curve Fitting)

Ajustas los parámetros de tu estrategia hasta que el backtest muestra resultados perfectos en los datos históricos. El problema: los parámetros aprendieron el pasado específico, no el principio subyacente. Cuando el mercado cambia ligeramente, la estrategia colapsa.

Señal de alerta: si tu estrategia tiene 10+ parámetros ajustables y el backtest es perfecto, está overfitted. Las mejores estrategias tienen 2-4 reglas simples.

4. Ignorar Comisiones y Slippage

Un backtest sin costos de transacción realistas es ficción. Para small cap day trading, incluye siempre: comisión ($0.005-0.007/acción), slippage estimado ($0.05-0.15/acción en stocks volátiles), posible spread (bid-ask puede ser $0.05-0.20 en small caps con bajo volumen).

Las Métricas que Realmente Importan

  • Win Rate: % de trades ganadores. En isolation, no dice nada — necesitas combinarlo con avg R.
  • Average R: Ganancia promedio en unidades de riesgo. Win rate del 40% con avg R de 3R es mejor que 70% con avg R de 0.5R.
  • Profit Factor: Total ganancias brutas / Total pérdidas brutas. >1.5 es aceptable, >2.0 es excelente.
  • Max Drawdown: La mayor caída desde un pico hasta el siguiente valle. Si tu estrategia tiene un max drawdown del 40%, ¿puedes sobrevivir psicológicamente a eso?
  • Sharpe Ratio: Retorno / Desviación estándar. >1.0 es bueno, >2.0 es excelente.
Fórmula: Profit Factor
Profit Factor = Suma de todas las ganancias ÷ Suma de todas las pérdidas (en valor absoluto)

Forward Testing: El Paso Obligatorio Después del Backtest

El backtest dice que la estrategia funcionó en el pasado. El forward test dice que funciona ahora, en condiciones de mercado actuales. Protocolo:

  • 30 días de paper trading con las mismas reglas exactas del backtest
  • Registra cada trade en tiempo real (no ex-post)
  • Si el forward test muestra métricas similares al backtest (±20%), la estrategia está validada para trading en vivo
  • Si el forward test es significativamente peor, revisa si el mercado cambió o si hay look-ahead bias no detectado

Why Most Traders Avoid Backtesting

Backtesting is tedious. It means reviewing hundreds of historical charts, logging every trade in a spreadsheet, and facing the possibility that your strategy — the one you've been working on for weeks — simply has no edge. That hurts. So most traders avoid it and trade strategies that "seem good" based on recent anecdotes.

Result: 85% of traders lose money within their first 2 years. Not because the market is unbeatable — but because they trade without evidence that their approach works.

Manual vs Automated Backtesting

There are two ways to backtest, each with advantages:

Manual: You review historical charts yourself, bar by bar, as if watching the market in real time. You log every entry signal, every exit, every stop hit. It's slow (30-60 seconds per chart, 100+ trades = several hours) but the most educational. When you finish manual backtesting of 100 trades, you understand your strategy better than any spreadsheet could teach you.

Automated: You program your strategy rules into a platform (TradingView Pine Script, Python with Backtrader) and the computer tests thousands of trades in seconds. It's faster but more prone to programming errors and the biases I'll describe below.

My recommendation: always start manual. Do it on 100 trades first. Then, if you want to scale to 1,000+ trades, automate using the same rules you already validated manually.

Minimum Sample Size

  • 100 trades: Absolute minimum. You can see patterns, but statistical variance is high.
  • 200-300 trades: Where real edge starts to emerge. Enough to see the P&L distribution and drawdowns.
  • 500+ trades: Robust statistical confidence. If you have edge over 500 trades, it's real.
Formula: Statistical Significance Z-Score
Z = (Observed Win Rate − 0.50) ÷ √(0.25 ÷ N)
Example
Win rate = 58% over 100 trades (N=100)
Z = (0.58 − 0.50) ÷ √(0.25 ÷ 100)
Z = 0.08 ÷ 0.05 = 1.6
Z > 1.96 indicates 95% statistical confidence. At 58% over 100 trades, edge is suggested but not statistically confirmed.
At 200 trades with the same 58%: Z = 0.08 ÷ 0.0354 = 2.26 → Statistically significant edge.

The 4 Fatal Backtesting Errors

1. Survivorship Bias

If you backtest only on stocks that still exist today and had big moves, you're studying the market's top 5% winners. Stocks that went bankrupt, companies that were delisted, gaps that failed to continue — those don't appear in your sample. Result: your historical win rate is inflated.

Solution: work with historical databases that include all stocks, including those that no longer exist (Compustat, Sharadar).

2. Look-Ahead Bias

Using information not available at the time of the trade. Example: "I entered because the stock was at the day's low" — the day's low is only known at market close, not at entry time. In manual backtesting, always cover future bars and advance only one bar at a time.

3. Overfitting (Curve Fitting)

You tune your strategy parameters until the backtest shows perfect results on historical data. The problem: those parameters learned the specific past, not the underlying principle. When market conditions shift slightly, the strategy collapses.

Warning sign: if your strategy has 10+ tunable parameters and the backtest is perfect, it's overfitted. The best strategies have 2-4 simple rules.

4. Ignoring Commissions and Slippage

A backtest without realistic transaction costs is fiction. For small cap day trading, always include: commission ($0.005-0.007/share), estimated slippage ($0.05-0.15/share on volatile stocks), potential spread (bid-ask can be $0.05-0.20 on low-volume small caps).

The Metrics That Actually Matter

  • Win Rate: % of winning trades. In isolation it means nothing — pair it with avg R.
  • Average R: Average gain in units of risk. 40% win rate with 3R avg is better than 70% with 0.5R avg.
  • Profit Factor: Total gross gains / Total gross losses. >1.5 is acceptable, >2.0 is excellent.
  • Max Drawdown: The largest drop from a peak to the next valley. If your strategy has 40% max drawdown, can you psychologically survive that?
  • Sharpe Ratio: Return / Standard deviation. >1.0 is good, >2.0 is excellent.
Formula: Profit Factor
Profit Factor = Sum of all gains ÷ Sum of all losses (absolute value)

Forward Testing: The Mandatory Step After Backtesting

The backtest says the strategy worked in the past. The forward test says it works now, under current market conditions. Protocol:

  • 30 days of paper trading with the exact same rules as the backtest
  • Log every trade in real time (not ex-post)
  • If forward test shows metrics similar to backtest (±20%), the strategy is validated for live trading
  • If forward test is significantly worse, check whether the market changed or if there's undetected look-ahead bias

Lecturas Relacionadas

Related Reading

Paper Trading: Lo Que Sí y No Te Enseña Scanners de Mercado El Verdadero Costo de Tradear
Paper Trading: What Simulation Does and Doesn't Teach Market Scanners The True Cost of Trading