未来を見ずにバックテストを行う

読了まで約53 分分、10 節 節の 7 例 例。

第2026.11.11版 2026年11月20日時点で例が通過 41 例中 41 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.11)から翻訳した。 原文を読む

本章では、1年分のカットオフに対して翌日予測を採点するときに、その履歴へ未来を混入させない方法を扱う。あわせて、データに含まれる2つの時計切り替えの時間帯の扱い方と、カットオフより先を読む特徴量を検出するシフトテストの実行方法を学ぶ。前提となるのは、第2章で得た知識である。具体的には、季節ナイーブベースライン、MAE、そして履歴から求めたスケールである。手法そのものは変わらない。変わるのは、採点を行う回数と、そのたびにデータを切り分ける際の慎重さである。

この部分はまだ翻訳されていないため、英語で表示している。

Why one test week misleads

最終変更:版2026.11.11

So far the evidence is the held-out week of Chapter 1: seven day-ahead forecasts for one client, 168 scored hours in all. A sample that size can be lucky. A forecast can match a calm week and miss the next, and one week cannot tell the two apart. Before the supplier trusts a method with each day's purchase, it needs to know how a forecast does across many days, the unusual ones included.

A backtest answers that question with the data you already have. It makes a forecast at many past moments, each with only the readings available at that moment, and scores each one against the readings that followed. Each such moment is a cutoff. Each cutoff, with the hours it forecasts, is a window. The scores of all the windows together say how the method behaves across the year, not on one week.

This matters most for the clock changes. A year of cutoffs contains the March change, when the 01:00 hour does not occur on the clock, and the October change, when one 01:00 label holds two hours of energy. A single week, such as the last week of December, contains neither. A backtest that does not reach those dates cannot show what the method does on them, so the sample has to be chosen with them in mind.

Working rule: Prefer a year of cutoffs before you trust a difference between two methods. When cost forces fewer, say so beside each score, as Chapters 4 to 9 do. Make sure the sample reaches the odd days of the year. Report how many windows and how many scored hours stand behind each number. A figure from one week is one sample, and a reader should be able to see that.

カットオフを前方へ進める

最終変更:版2026.11.11

ウィンドウは三つの部分から成る。カットオフ、ホライズン、履歴である。カットオフは予測を行う時点である。ホライズンは予測がどこまで先に及ぶかを表し、ここでは24時間である。したがって予測の対象は、カットオフから始まる24時間となる。履歴はカットオフより前の測定値のうち、モデルが利用してよいものであり、本書では1,344時間、すなわち8週間に設定する。カットオフを1ステップだけ動かすと、次のウィンドウが得られる。ステップは、日曜日のサンプルでは1週間であり、時計変更を扱う二つの節、3月の値がゼロになる時間と10月の二つの値を持つ時間の日次サンプルでは1日である。

言い換えると、各ウィンドウの予測対象はカットオフからの24時間であり、その履歴はカットオフの1,344時間前からカットオフの直前までの測定値である。次のウィンドウでは、この両方を1ステップ分だけ動かす。そのため、ある測定値が、あるウィンドウでは予測対象となり、後のウィンドウでは履歴となることがある。これは正しい扱いである。後のカットオフの時点では、その測定値はすでに過去にあり、どちらの位置でも同じ測定値だからである。

日曜日のサンプルでは、2014年1月5日から12月28日までの2014年の全日曜日について、季節ナイーブ法を実行する。EUはすべての時計変更を3月と10月の最終日曜日に置いており(指令2000/84/EC、第2条および第3条)、2014年の二回の変更、3月30日と10月26日は、いずれもこのサンプルに含まれる。サンプルには、本書の8クライアントのサブセットであるSUBSET8を用いる。この8クライアントについて、1年分をウィンドウごとに採点した結果を次に示す。

