Forge Fate
Quant & Data Research

Designing a Logistic Regression Baseline: Keeping Unfinished Labels Out of Training

4 min read

The ETF baseline in Part 6 compares buy-and-hold with 12-month momentum. This article designs logistic regression as the next comparison. It does not report performance from training a model on actual ETF data. Before deciding how many features to use, the first question is which outcomes are eligible for training at each point in time.

Define the prediction and the comparison

The prediction question is: “Can features available by month-end classify whether the next holding period's return will be positive?” A positive return receives label 1; zero or a negative return receives label 0. If the holding period has not ended, neither label is known yet.

Logistic regression's predict_proba returns estimated probabilities for each class. These should not automatically be interpreted as real-world frequencies of price increases or probabilities of investment success. Probability calibration and trading performance need separate evaluation. scikit-learn LogisticRegression

The comparison shares the following conditions.

ItemProposed fixed condition
DataThe same ETF universe, price definition, and snapshot as the baseline
SignalCalculated using information available by month-end
ExecutionChange weights at the next observed trading day's close; apply new weights to subsequent returns
SelectionEqual weights among assets with estimated probability at least 0.50; cash if none qualify
CostsCalculate one-way costs of 0, 5, 10, and 20 bp with the same accounting code
EvaluationCompare the same test dates, returns, drawdown, turnover, and cash allocation

The 0.50 threshold and cost scenarios are comparison assumptions. They are not optimal values or a statement about anyone's actual costs. The full-period results in Part 6 have already been observed, so reusing that period is not a new independent validation either.

A label describes the outcome between two execution reference points

This design uses the close on the trading day after the signal as the entry reference, and the execution-day close associated with the following monthly signal as the exit reference. The numbers below are illustrative, not actual ETF prices.

Signal dateEntry reference dateEntry priceNext exit priceReturnLabel
January 30February 2100110+10%1
February 27March 211099−10%0
March 31April 199Not yet knownNot yet knownMissing

When retraining on March 31, the first row's outcome is known, but the second row ends on April 1, which has not arrived. Being able to calculate the whole table afterward is different from having those outcomes available for training at the time.

Comparing and immediately converting to integers as below can turn an ordinary floating-point NaN into the non-positive class, 0.

python
monthly["label"] = monthly["forward_return"].gt(0).astype("int8")

Detect missing values explicitly rather than through value comparisons. pandas nullable integers can preserve both integer labels and missing values in one column. pandas missing-data guide

Preserve missing labels and exclude them when selecting training rows

The date columns in this example use pandas datetime types. It assumes there are no missing rows in each asset's rebalancing schedule. shift(-1) does not find the next calendar month automatically: it takes the next row for the same asset. Real data also requires checks for missing scheduled observations and price availability times.

execution_close is an execution reference price. Future outcomes attached afterward are used to construct labels; they must not enter the model's features on the signal date.

python
import numpy as npimport pandas as pddef make_samples(monthly):    # 입력: 자산별 리밸런싱 일정이 빠짐없이 정렬 가능한 월별 표.    s = monthly.sort_values(['symbol', 'signal_date']).reset_index(drop=True).copy()    if s[['symbol', 'signal_date', 'execution_date']].isna().any().any():        raise ValueError('식별자와 날짜가 필요합니다')    if s.duplicated(['symbol', 'signal_date']).any():        raise ValueError('같은 자산·신호일의 중복 행입니다')    price = s['execution_close'].to_numpy(dtype=float)    if not np.isfinite(price).all() or (price <= 0).any():        raise ValueError('체결 기준 가격은 유한한 양수여야 합니다')    if not s['execution_date'].gt(s['signal_date']).all():        raise ValueError('이 예제의 체결일은 신호일 뒤여야 합니다')    grouped = s.groupby('symbol', sort=False)    next_price = grouped['execution_close'].shift(-1)    s['label_end_date'] = grouped['execution_date'].shift(-1)    s['forward_return'] = next_price / s['execution_close'] - 1    # 마지막 행의 알 수 없는 결과를 0으로 바꾸지 않습니다.    s['label'] = pd.Series(pd.NA, index=s.index, dtype='Int8')    known = s['forward_return'].notna() & s['label_end_date'].notna()    s.loc[known, 'label'] = s.loc[known, 'forward_return'].gt(0).astype('Int8')    return sdef split_at(samples, signal_date):    train = samples.loc[        samples['signal_date'].lt(signal_date)        & samples['label_end_date'].lt(signal_date)        & samples['label'].notna()    ].copy()    # 예측에는 미래 레이블이 필요하지 않습니다.    current = samples.loc[samples['signal_date'].eq(signal_date)].copy()    return train, current

The code uses the conservative, date-level rule label_end_date < signal_date, excluding labels that finish on the same date. To use information from the same day, represent publication, receipt, and signal calculation times and verify that the outcome was known before the training cutoff.

First construct labels with samples = make_samples(monthly), then obtain train, current = split_at(samples, signal_date) for each signal date. current retains rows even when their labels are missing. The future outcome being predicted is normally not known yet.

Features and model fitting come next

Initial feature candidates include returns over the past 1, 5, and 20 trading days, 20-day volatility, and the gap between 20-day and 120-day moving averages. This is a starting list, not the confirmed specification of an executed model. Define each feature's price basis, calculation window, and availability time before fixing the list.

Place preprocessing and the classifier in one Pipeline, fitted only on that signal date's train rows. Apply the fitted transformation to current prediction rows. Standardizing with full-period means and standard deviations can introduce future distributions into training. scikit-learn guidance on preprocessing leakage

Before training:

  • Check that features are finite numbers and do not include future returns or labels.
  • Check that training data contains both classes, 0 and 1. Record the status and reason for windows that cannot support binary classification.
  • Set minimum training history and sample counts, and failure-handling rules, before looking at results.
  • Assign all ETF rows on the same signal date to the same training, validation, or test partition.

Silently dropping months with insufficient history changes the comparison period. One proposed approach is to fix a common eligible start date and record the run as failed if required checks fail after that point.

Separate selection rules from final evaluation

Define training, validation, and test boundaries by signal date. Do not change features, thresholds, or model settings selected during validation after entering the test period. If monthly retraining is allowed, predefine how earlier labels that have become known can be added during testing. That differs from choosing settings again after inspecting test performance.

Classification evaluation uses only prediction rows whose labels are known. Current predictions can still be stored without labels. Keeping these two datasets distinct prevents the final unfinished period from being evaluated against a false answer.

ObservationWhat to inspect next
Accuracy improves but after-cost return fallsLoss sizes on incorrect trades and trading volume
Drawdown and return both fallCash allocation and market exposure
Superiority appears only at 0 bpSensitivity to trading costs
Most gains come from one periodPeriod-level results and sample dependence

This article provides code for separating label availability from training time, together with a model-comparison design. It does not yet answer whether logistic regression beats the baseline on actual ETFs. That requires fixed inputs and settings, monthly predictions, and after-cost results under the same accounting rules.

The next article develops a design for comparing logistic regression and tree models under the same conditions.

Report an error or share feedback

Open a draft with this article’s title and URL. Review the message and recipient before sending.

To: [email protected]

Open email draft

If no email app opens, copy these details into your usual email service.

Contact information