如何在Pine Script中通过Bars数量而非起止日期设置回测周期?
Absolutely! You can definitely set your backtesting period using a bar count relative to the latest bar in Pine Script, just like WallStreet.io does. This approach gives you flexibility to use custom year-to-bar mappings (like your 260 bars = 1 year, 320 bars = 2 years rules) instead of rigid date ranges.
Here's a step-by-step implementation with code:
Step 1: Define Input and Custom Bar Mappings
First, add an input for the number of years you want to backtest, then map those years to your desired bar counts:
// Input: Number of years to backtest (adjust minval/maxval as needed) input_years = input.int(title="Backtest Period (Years)", defval=1, minval=1, maxval=5) // Custom year-to-bar-count mapping per your rules var int total_bars = 0 if input_years == 1 total_bars := 260 elif input_years == 2 total_bars := 320 elif input_years == 3 total_bars := 380 // Add more cases for additional years else total_bars := 260 * input_years // Fallback linear calculation if needed
Step 2: Calculate the Backtest Start Point
Next, compute the starting bar index relative to the latest bar on the chart:
// Calculate the first bar index of the backtest period start_bar_index = bar_index - total_bars // Ensure we don't go beyond the first available bar on the chart in_backtest_period = bar_index >= start_bar_index and start_bar_index >= 0
Step 3: Apply the Period to Your Strategy/Indicator
Use the in_backtest_period condition to restrict your strategy's trades or indicator calculations to only the desired period:
Example Strategy Implementation
strategy("Bar-Count Backtest Strategy", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000) // Only execute trades within the backtest period if in_backtest_period // Simple moving average crossover strategy fast_ma = ta.sma(close, 50) slow_ma = ta.sma(close, 200) if ta.crossover(fast_ma, slow_ma) strategy.entry("Long", strategy.long) if ta.crossunder(fast_ma, slow_ma) strategy.close("Long") // Visualize the backtest period with a background color bgcolor(in_backtest_period ? color.new(color.blue, 90) : na, title="Backtest Period")
Key Notes
- Custom Bar Counts: Adjust the values in the year-to-bar mapping to match your exact requirements (e.g., add more
elifcases for 4+ years). - Timeframe Considerations: Remember that bar counts are timeframe-dependent. Your 260-bar rule works for daily charts (~1 trading year), but you'll need to adjust counts for hourly/weekly charts if needed.
- Edge Cases: The
start_bar_index >= 0check ensures your backtest doesn't try to access bars that don't exist on the chart (e.g., if you select 3 years but the chart only has 2 years of data).
This setup lets users select a backtest period by inputting years, which translates to your custom bar count—exactly like the WallStreet.io functionality you referenced.
内容的提问来源于stack exchange,提问作者Vince Kasprzak