backtest-sundays-2014.py Python 3.13.16 · holidays 0.110.dev20261118063242 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 合格
"""Seasonal naive over the 52 Sunday cutoffs of 2014, for eight clients, with no clock-change rule: how much history eachwindow gets, then the year's scores. The prose's headline rests on the mean per-client MASE line."""import pandas as pdfrom holidays import country_holidaysfrom statsforecast import StatsForecastfrom statsforecast.models import SeasonalNaivefrom lib.backtest import forecast_windows, history_beforefrom lib.electricity import loadfrom lib.quirks import year_scoresfrom lib.scoring import book_scale, clients_left_outfrom lib.settings import HISTORY_HOURS, HORIZON, SUBSET8, showCOLS = ["unique_id", "ds", "y"]cutoffs = pd.date_range("2014-01-05", "2014-12-28", freq="W-SUN")  # 52 Sundays, both clock changes among themdf = load(SUBSET8)[COLS + ["quirk"]]sf = StatsForecast(models=[SeasonalNaive(season_length=24)], freq="h", n_jobs=1)  # 24 hourly readings a day: each hour copies the same hour of the day beforeforecasts = forecast_windows(sf, df[COLS], cutoffs, h=HORIZON)scored = forecasts.merge(df, on=["unique_id", "ds"])  # attaches each forecast hour's reading and its quirk flagscale = book_scale(df, cutoffs[0])  # the MASE scale: every reading before the first cutoff, from 2013 onsizes = pd.concat([history_before(df, c).groupby("unique_id").size() for c in cutoffs])  # history rows per client in each windowassert sizes.min() == sizes.max() == HISTORY_HOURS  # every window's history is the same length, the prose's claimholidays = country_holidays("PT", years=[2014])show("windows", len(cutoffs))show("history hours per series, min over windows", sizes.min())show("history hours per series, max over windows", sizes.max())show("Sunday windows on a Portuguese holiday", sum(c.date() in holidays for c in cutoffs))show("client left out of MASE", ", ".join(clients_left_out(df, cutoffs[0])))for label, value in year_scores(scored, scale).items():  # pooled MAE and RMSE, per-client MASE, the largest client's share    show(label, value)
出力python backtest-sundays-2014.py
windows: 52
history hours per series, min over windows: 1344
history hours per series, max over windows: 1344
Sunday windows on a Portuguese holiday: 1
client left out of MASE: MT_115
scored hours: 9936
scored hours before a first reading: 48
MAE: 382.02
RMSE: 1369.57
largest client by absolute error: MT_370
largest client's share of absolute error, percent: 88.69
clients in MASE: 7
mean MASE: 0.97
lowest client MASE: 0.77
highest client MASE: 1.26

どのウィンドウでも、履歴は各クライアントについて同じ1344時間であり、これは本書が定める8週間に当たる。この長さがすべてのウィンドウで同じであることは、例の中でアサートして確認している。52個のウィンドウで採点される時間は9936時間である。これは、8クライアント、各24時間にウィンドウ数を掛け、そこから、遅れて開始した1クライアントの、最初の測定値より前の時間を引いた値であり、その事情は次の段落以降で説明する。

主要な指標は、プールした誤差ではなく、クライアントごとのMASEの平均である。MASEのスケールはクライアントごとに一つの数値であり、scoring.book_scaleが本書全体のデータについて計算する。最初のカットオフより前のすべての測定値を対象とし、時計変更の時間はマスクし、各クライアントの先頭のゼロは取り除く。最初のカットオフは2014年1月5日であるから、このサンプルのスケールは2013年1月1日から2014年1月4日までの測定値から求める。クライアントごとのMASEの平均は0.97、最小は0.77、最大は1.26であり、対象は7クライアントである。

採点対象の時間にわたるプールしたMAEは382.02 kWhであり、同じクライアントとウィンドウの上で手法どうしを比較するには使えるが、クライアント間の比較には使えない。最大のクライアントであるMT_370は、絶対誤差の88.69パーセントを占める。このクライアントは1時間に数千キロワット時を使用するため、誤差も数千のオーダーになるからである。RMSEは1369.57 kWhである。

クライアントMT_115には、2014年1月14日より前の測定値がない。それまでメーターはゼロを報告しており、データカードはそのゼロが需要ではないと述べている。コードは、最初の測定値より前の48時間をすべての採点から除外する。これは最初の二つのウィンドウに当たる。ただし履歴にはそのゼロが残っている。履歴の開始規則は第4章で扱うからである。このクライアントのMASEを除外するのは別の理由による。スケールは2014年1月5日より前の測定値から求めるが、このクライアントにはそれがないのである。出力では、このクライアントをMASEから除外したものとして記載し、開始規則はその章に委ねる。

statsforecastライブラリには、このループのための関数cross_validationがあるが、意図したウィンドウにならないまま呼び出すことが可能である。バージョン2.1.1では、input_sizeを渡さない限り、各ウィンドウの訓練用スライスは系列の最初の測定値から始まる。すると履歴はウィンドウごとに伸びていき、8週間という規則は効力を失う。HyndmanとAthanasopoulosは、訓練セットはテストセットより前の観測のみから成るという原則を述べている(Forecasting: Principles and Practice、第3版、第5章)。cross_validationの背後にあるコードが、そのセットの長さを決める(statsforecast 2.1.1、statsforecast/core.py)。そのカットオフは、ウィンドウが訓練に使う最後の時間であるのに対し、本章のカットオフはウィンドウが予測する最初の時間であるため、二つの名前は1時間だけ異なる。本章では、各ウィンドウの履歴をカットオフから後ろへさかのぼって自前で構築する。これにより、どのウィンドウでも同じ1,344時間となり、規則がコードの上に明示される。

実践ルール: 履歴の長さは時間単位で明示的に設定し、すべてのウィンドウで同じであることを確認する。ライブラリがウィンドウのループを代行する場合は、その出力を信頼する前に、訓練用スライスをどのように設定しているかを読むこと。既定値が、選んだ長さではなく拡張ウィンドウである可能性があるからである。

この部分はまだ翻訳されていないため、英語で表示している。

Keep the future out of the history

