Stock Swing Trading Strategy Evaluator

Stock Data & Simulation Setup

Ensure data is sequential (oldest first). Date can be any text or YYYY-MM-DD. Open, High, Low, Close are required. Volume is optional but good for context if your strategy uses it (this basic version doesn't actively use volume in its logic). Minimum Long MA Period data points required.

Strategy Parameters (SMA Entry, ATR Exits - Long Only)

Buy when Close crosses above this SMA.

Stop-Loss = Entry Price - (Multiplier * ATR)

Take-Profit = Entry Price + (Multiplier * ATR)

Backtest Results for Your Stock

Trade Log (Last 50 Trades):

Trade log will appear here after running the backtest...

Important Notes & Limitations:
  • This tool backtests your defined swing trading strategy (SMA entry, ATR-based exits) using the historical data you provided.
  • Entry Signal: Buys when the closing price crosses above the specified Simple Moving Average (SMA). Sells (exits position) based on ATR stop-loss or take-profit. This is a long-only strategy.
  • Buy & Hold Benchmark: Buys the stock at the start of the usable data period (after initial MA/ATR calculation) and holds until the end.
  • Past Performance is Not Future Guarantee: Historical results do not predict future outcomes.
  • No Slippage: Assumes trades execute exactly at the calculated entry, stop-loss, or take-profit prices. Real-world slippage can impact results.
  • No Taxes: Capital gains taxes are not considered.
  • Data Quality: The accuracy of the backtest depends entirely on the quality and consistency of the historical data entered.
  • Optimization Bias: Repeatedly testing different parameters on the same historical data can lead to over-optimized strategies that may not perform well in the future.
This tool is for educational and illustrative purposes only and does not constitute financial advice.

Stock Name/Ticker: ${inputs.stockName}

Data Points Used: ${inputs.dataPointsCount}

Data Points Per Year: ${inputs.periodsPerYear}

Initial Capital: ${sts_formatCurrency(inputs.initialCapital)}

Transaction Cost: ${inputs.txCostType === 'percent' ? sts_formatPercentage(inputs.txCostValue) : sts_formatCurrency(inputs.txCostValue)} per trade

MA Period (Entry): ${inputs.maPeriod}

ATR Period (Exits): ${inputs.atrPeriod}

Stop-Loss ATR Multiplier: ${inputs.stopLossAtrMult}

Take-Profit ATR Multiplier: ${inputs.takeProfitAtrMult}

`; const resultsTableHtml = ` MetricStrategyBuy & Hold Initial Capital${sts_formatCurrency(results.initialCapital)}${sts_formatCurrency(results.initialCapital)} Final Portfolio Value${sts_formatCurrency(results.strategyFinalValue)}${sts_formatCurrency(results.buyHoldFinalValue)} Total Return${sts_formatPercentage(results.strategyTotalReturn)}${sts_formatPercentage(results.buyHoldTotalReturn)} Annualized Return (CAGR)${results.strategyCAGR !== null ? sts_formatPercentage(results.strategyCAGR) : 'N/A'}${results.buyHoldCAGR !== null ? sts_formatPercentage(results.buyHoldCAGR) : 'N/A'} Strategy Trade Statistics Total Trades${results.totalTrades}N/A Win Rate${sts_formatPercentage(results.winRate)}N/A Avg Gain (Winning Trade)${sts_formatCurrency(results.avgGain)}N/A Avg Loss (Losing Trade)${sts_formatCurrency(results.avgLoss)}N/A Profit Factor${isFinite(results.profitFactor) ? sts_formatNumber(results.profitFactor,2) : "Inf"}N/A `; let logHtml = `
Trade Log (Last 20 Trades for Brevity)
`; if(tradeLog.length > 0) { logHtml += `
`; tradeLog.slice(-20).forEach(log => { // Last 20 for PDF logHtml += `

${log.date}: ${log.type} ${log.shares.toFixed(4)} @ ${sts_formatCurrency(log.price)}. ${log.reason}. ${log.type.includes("SELL") ? `P/L: ${sts_formatCurrency(log.pnl)}.` : ''} Cap: ${sts_formatCurrency(log.capital)}

`; }); logHtml += `
`; } else { logHtml += `

No trades were executed.

`; } const interpretationNote_pdf = `Backtest results are historical and not indicative of future performance. This simulation does not account for slippage, taxes, or other market frictions beyond specified transaction costs.`; pdfContentEl.innerHTML = `
Stock Swing Trading Strategy Evaluation: ${inputs.stockName}
Input Parameters
${inputsHtml}
Performance Summary
${resultsTableHtml}
${logHtml}
Important Notes: ${interpretationNote_pdf}
`; document.body.appendChild(pdfContentEl); html2canvas(pdfContentEl, { scale: 2, useCORS: true, logging:true, windowWidth: pdfContentEl.scrollWidth, windowHeight: pdfContentEl.scrollHeight }).then(canvas => { const imgData = canvas.toDataURL('image/png'); const pdfWidth = pdf.internal.pageSize.getWidth(); const pdfHeight = pdf.internal.pageSize.getHeight(); let numPages = Math.ceil(canvas.height / ( (pdfHeight - 40) * (canvas.width / (pdfWidth - 40)) ) ); // Estimate pages let pageCanvasHeight = (pdfHeight - 40) * (canvas.width / (pdfWidth - 40)); // Canvas pixels per PDF page height for (let i = 0; i < numPages; i++) { if (i > 0) pdf.addPage(); let sourceY = i * pageCanvasHeight; let sourceHeight = Math.min(pageCanvasHeight, canvas.height - sourceY); const tempCanvas = document.createElement('canvas'); tempCanvas.width = canvas.width; tempCanvas.height = sourceHeight; const ctx = tempCanvas.getContext('2d'); ctx.drawImage(canvas, 0, sourceY, canvas.width, sourceHeight, 0, 0, canvas.width, sourceHeight); const pageImgData = tempCanvas.toDataURL('image/png'); const pageImgHeight = (sourceHeight * (pdfWidth - 40)) / canvas.width; pdf.addImage(pageImgData, 'PNG', 20, 20, pdfWidth - 40, pageImgHeight, undefined, 'FAST'); } pdf.save(`${inputs.stockName.replace(/[^a-z0-9]/gi, '_') || 'Swing_Trade'}_Backtest.pdf`); if(document.body.contains(pdfContentEl)) document.body.removeChild(pdfContentEl); }).catch(err => { console.error("STS PDF Error:", err); alert("Error generating Backtest PDF. See console."); if(document.body.contains(pdfContentEl)) document.body.removeChild(pdfContentEl); }); } document.addEventListener('DOMContentLoaded', function() { sts_openTab({}, 'sts_tab_data'); const dataInputEl = document.getElementById('sts_ohlcvData'); if (dataInputEl && !dataInputEl.value) { // Example data for testing // dataInputEl.value = "2023-01-01,100,102,99,101,1000\n2023-01-02,101,103,100,102,1200\n2023-01-03,102,104,101,103,1100\n2023-01-04,103,105,102,104,1300\n2023-01-05,104,106,103,105,1000"; } if (!document.getElementById('sts_ohlcvData')) { console.error("Critical input 'sts_ohlcvData' not found."); } });
Scroll to Top