Does a trend filter
improve the trade-off?
A fixed 200-day moving-average filter on SPY. Historical simulation from 2 January 2018 to 31 December 2025, with the same trading costs applied to the benchmark.
Self-initiated portfolio example. Not client work, a live track record, or a strategy recommendation.
Download research bundle ↓Inspect methodologyLess drawdown. Less return.
In this sample, the filter reduced the worst observed drawdown, but ended with less wealth than buy & hold. Its Sharpe ratio was also slightly lower. This is a documented trade-off, not evidence of superiority.
Starting equity: $10,000 USD each. Daily adjusted-close proxy. Historical simulation, not live results.
| Full-period metric | Strategy | Buy & hold |
|---|---|---|
| Ending equity | $20,279 | $28,719 |
| Total return | 102.79% | 187.19% |
| Annualized return (CAGR) | 9.23% | 14.09% |
| Maximum drawdown | -24.21% | -33.72% |
| Sharpe (zero risk-free rate) | 0.77 | 0.78 |
| Market exposure | 80.61% | 99.95% |
| Orders, including final exit | 50 | 2 |
Exactly what was tested.
- Calculate a simple average of the last 200 daily adjusted closes.
- At each close, signal long if the adjusted close is strictly above the average; otherwise signal cash.
- Execute that signal at the following trading day's close. Existing exposure earns that day's return before the new signal is executed.
- Allocate 100% of equity when long, with fractional exposure, no leverage and 0% return on idle cash.
- Charge 5 basis points (0.05%) on traded value for each entry and exit. This is an illustrative combined commission/slippage assumption.
- Begin both simulations in cash. The benchmark buys at the first evaluated close. Liquidate both at the final close, including exit costs.
Data before 2018 is used only for indicator warm-up. No parameter search was performed. The 200-day rule was fixed for this demonstration.
Check more than the headline.
Retrospective chronological comparison
Each subperiod restarts with $10,000 and the same fixed rule and costs. These are historical segments, not an untouched prospective holdout or evidence of live out-of-sample performance.
| Period | Strategy CAGR | Benchmark CAGR | Strategy max DD |
|---|---|---|---|
| 2018–2021 | 12.89% | 17.26% | -15.61% |
| 2022–2025 | 5.51% | 10.81% | -24.25% |
Transaction-cost sensitivity
Only the one-way cost assumption changes. All strategy parameters remain fixed.
| One-way cost | Strategy CAGR | Strategy max DD |
|---|---|---|
| 0 bps | 9.57% | -23.45% |
| 5 bps | 9.23% | -24.21% |
| 10 bps | 8.89% | -24.97% |
| 20 bps | 8.21% | -26.46% |
What this test cannot establish.
- One ETF and one historical window cannot demonstrate robustness across markets or regimes.
- Adjusted closes approximate distributions and corporate actions. They are not executable prices, and the test does not explicitly account for dividend cash flows or withholding taxes.
- Daily closing prices hide intraday drawdowns, bid/ask spreads, liquidity and rejected orders. A fixed cost model cannot capture these effects fully.
- Tax, data fees, financing and operational costs are excluded. Fractional allocation may not be available in every implementation.
- Historical source data may be revised. No independent vendor cross-check was performed.
- The method uses delayed execution but this alone does not rule out every research or implementation error.
Inspect the deliverable.
Read Python source directly on this page ↓
The bundle contains the Python implementation, frozen input data, metrics, daily equity series, order logs and methodology. Python uses only the standard library.
Download complete bundle ↓Python source ↓Order log ↓python backtest.py --data prices.csv --out results
Source: Yahoo Finance / SPY historical data, retrieved 21 October 2026 via its chart endpoint. Input snapshot covers 21 October 2016 through 31 December 2025. USD throughout.
Want this level of clarity on your system?
Start with a Strategy Audit or scope a custom research project.
View packages ↗Python source preview
Open the complete implementation
"""Edgecraft Quant educational demonstration; Python standard library only.
Run: python backtest.py --data prices.csv --out results
Data source: Yahoo Finance chart/SPY daily adjusted closes, retrieved 2026-10-21.
Fixed SMA(200), long/cash, no leverage. Signal at close t executes close t+1.
Adjusted closes are a total-return proxy, not executable fill prices.
Fractional exposure, idle cash earns 0%, 5 bps one-way trading costs.
No parameter fitting. Chronological splits are retrospective, not live OOS proof.
"""
import argparse,csv,json,math,statistics
from pathlib import Path
from datetime import date
def load(path):
with open(path,newline='') as f: rows=list(csv.DictReader(f))
prices=[float(r['adjusted_close']) for r in rows]
dates=[r['date'] for r in rows]
assert dates==sorted(set(dates)), 'Dates must be unique and ordered'
assert all(math.isfinite(p) and p>0 for p in prices)
return dates,prices
def simulate(dates,prices,start,end,bps=5,benchmark=False):
indices=[i for i,d in enumerate(dates) if start<=d<=end and i>=201]
assert indices
equity=10000.;peak=equity;dd=0.;pos=0;daily=[];curve=[];orders=[];exposure=[]
baseline=dates[indices[0]-1]
curve.append({'date':baseline,'equity':equity,'drawdown':0.,'position':0})
for i in indices:
previous=equity
# Existing exposure earns today's close-to-close return. Yesterday's signal
# can only change exposure at today's close; it earns no earlier return.
exposure.append(pos)
equity*=1+pos*(prices[i]/prices[i-1]-1)
target=1 if benchmark else int(prices[i-1]>sum(prices[i-200:i])/200)
# Liquidate on the last close, charging both approaches the same exit cost.
if i==indices[-1]: target=0
if target!=pos:
fee=equity*bps/10000
equity-=fee
orders.append({'date':dates[i],'action':'BUY' if target else 'SELL','cost_usd':fee,'equity_after_cost':equity})
pos=target
daily.append(equity/previous-1)
peak=max(peak,equity);drawdown=equity/peak-1;dd=min(dd,drawdown)
curve.append({'date':dates[i],'equity':equity,'drawdown':drawdown,'position':pos})
years=(date.fromisoformat(dates[indices[-1]])-date.fromisoformat(baseline)).days/365.25
sd=statistics.stdev(daily)
metrics={'start':dates[indices[0]],'baseline':baseline,'end':dates[indices[-1]],'initial':10000,'final':equity,'total_return':equity/10000-1,'cagr':(equity/10000)**(1/years)-1,'max_drawdown':dd,'sharpe_zero_rf':statistics.mean(daily)/sd*math.sqrt(252) if sd else 0,'exposure':statistics.mean(exposure),'orders':len(orders),'round_trips':len(orders)//2,'cost_bps':bps}
return {'metrics':metrics,'curve':curve,'orders':orders}
def run(data,out):
dates,prices=load(data);out=Path(out);out.mkdir(parents=True,exist_ok=True)
result={}
for name,start,end in [('full','2018-01-01','2025-12-31'),('early','2018-01-01','2021-12-31'),('later','2022-01-01','2025-12-31')]:
result[name]={k:simulate(dates,prices,start,end,benchmark=(k=='benchmark')) for k in ['strategy','benchmark']}
result['cost_sensitivity']=[simulate(dates,prices,'2018-01-01','2025-12-31',bps=b)['metrics'] for b in [0,5,10,20]]
(out/'summary.json').write_text(json.dumps(result,indent=2))
for kind in ['strategy','benchmark']:
for field in ['curve','orders']:
rows=result['full'][kind][field]
with (out/f'{kind}_{field}.csv').open('w',newline='') as f:
w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
return result
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--data',default='prices.csv');parser.add_argument('--out',default='results');args=parser.parse_args()
r=run(args.data,args.out)
print(json.dumps({k:r['full'][k]['metrics'] for k in ['strategy','benchmark']},indent=2))