最終変更:版2026.11.5

A backtest leaks when a window's model sees a reading from the hours it is asked to forecast. The reading can reach the model in several ways: through the history, through a feature, or through a scale computed from data that includes the target. Hewamalage, Ackermann and Bergmeir describe rolling-origin evaluation as prone to exactly this, because the test data of one window becomes training data of the next. In forecasting, they note, the leak is easier to make and harder to avoid than in other machine learning tasks (2022, section 3.4).

One rule closes the history path. Each window's history is the readings whose timestamps fall in the eight weeks before its cutoff, and nothing at or after the cutoff. In the book's code, history_before keeps the rows with ds from the cutoff minus 1,344 hours up to, but not including, the cutoff. The reading at the cutoff itself belongs to the target day, so the same comparison excludes it. Membership is decided by timestamps, not by row positions, so a missing row cannot shift a window by an hour. history_before also raises an error unless every client has exactly 1,344 rows in the window.

The window's own first hour is the cutoff, so a cut that is one hour too generous passes the first target reading into the history, and nothing in a forecast shows it. A row count can catch it, and the example below counts the rows.

history-cut-check.py Python 3.13.16 · numpy 2.5.5 · pandas 2.3.3 · utilsforecast 0.2.17 合格
"""One window's history, cut by its cutoff: its first and last timestamps, and what a cut that keeps the cutoff hour adds.The prose's timestamps rest on the first two lines, and its off-by-one point on the row countswith the cutoff hour in and out."""import pandas as pdfrom lib.backtest import history_beforefrom lib.electricity import loadfrom lib.settings import HISTORY_HOURS, LEAD, showdf = load([LEAD])  # the lead client's readings only: one series is enough to show the cutcutoff = pd.Timestamp("2014-12-29")  # the window's cutoff at midnight, which is also its first forecast hourhist = history_before(df, cutoff)  # the 1,344 hours before the cutoff; the cutoff hour itself is not in itshow("history rows", len(hist))show("first history timestamp", hist["ds"].min().strftime("%Y-%m-%d %H:%M"))show("last history timestamp", hist["ds"].max().strftime("%Y-%m-%d %H:%M"))wrong = df[(df["ds"] >= cutoff - pd.Timedelta(hours=HISTORY_HOURS)) & (df["ds"] <= cutoff)]  # the off-by-one cut: <= keeps the cutoff hourshow("history rows with ds at or before the cutoff", len(wrong))show("target-day readings in that cut", int((wrong["ds"] == cutoff).sum()))
出力python history-cut-check.py
history rows: 1344
first history timestamp: 2014-11-03 00:00
last history timestamp: 2014-12-28 23:00
history rows with ds at or before the cutoff: 1345
target-day readings in that cut: 1

Keeping the cutoff hour adds one row, and the count shows it. The history for the cutoff of Dec 29, 2014 runs from 2014-11-03 00:00 to 2014-12-28 23:00 and holds 1344 rows. A cut with ds <= cutoff holds 1345 rows, because the target day's first reading, the cutoff hour, has entered the history. A count one row too high is the sign of that error.

The same care applies to the scale. evaluate in utilsforecast takes a training frame for its scale, and it cuts that frame by time only when the forecast frame carries a cutoff column. Then it keeps the training rows with ds at or before the cutoff, which includes the cutoff hour itself (utilsforecast 0.2.17, evaluation.py). This chapter does not use that option. Its scale comes from scoring.book_scale, which passes only the rows before the first cutoff, and the frame it scores has no cutoff column.

Working rule: Slice each window's history by its cutoff, never by the start of its test window, and pass a library only the rows it may use. Check the first and last timestamps of every history, and make sure the last one is an hour before the cutoff.

時計の切り替えを知る

最終変更:版2026.11.5

このデータには、1 時間ごとに 1 件の読み取り値があるという単純な見方に当てはまらない時間が 2 つある。3 月の切り替え日には、現地の時計は 00:59 から 02:00 に進むため、01:00 の時間帯は時計上に存在しない。ポルトガル本土は冬にグリニッジ標準時を採用しており、EU は時計をグリニッジ標準時の 01:00、すなわち現地時間の 02:00 に切り替える(Directive 2000/84/EC、第 2 条)。10 月の切り替え日には、時計は 02:00 から 01:00 に戻るため、01:00 の時間帯は 2 回現れる。ファイルには 1 日につき 01:00 の行が 1 行あり、本書のデータでは clock_change_gap または clock_change_repeat としてフラグが付けられている。

本書は、1 つの明示した前提のもとでこのファイルを読み、以降のすべての章がこの前提に依拠する。読み取り値のタイムスタンプ ds は、現地時間でのその時間帯の開始時刻であり、インデックスはタイムゾーンを持たない 1 本のナイーブな 1 時間単位のインデックスである。3 月の証拠はこの読み方を裏付ける。データセット自体の注記が、Dataset 321 of the UCI Machine Learning Repository に記されており、3 月の切り替え日の 01:00 の値はすべての顧客についてゼロであるとしている。ファイルはおおむねこれと一致する。このことは最初の小節で示し、2 番目の小節では 10 月のラベルに現れる 2 つの時間帯を示す。

