I was working on something with Claude when - during it's checking, rechecking & cross-checking - it discovered this bug. Rather than me trying to write this up in my usual inept way, I asked it to create a full report. Here it is (verbatim, except for some editing changes):
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TL;DR: On Daily-scale strategies, ToWeekly(bars) and TradingDaysRemaining(..., Weekly) disagree for symbols with missing bars, so mapping daily bars to weekly bars with TradingDaysRemaining silently drifts (73 weeks off for FER). Runnable 20-line diagnostic and a date-based workaround below. Not a problem with complete data or with Norgate Padding on.
-------------------------------------
Summary
When a Daily-scale strategy builds weekly series with BarHistoryCompressor.ToWeekly(bars), a common way to map daily bars to weekly bars and detect the week’s last trading day is bars.TradingDaysRemaining(i, Frequency.Weekly) == 0. For symbols with missing daily bars, the weekly bar count from ToWeekly and the number of TradingDaysRemaining == 0 events differ. A mapping built on TradingDaysRemaining then drifts out of alignment with ToWeekly’s bars for the rest of the history. Nothing warns about it, so weekly values are silently read from the wrong weeks.
Environment
WealthLab 9, build 15
Data provider: [any; mine is Norgate, with Padding set to No]
Symbol: FER, Daily scale, 2016-11-18 to 2026-11-18 (sparse history)
What the issue is
Counts measured on FER’s daily data (Norgate, Padding = No; data through 2026-11-18):
Two behaviours appear to be involved (inferred from the counts and dates, not from WL’s source):
1. TradingDaysRemaining seems calendar-based. A week whose final trading day is missing from the symbol’s data never returns 0, so that week is never counted. This is plausibly by design but undocumented.
2. ToWeekly does not group by calendar week on sparse data. Each weekly bar is dated with the last daily bar of its group. It looks as if a new weekly bar starts when the weekday number goes backwards, not when the calendar week changes. For example, FER’s weekly bar dated 12/8/2016 contains daily bars from two different calendar weeks (11/29 and 11/30, plus 12/8).
Because the two follow different rules, a weekly index built by counting TradingDaysRemaining == 0 events ends up 73 weeks behind ToWeekly’s bars on FER, and stays that way even after FER’s data becomes complete. For complete-data symbols all counts agree (the weekly count may differ by one for a partial last week). In a 100-symbol Nasdaq-100 test only FER showed the mismatch.
How to verify
Run this strategy on Daily scale, 2016-11-18 to 2026-11-18, on a sparse symbol (FER on my data) and on a complete one (e.g. AAPL), then read the Debug log:
Output on my FER data: dailyBars=912 toWeekly=266 calendarWeeksWithData=328 TDR==0 count=192 gaps>5d=147.
Output on my AAPL data: dailyBars=2512 toWeekly=522 calendarWeeksWithData=522 TDR==0 count=521 gaps>5d=0.
On a complete-data symbol, toWeekly, calendarWeeksWithData and TDR==0 count should be equal ((toWeekly and calendarWeeksWithData should be equal; TDR==0 count can be one lower when the final calendar week is incomplete)). On FER they are 266, 328 and 192.
Impact
Any daily-bar strategy that builds weekly (or monthly) series internally and maps daily bars to them by counting TradingDaysRemaining == 0 events will silently read weekly indicator values from the wrong weeks for symbols with missing bars (ADRs, thin or recently relisted tickers, providers with gaps). There is no error or warning.
Recommended fixes
1. Make ToWeekly (and monthly) group by calendar period, so bar counts match the calendar even when days are missing. If the current rule is intentional, document it precisely.
2. Provide an official daily-to-weekly mapping, e.g. a ToWeekly overload that also returns the daily-to-compressed index map, or bars.IsLastBarOfPeriod(idx, Frequency.Weekly) based on the symbol’s own data.
3. Document TradingDaysRemaining: whether it uses the market calendar or the symbol’s own bars, and that it returns 0 only when the calendar’s last day exists in the data.
4. Warn in the docs that the pattern “weekly logic on daily bars using TradingDaysRemaining == 0” assumes complete data.
5. Optional: a one-time debug warning when ToWeekly(bars).Count and the number of TradingDaysRemaining == 0 events differ by more than one.
Data provider note
With Norgate’s Padding option set to No, FER’s non-traded days are missing bars, which produces the mismatch above. With Padding enabled (non-traded market days filled with the last Close, data through 2026-11-18), the three counts agree for FER:
FER: dailyBars=2512 toWeekly=522 calendarWeeksWithData=522 TDR==0 count=521 gaps>5d=0
(TDR==0 count is one lower only because the final calendar week is still in progress.)
So the problem only appears when bars are missing. Padding is not a general fix, though: it alters indicator values (ATR, average volume, SMA, etc etc), and in my strategy it changed the trade count (552 to 559).
Workaround (what I use now)
Map by date against the weekly bars’ own dates, which is exact however ToWeekly groups bars, and mark a daily bar as “week complete” only if it is the last daily bar of its weekly bar and TradingDaysRemaining == 0. The block below is self-contained and ends with a printout that confirms the fix:
Expected output:
dateMapCloseMismatches=0 for every symbol. This proves each weekly bar is mapped to the right daily bar.
oldCountDriftAtEnd=0 on complete-data symbols, and a large number on a sparse symbol like FER. That is the old counting method’s drift, which the date-based mapping avoids.
With this mapping, results for complete-data symbols are identical to the old mapping, and FER’s weekly series line up correctly.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TL;DR: On Daily-scale strategies, ToWeekly(bars) and TradingDaysRemaining(..., Weekly) disagree for symbols with missing bars, so mapping daily bars to weekly bars with TradingDaysRemaining silently drifts (73 weeks off for FER). Runnable 20-line diagnostic and a date-based workaround below. Not a problem with complete data or with Norgate Padding on.
-------------------------------------
Summary
When a Daily-scale strategy builds weekly series with BarHistoryCompressor.ToWeekly(bars), a common way to map daily bars to weekly bars and detect the week’s last trading day is bars.TradingDaysRemaining(i, Frequency.Weekly) == 0. For symbols with missing daily bars, the weekly bar count from ToWeekly and the number of TradingDaysRemaining == 0 events differ. A mapping built on TradingDaysRemaining then drifts out of alignment with ToWeekly’s bars for the rest of the history. Nothing warns about it, so weekly values are silently read from the wrong weeks.
Environment
WealthLab 9, build 15
Data provider: [any; mine is Norgate, with Padding set to No]
Symbol: FER, Daily scale, 2016-11-18 to 2026-11-18 (sparse history)
What the issue is
Counts measured on FER’s daily data (Norgate, Padding = No; data through 2026-11-18):
CODE:
Measure Value Daily bars 912 (about 2,500 expected for 10 years) Gaps over 5 days 147 (longest 58 days) Distinct ISO calendar weeks with at least one daily bar 328 ToWeekly(bars).Count 266 Daily bars where TradingDaysRemaining(i, Frequency.Weekly) == 0 192
Two behaviours appear to be involved (inferred from the counts and dates, not from WL’s source):
1. TradingDaysRemaining seems calendar-based. A week whose final trading day is missing from the symbol’s data never returns 0, so that week is never counted. This is plausibly by design but undocumented.
2. ToWeekly does not group by calendar week on sparse data. Each weekly bar is dated with the last daily bar of its group. It looks as if a new weekly bar starts when the weekday number goes backwards, not when the calendar week changes. For example, FER’s weekly bar dated 12/8/2016 contains daily bars from two different calendar weeks (11/29 and 11/30, plus 12/8).
Because the two follow different rules, a weekly index built by counting TradingDaysRemaining == 0 events ends up 73 weeks behind ToWeekly’s bars on FER, and stays that way even after FER’s data becomes complete. For complete-data symbols all counts agree (the weekly count may differ by one for a partial last week). In a 100-symbol Nasdaq-100 test only FER showed the mismatch.
How to verify
Run this strategy on Daily scale, 2016-11-18 to 2026-11-18, on a sparse symbol (FER on my data) and on a complete one (e.g. AAPL), then read the Debug log:
CODE:
using WealthLab.Backtest; using WealthLab.Core; using System; using System.Collections.Generic; using System.Globalization; namespace WealthScript { public class WeeklyMapDiag : UserStrategyBase { public override void Initialize(BarHistory bars) { BarHistory wk = BarHistoryCompressor.ToWeekly(bars); int tdr0 = 0, gaps = 0; var isoWeeks = new HashSet<int>(); for (int i = 0; i < bars.Count; i++) { DateTime d = bars.DateTimes[i]; isoWeeks.Add(ISOWeek.GetYear(d) * 100 + ISOWeek.GetWeekOfYear(d)); if (i > 0 && (d.Date - bars.DateTimes[i - 1].Date).TotalDays > 5) gaps++; if (bars.TradingDaysRemaining(i, Frequency.Weekly) == 0) tdr0++; } WriteToDebugLog($"{bars.Symbol}: dailyBars={bars.Count} toWeekly={wk.Count} " + $"calendarWeeksWithData={isoWeeks.Count} TDR==0 count={tdr0} gaps>5d={gaps}"); } public override void Execute(BarHistory bars, int idx) { } } }
Output on my FER data: dailyBars=912 toWeekly=266 calendarWeeksWithData=328 TDR==0 count=192 gaps>5d=147.
Output on my AAPL data: dailyBars=2512 toWeekly=522 calendarWeeksWithData=522 TDR==0 count=521 gaps>5d=0.
On a complete-data symbol, toWeekly, calendarWeeksWithData and TDR==0 count should be equal ((toWeekly and calendarWeeksWithData should be equal; TDR==0 count can be one lower when the final calendar week is incomplete)). On FER they are 266, 328 and 192.
Impact
Any daily-bar strategy that builds weekly (or monthly) series internally and maps daily bars to them by counting TradingDaysRemaining == 0 events will silently read weekly indicator values from the wrong weeks for symbols with missing bars (ADRs, thin or recently relisted tickers, providers with gaps). There is no error or warning.
Recommended fixes
1. Make ToWeekly (and monthly) group by calendar period, so bar counts match the calendar even when days are missing. If the current rule is intentional, document it precisely.
2. Provide an official daily-to-weekly mapping, e.g. a ToWeekly overload that also returns the daily-to-compressed index map, or bars.IsLastBarOfPeriod(idx, Frequency.Weekly) based on the symbol’s own data.
3. Document TradingDaysRemaining: whether it uses the market calendar or the symbol’s own bars, and that it returns 0 only when the calendar’s last day exists in the data.
4. Warn in the docs that the pattern “weekly logic on daily bars using TradingDaysRemaining == 0” assumes complete data.
5. Optional: a one-time debug warning when ToWeekly(bars).Count and the number of TradingDaysRemaining == 0 events differ by more than one.
Data provider note
With Norgate’s Padding option set to No, FER’s non-traded days are missing bars, which produces the mismatch above. With Padding enabled (non-traded market days filled with the last Close, data through 2026-11-18), the three counts agree for FER:
FER: dailyBars=2512 toWeekly=522 calendarWeeksWithData=522 TDR==0 count=521 gaps>5d=0
(TDR==0 count is one lower only because the final calendar week is still in progress.)
So the problem only appears when bars are missing. Padding is not a general fix, though: it alters indicator values (ATR, average volume, SMA, etc etc), and in my strategy it changed the trade count (552 to 559).
Workaround (what I use now)
Map by date against the weekly bars’ own dates, which is exact however ToWeekly groups bars, and mark a daily bar as “week complete” only if it is the last daily bar of its weekly bar and TradingDaysRemaining == 0. The block below is self-contained and ends with a printout that confirms the fix:
CODE:
using WealthLab.Backtest; using WealthLab.Core; using System; using System.Collections.Generic; using System.Globalization; namespace WealthScript { public class WeeklyMapDiag : UserStrategyBase { public override void Initialize(BarHistory bars) { BarHistory wklyBars = BarHistoryCompressor.ToWeekly(bars); int n = bars.Count, nw = wklyBars.Count; int[] wkOf = new int[n]; // daily idx -> weekly idx int[] wkLast = new int[nw]; // weekly idx -> last daily idx bool[] wkEnd = new bool[n]; // true on the day the weekly bar is complete for (int k = 0; k < nw; k++) wkLast[k] = -1; int kk = 0; for (int i = 0; i < n; i++) { DateTime d = bars.DateTimes[i].Date; while (kk < nw - 1 && wklyBars.DateTimes[kk].Date < d) kk++; wkOf[i] = kk; wkLast[kk] = i; } for (int i = 0; i < n; i++) wkEnd[i] = (wkLast[wkOf[i]] == i) && bars.TradingDaysRemaining(i, Frequency.Weekly) == 0; // ---- confirmation printout ---- int bad = 0; // weekly Close must equal the Close of its mapped last daily bar for (int k = 0; k < nw; k++) if (wkLast[k] < 0 || Math.Abs(wklyBars.Close[k] - bars.Close[wkLast[k]]) > 1e-6) bad++; int oldWeeks = 0, firstMis = -1; // old approach: index = number of TDR==0 events so far for (int i = 0; i < n; i++) { if (firstMis < 0 && oldWeeks != wkOf[i]) firstMis = i; if (bars.TradingDaysRemaining(i, Frequency.Weekly) == 0) oldWeeks++; } int drift = wkOf[n - 1] - oldWeeks; // weeks the old index is behind at the end of history WriteToDebugLog($"{bars.Symbol}: weeklyBars={nw}, dateMapCloseMismatches={bad}, " + $"oldCountDriftAtEnd={drift} weeks, oldCountFirstMismatch={(firstMis >= 0 ? bars.DateTimes[firstMis].ToString("d") : "none")}"); } public override void Execute(BarHistory bars, int idx) { } } }
Expected output:
dateMapCloseMismatches=0 for every symbol. This proves each weekly bar is mapped to the right daily bar.
oldCountDriftAtEnd=0 on complete-data symbols, and a large number on a sparse symbol like FER. That is the old counting method’s drift, which the date-based mapping avoids.
With this mapping, results for complete-data symbols are identical to the old mapping, and FER’s weekly series line up correctly.
Rename
TradingDaysRemaining
[An indicator that] returns the number of trading days remaining in the specified calendar interval as of bar.
TradingDaysRemaining is an indicator and it is not used to scale bars. Further, TradingDaysRemaining(idx, Frequency.Weekly) has no use in a Weekly context as you'll see below.
Important!
It's irrelevant that the instrument does not trade on every trading day in the week. Trading days are the days that the market is open. If you need an indicator that peeks ahead to tell you how many times the instrument will trade (in the future) that week, then you should create your own custom peeking indicator for that.
TradingDaysRemaining(idx, Frequency.Weekly), when used in a Daily context will give you the number of trading days left in the market's week, where Friday is 0. This Daily chart shows TradingDaysRemaining in the week annotated on each bar.

TradingDaysRemaining(idx, Frequency.Weekly), when used in a Weekly context will always be 0. The week is complete for weekly bars, and usually carries Friday's date (or whatever the last trading day was).

I know we're going to have a different opinion on this one, so I'm glad you've found a workaround for the way you see it.
[An indicator that] returns the number of trading days remaining in the specified calendar interval as of bar.
TradingDaysRemaining is an indicator and it is not used to scale bars. Further, TradingDaysRemaining(idx, Frequency.Weekly) has no use in a Weekly context as you'll see below.
Important!
It's irrelevant that the instrument does not trade on every trading day in the week. Trading days are the days that the market is open. If you need an indicator that peeks ahead to tell you how many times the instrument will trade (in the future) that week, then you should create your own custom peeking indicator for that.
TradingDaysRemaining(idx, Frequency.Weekly), when used in a Daily context will give you the number of trading days left in the market's week, where Friday is 0. This Daily chart shows TradingDaysRemaining in the week annotated on each bar.
TradingDaysRemaining(idx, Frequency.Weekly), when used in a Weekly context will always be 0. The week is complete for weekly bars, and usually carries Friday's date (or whatever the last trading day was).
I know we're going to have a different opinion on this one, so I'm glad you've found a workaround for the way you see it.
Your Response
Post
Edit Post
Login is required