この部分はまだ翻訳されていないため、英語で表示している。

The March hour that reads zero

最終変更:版2026.11.5

On Mar 30, 2014, the 01:00 label reads zero for 5 of the eight clients in the subset. The others read a small amount, not an hour of demand. The census covers all thirty clients.

clock-change-census.py Python 3.13.16 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 合格
"""The clock-change hours of all thirty clients, each against its neighbours. The point that the March hours read near zerorests on the gap rows below 5 percent of their neighbours, with the zero count and the median ratio beside them."""from lib.electricity import loadfrom lib.quirks import clock_ratiosfrom lib.settings import showr = clock_ratios(load())  # each clock-change hour divided by the mean of the hour before and the hour aftergap = r[r["quirk"] == "clock_change_gap"]  # the file's flag: 01:00 on the March change day, an hour the clock skipsrepeat = r[r["quirk"] == "clock_change_repeat"]  # the file's flag: 01:00 holds two hours on the October change dayshow("gap rows", len(gap))show("gap rows that read zero", int((gap["y"] == 0).sum()))show("gap rows that read above zero", int((gap["y"] > 0).sum()))show("gap rows below 5 percent of their neighbours", int((gap["ratio"] < 0.05).sum()))  # a NaN ratio, where both neighbours are zero, counts in neither lineshow("gap rows at or above 5 percent of their neighbours", int((gap["ratio"] >= 0.05).sum()))show("median gap ratio to neighbours", gap["ratio"].median(), digits=3)show("repeat rows", len(repeat))show("median repeat ratio to neighbours", repeat["ratio"].median(), digits=3)
出力python clock-change-census.py
gap rows: 57
gap rows that read zero: 40
gap rows that read above zero: 17
gap rows below 5 percent of their neighbours: 55
gap rows at or above 5 percent of their neighbours: 2
median gap ratio to neighbours: 0.000
repeat rows: 58
median repeat ratio to neighbours: 1.948

Most flagged hours read near zero: 55 of the 57 flagged client-hours on the two March change days sit below 5 percent of their neighbouring hours, which is what this chapter means by near zero. The median ratio to the neighbours is 0.000.

The file mostly agrees with the dataset's note: 40 of the 57 read exactly zero, and 17 read above zero.

The data say zero or near zero, enough for the rule. The meter recorded nothing for an hour that did not occur on the clock, so the reading is not demand.

Seasonal naive copies the last day's values forward, so the forecast for 01:00 on Mar 30 is the demand of Mar 29 at 01:00. That is an ordinary hour, and where the reading is zero, the error is the whole forecast.

Make a guess before the next run. The cutoff of Mar 31 looks back over 24 hours, and those hours include the zero. How large is the error at 01:00 on Mar 31 compared with an ordinary hour? The run covers the 15 daily cutoffs from Mar 23 to Apr 6, 2014, first with no rule and then with the rule from the next section:

clock-gap-daily-cutoffs.py Python 3.13.16 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 合格
"""Seasonal naive around the March clock change, for eight clients: the raw failure, then the rule. The prose's claims reston the gap-hour and next-day 1am lines, with and without the rule, the median client ratios, and the count of missingforecasts without the fill."""import pandas as pdfrom lib.backtest import history_beforefrom lib.electricity import loadfrom lib.quirks import filled_history, mae_of, mask_clock_changes, median_client_ratio, seasonal_naive_atfrom lib.settings import SUBSET8, showcutoffs = pd.date_range("2014-03-23", "2014-04-06", freq="D")  # 15 daily cutoffs around Mar 30, 2014next_day = pd.Timestamp("2014-03-31 01:00")  # 01:00 the day after the change: the forecast that copies the zerodf = load(SUBSET8)[["unique_id", "ds", "y", "quirk"]]masked = mask_clock_changes(df)  # a copy with the gap and repeat hours set to NaNraw = seasonal_naive_at(df, cutoffs, lambda c: history_before(df, c))  # no rule: the history keeps the zeros as the file has themgap = raw["quirk"] == "clock_change_gap"  # the file's flag marks the gap hoursat_next_day = raw["ds"] == next_dayshow("gap hours in actuals", int(gap.sum()))show("gap hours that read zero", int((raw[gap]["y"] == 0).sum()))show("gap-hour MAE with no rule", mae_of(raw[gap]))show("other-hour MAE with no rule", mae_of(raw[~gap]))# per client: the mean error at gap hours over the mean at other hours, then the median across clientsshow("median client ratio, gap hour to other hours, no rule", median_client_ratio(raw, gap, ~gap))show("next-day MAE at 1am with no rule", mae_of(raw[at_next_day]))# a forecast of exactly zero is the March zero copied forward from the day beforeshow("next-day 1am forecasts that are zero, no rule", int((raw[at_next_day]["SeasonalNaive"] == 0).sum()))show("median client ratio, next-day 1am to other hours, no rule", median_client_ratio(raw, at_next_day, ~gap))no_fill = seasonal_naive_at(masked, cutoffs, lambda c: history_before(masked, c))  # masked history, no fill: a NaN copies forward and stays NaNshow("NaN forecasts without the fill", int(no_fill["SeasonalNaive"].isna().sum()))fixed = seasonal_naive_at(masked, cutoffs, lambda c: filled_history(masked, c))  # the rule: masked hours filled from the history before each cutoffshow("next-day MAE at 1am with the rule", mae_of(fixed[fixed["ds"] == next_day]))show("other-hour MAE with the rule", mae_of(fixed[fixed["quirk"] != "clock_change_gap"]))
出力python clock-gap-daily-cutoffs.py
gap hours in actuals: 8
gap hours that read zero: 5
gap-hour MAE with no rule: 2322.69
other-hour MAE with no rule: 234.21
median client ratio, gap hour to other hours, no rule: 7.93
next-day MAE at 1am with no rule: 2393.01
next-day 1am forecasts that are zero, no rule: 5
median client ratio, next-day 1am to other hours, no rule: 9.92
NaN forecasts without the fill: 8
next-day MAE at 1am with the rule: 274.41
other-hour MAE with the rule: 228.31

For the median client, the error at 01:00 on Mar 31 is 9.92 times its error at other hours. The forecast for that hour copies the zero for 5 clients.

The gap hour itself fails as well. Its pooled error is 2322.69 kWh, against 234.21 kWh at other hours, and the median client's ratio is 7.93. Both pooled figures are set mostly by the largest client, while the per-client median counts each client once.

Pooled, the next day's error at 01:00 is 2393.01 kWh, about as much as the gap hour's. The method is wrong on the change hour, and wrong by about as much the day after, because it copied the zero.

Working rule: Treat a 01:00 reading of zero on a March clock-change day as a missing hour, not as zero demand. Keep it out of a model's history and out of the scores, and do not let a seasonal method copy it into the next day.

2つ分の時間を含む10月の1時間

最終変更:版2026.11.5

2014年10月26日、01:00のラベルにはおよそ2時間分のエネルギーが含まれている。センサスによると、この時間帯と前後の時間帯との比の中央値は1.948であり、これはファイル内でフラグが付いた58件のクライアント時間に基づく値である。UCIの注記も一致しており、01:00の値は2時間分の消費量を集計したものであるとされている。

この失敗は3月の場合とは逆である。時刻変更日には、季節ナイーブ予測は01:00のラベルを前日の値から予測する。前日の値は通常の1時間であり、実績値はその約2倍になる。10月27日のカットオフはこの2倍の値をそのままコピーするため、10月27日の01:00の予測値は通常の1時間の約2倍となり、実績値は通常の値になる。

同じ比較を、2014年10月19日から11月2日までの15回の日次カットオフについて行う。

clock-repeat-daily-cutoffs.py Python 3.13.16 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 合格
"""Seasonal naive around the October clock change, for eight clients: the raw failure, then the rule. The prose's claims reston the repeat-hour and next-day 1am lines, the median client ratios, and the count of missing forecasts without the fill."""import pandas as pdfrom lib.backtest import history_beforefrom lib.electricity import loadfrom lib.quirks import filled_history, mae_of, mask_clock_changes, median_client_ratio, seasonal_naive_atfrom lib.settings import SUBSET8, showcutoffs = pd.date_range("2014-10-19", "2014-11-02", freq="D")  # 15 daily cutoffs around Oct 26, 2014next_day = pd.Timestamp("2014-10-27 01:00")  # 01:00 the day after the change: the forecast that copies the doubled valuedf = load(SUBSET8)[["unique_id", "ds", "y", "quirk"]]masked = mask_clock_changes(df)  # a copy with the gap and repeat hours set to NaNraw = seasonal_naive_at(df, cutoffs, lambda c: history_before(df, c))  # no rule: the history keeps the doubled 01:00 valuerepeat = raw["quirk"] == "clock_change_repeat"  # the file's flag: two hours of energy in one 01:00 labelat_next_day = raw["ds"] == next_dayshow("repeat hours in actuals", int(repeat.sum()))show("repeat-hour MAE with no rule", mae_of(raw[repeat]))show("other-hour MAE with no rule", mae_of(raw[~repeat]))# per client: the mean error at the repeat hour over the mean at other hours, then the median across clientsshow("median client ratio, repeat hour to other hours, no rule", median_client_ratio(raw, repeat, ~repeat))show("next-day MAE at 1am with no rule", mae_of(raw[at_next_day]))show("median client ratio, next-day 1am to other hours, no rule", median_client_ratio(raw, at_next_day, ~repeat))no_fill = seasonal_naive_at(masked, cutoffs, lambda c: history_before(masked, c))  # masked history, no fill: a NaN copies forward and stays NaNshow("NaN forecasts without the fill", int(no_fill["SeasonalNaive"].isna().sum()))fixed = seasonal_naive_at(masked, cutoffs, lambda c: filled_history(masked, c))  # the rule: masked hours filled from the history before each cutoffshow("next-day MAE at 1am with the rule", mae_of(fixed[fixed["ds"] == next_day]))show("other-hour MAE with the rule", mae_of(fixed[fixed["quirk"] != "clock_change_repeat"]))
出力python clock-repeat-daily-cutoffs.py
repeat hours in actuals: 8
repeat-hour MAE with no rule: 637.18
other-hour MAE with no rule: 397.96
median client ratio, repeat hour to other hours, no rule: 6.98
next-day MAE at 1am with no rule: 1524.26
median client ratio, next-day 1am to other hours, no rule: 7.53
NaN forecasts without the fill: 8
next-day MAE at 1am with the rule: 184.22
other-hour MAE with the rule: 394.23

プールした数値は、変更時間帯での失敗を過小に見せる。変更時間帯では予測が通常の1時間で実績が2倍になるため、プールした誤差は637.18 kWhとなり、他の時間帯では397.96 kWhである。この差が実際より小さく見えるのは、最大のクライアントの誤差がどの時間帯でも大きいためである。中央値のクライアントでは、変更時間帯の誤差は他の時間帯の誤差の6.98倍である。

2倍の値が最も大きな被害を与えるのは翌日である。10月27日の01:00の予測はその値をコピーするため、この時間帯のプールした誤差は1524.26 kWhであり、3つの中で最大となる。中央値のクライアントの比は7.53である。10月の生のラベルを通常の1時間として扱う読者は、ある1時間を過小に予測し、次の1時間を過大に予測することになる。

実践ルール: 10月の01:00のラベルは、1つの枠に2時間分のエネルギーが入ったものとして扱い、通常の1時間として扱ってはならない。1時間分に見せるために半分にしてもいけない。その理由は次の節で述べる。

この部分はまだ翻訳されていないため、英語で表示している。

Mark clock-change hours as missing

最終変更:版2026.11.5

The rule the book uses is a choice, and this section states it in one place so that every later chapter can call the same code. Both 01:00 hours, the March gap and the October repeat, are set to missing in the history and in the scores, so a masked hour is never scored. A model that takes missing values skips the hour. A model that cannot, such as seasonal naive, reads a filled value instead, because a missing value would copy into the next day's forecast. Either way the hour is never scored, and the forecast still produces a value for its label, because the output grid must stay complete. The fill is the mean of the hour before and the hour after, taken from the history before the cutoff only. It is a rule of thumb for an hour that sits between two ordinary ones, and it is labelled as one.

Halving the October label instead would give each real hour half of its reading, which assumes both hours used the same energy. The data card does not show that, so the book does not do it.

Without the fill, the forecast for 01:00 on the day after each change is missing for 8 of the eight clients in March, and for 8 in October.

With the fill, the next-day error at that hour falls from 2393.01 to 274.41 kWh in March, and from 1524.26 to 184.22 kWh in October, while the error at other hours moves little.

The year of Sunday cutoffs is a different test, because it applies the mask to the scores and the fill plays no part. Scoring the year twice, plain and masked, shows how much the two hours moved the headline.

clock-masked-backtest.py Python 3.13.16 · numpy 2.5.5 · pandas 2.3.3 · statsforecast 2.1.1 · utilsforecast 0.2.17 合格
"""The Sunday backtest of 2014 for eight clients, scored twice: as the readings stand, and with the clock-change rule, whichleaves the masked hours out of the scores and fills the history. The prose's comparison rests on the masked-hour count,the two pooled MAE lines, the two mean MASE lines and the two scored-hour lines."""import pandas as pdfrom lib.backtest import history_beforefrom lib.electricity import loadfrom lib.quirks import CLOCK_CHANGE_QUIRKS, filled_history, mask_clock_changes, seasonal_naive_at, year_scoresfrom lib.scoring import book_scalefrom lib.settings import SUBSET8, showcutoffs = pd.date_range("2014-01-05", "2014-12-28", freq="W-SUN")  # the same 52 Sunday cutoffs as the plain backtestdf = load(SUBSET8)[["unique_id", "ds", "y", "quirk"]]masked = mask_clock_changes(df)  # a copy with the gap and repeat hours set to NaN; the rule's scores skip themscale = book_scale(df, cutoffs[0])  # book_scale masks the clock-change hours itself, so both runs share this one scaleplain = seasonal_naive_at(df, cutoffs, lambda c: history_before(df, c))  # as the readings stand: the zeros and the doubled hour stay inruled = seasonal_naive_at(masked, cutoffs, lambda c: filled_history(masked, c))  # the rule: history filled from before each cutoffshow("masked hours in scored windows", int(plain["quirk"].isin(CLOCK_CHANGE_QUIRKS).sum()))  # counted in the plain run, where the flags are still presentfor tag, scored in [("without the mask", plain), ("with the mask", ruled)]:    result = year_scores(scored, scale)    show(f"scored hours {tag}", result["scored hours"])    show(f"MAE {tag}", result["MAE"])    show(f"mean MASE {tag}", result["mean MASE"])
出力python clock-masked-backtest.py
masked hours in scored windows: 16
scored hours without the mask: 9936
MAE without the mask: 382.02
mean MASE without the mask: 0.97
scored hours with the mask: 9920
MAE with the mask: 380.25
mean MASE with the mask: 0.96

The mask takes 16 masked hours out of the scored windows, the March and October hours of the subset, and the pooled MAE moves only a little, from 382.02 kWh to 380.25 kWh.

The mean MASE goes from 0.97 to 0.96, over 9920 scored hours rather than 9936. The difference comes from the removed hours.

The Sunday sample cannot show the fill at all, because seasonal naive reads only the day before each cutoff, which is a Saturday for every Sunday cutoff, and no Saturday holds a clock change.

Working rule: Mark both clock-change hours missing in every history and every score, count the masked hours in your report, and fill them from the history before the cutoff only when the model cannot take missing values. If the count of masked hours changes from one run to the next, the sample or the file's flags have changed, and you should find out why before you rerun the scores.

この部分はまだ翻訳されていないため、英語で表示している。

Check a backtest for leakage

最終変更:版2026.11.11

Every window in a backtest should be built from data available at its cutoff, so the check for a leak is simple to state. A feature for a window must have the same value whether it is computed from the history cut at the cutoff or from the whole series. If the two values differ, the feature read a reading after the cutoff, and the backtest flatters the method. The shift test compares a feature computed from the history cut at the cutoff with the same feature computed from the whole series. It is cheap to run, and it catches a mistake that the backtest cannot catch on its own, because a leaking feature scores well by design.

The test has two halves, and each catches what the other misses. Take the lead client, MT_014, and three features over its hourly readings. The first is a trailing mean: the average of the 24 hours up to and including each hour, which reads nothing after its hour. The second is the same mean shifted one hour forward, so each value is the average of a window that ends one hour later, and it reads the first hour after the cutoff. The third is a lag of one hour, the most common day-ahead leak. The history half compares each feature on the rows of the eight weeks before each of the three evaluation cutoffs, Dec 29 to Dec 31, 2014. The target half compares the 24 hours that each cutoff forecasts, computed from the readings before the cutoff only. Both versions start from the same first reading, so the warm-up of a rolling mean matches on both sides. Computed from different starts, the warm-up and floating-point rounding would show as false differences, which is why the check compares with a tolerance:

leakage-shift-check.py Python 3.13.16 · numpy 2.5.5 · pandas 2.3.3 合格
"""Shift test: a feature must read nothing from its cutoff on, on the history rows and on the target hours. The prose'spoint rests on the counts of differing rows: an honest feature shows zero, and a leaking one shows its leak."""from lib.electricity import loadfrom lib.leakage import history_test, lag, peeking_mean, target_test, trailing_meanfrom lib.settings import EVAL_CUTOFFS, LEAD, showy = load([LEAD]).set_index("ds")["y"]  # indexed by timestamp, so each feature can be cut at a cutoff by timecompared, honest = history_test(y, trailing_mean)  # rows compared, and the rows where cutting at the cutoff changes the feature_, peeking = history_test(y, peeking_mean)  # the leaking feature: its last value before each cutoff reads the cutoff hour_, lag1_history = history_test(y, lag(1))  # lag 1 reads only the past on history rows, so this half passes itshow("cutoffs", len(EVAL_CUTOFFS))show("rows compared", compared)show("rows differing for the trailing mean", honest)show("rows differing for the peeking mean", peeking)show("rows differing for lag 1", lag1_history)targets, lag1_target = target_test(y, lag(1))  # target hours compared, and the hours that differ, over the 24 hours of each cutoff_, lag24_target = target_test(y, lag(24))show("target hours compared", targets)show("target hours differing for lag 1", lag1_target)show("target hours differing for lag 24", lag24_target)
出力python leakage-shift-check.py
cutoffs: 3
rows compared: 4032
rows differing for the trailing mean: 0
rows differing for the peeking mean: 3
rows differing for lag 1: 0
target hours compared: 72
target hours differing for lag 1: 69
target hours differing for lag 24: 0

On the history rows, the shifted mean differs on 3 of the 4032 compared, one at each cutoff: the last hour before each cutoff, whose value depends on the reading at the cutoff itself. The trailing mean differs on 0 of them.

The lag of one hour is the case the history half cannot catch. It differs on 0 history rows, because every row it reads lies in the past, so the history half alone passes it.

On the 72 target hours it differs on 69, since for every target hour after the first, the reading it uses is in the day being forecast. The lag of 24 hours differs on 0 of them, because it reads the same hour of the day before, which was known at each cutoff.

The shift test checks features and nothing else. It does not check the scale, the fill or the model's own code, which is why the earlier sections set those rules separately. Run it on every feature a model reads, at several cutoffs spread through the year, and include a cutoff on a clock-change day if the feature reads the hour before it.

When a feature fails the test, do not fix the score. Move the feature back until it reads only what was known at its cutoff, then run the test again until the count is zero.

Working rule: Keep every lag at least the horizon, 24 hours, so that the reading a lag uses for any target hour was known at the cutoff. Before you trust a backtest with features, run both halves of the shift test on every feature, at several cutoffs spread through the year, and require zero differing rows for every feature the model reads. A feature that differs is reading the future, so fix or remove it before you score anything.

この部分はまだ翻訳されていないため、英語で表示している。

What goes wrong in production

最終変更:版2026.11.5

A backtest is a sample of the past, and the sample is chosen. Every clock change falls on the last Sunday of March or October (Directive 2000/84/EC, Articles 2 and 3), so a Sunday sample reaches every change. A sample of Mondays would reach the day after each change without reaching the change hour itself, so the choice of days changes what the backtest can see. Record which dates the sample covers, and rerun the clock check when the sample's dates change.

Calendar effects are a separate sample problem. Easter Sunday, Apr 20, 2014, is a Portuguese holiday, which the holidays package lists for Portugal, and the run counts it: 1 of 52 windows. The held-out week contains Dec 25, 2014, a national holiday in Portugal, and a week of ordinary days and one holiday gives a different score from a week of ordinary days alone. A backtest that uses holiday features must count the holidays in its windows, and say how many fall in the sample.

A pooled error hides the windows that went wrong. A year of windows can average to a respectable number while one month, or one client, carries the error. Break the scores down by month and by client before you report one figure, and look at the worst windows, not only the average.

The masked count follows the calendar flag, not the readings. It changes when the sample's dates or the file's flags change, and it cannot see drift in the readings. Count the masked hours on every run, and alarm on a change in the count, because it is the cheapest signal that the sample or the file has changed. Drift in the readings needs the census: the gap hours that read zero, and the repeat hours against their neighbours. Chapter 10 returns to this in the running log.

Finally, a backtest that passes the shift test can still leak through the scale or the fill, if either is taken from data after the cutoff. The checks in this chapter cover those paths in the examples and the rules, not in every library a reader might use. A reader who adds a library should read how it cuts its training data, as the default of cross_validation shows.

Working rule: Run the clock and shift checks again on every data refresh, and before any change to the sample's dates, the history length or the scale. Keep the masked-hour count, the census counts and the shift-test counts in the run log next to the scores, so that a later change in either can be traced to its cause.

この章で下した判断

最終変更:版2026.11.5
  • バックテストには2014年の日曜日のカットオフを用いる。時計の切り替えはすべて日曜日に起こるため、標本はどの切り替えにも届き、2014年の2回の切り替えはどちらも含まれる。
  • どのウィンドウの履歴も、カットオフの前の1,344時間をカットオフで切ったものとする。この長さはコードで定め、ライブラリの既定値には任せない。
  • タイムスタンプ ds は、タイムゾーンを持たない現地時計時刻での、その時間の開始時刻である。本書はこの前提でファイルを読む。
  • 時計の切り替えがある2つの時間は、すべての履歴とすべてのスコアでマスクする。欠損値を扱えないモデルには、カットオフ以前の履歴から得た前後の時間の平均値を読ませる。
  • 10月の時間を半分にする方法は採らない。この方法は、実際の2つの時間が同じエネルギーを使ったと仮定しているが、データはそれを示していないからである。
  • 主要な指標は、第2章から scoring.book_scale までの単一のスケールで求めた、顧客ごとのMASEの平均である。プールしたMAEを第2の指標とし、最大の顧客の占める割合を併せて出力する。
  • 本文が引用する数値はすべて、第1章で示したとおり、その例の出力のラベル付きの行に結び付けたままにする。そのため、ライブラリの更新があれば章の数値が変わり、誰も手で打ち直す必要はない。
  • 最初のカットオフより前に読み取りが1件もない顧客は、MASEから除く。開始が遅い顧客については、最初の読み取りより前の時間をすべてのスコアから除く。履歴の開始規則は第4章で定める。
  • シフト検定は、すべての特徴量に対して、前半と後半の両方で行う。すべてのラグは少なくとも予測ホライズン以上とし、いずれかのカットオフで値が異なる特徴量は使わない。

この版における本章

第2026.11.11版2026年11月20日時点で例が通過この章の7 例件のうち7件が合格

英語版の書籍(版2026.11.11)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全10章中の第3章: 未来を見ずにバックテストを行う

  1. Why one test week misleads
  2. カットオフを前方へ進める
  3. Keep the future out of the history
  4. 時計の切り替えを知る
  5. The March hour that reads zero
  6. 2つ分の時間を含む10月の1時間
  7. Mark clock-change hours as missing
  8. Check a backtest for leakage
  9. What goes wrong in production
  10. この章で下した判断

ページの先頭に戻るすべての章