Skip to content

fix: correct WMA calculation to use nansum instead of nanmean#2109

Open
Ayush10 wants to merge 1 commit intomicrosoft:mainfrom
Ayush10:fix/issue-1993-wma-calculation
Open

fix: correct WMA calculation to use nansum instead of nanmean#2109
Ayush10 wants to merge 1 commit intomicrosoft:mainfrom
Ayush10:fix/issue-1993-wma-calculation

Conversation

@Ayush10
Copy link

@Ayush10 Ayush10 commented Jan 30, 2026

Summary

Closes #1993

The weighted_mean function in WMA._load_internal (qlib/data/ops.py) normalizes weights to sum to 1 via w = w / w.sum(), then incorrectly uses np.nanmean(w * x) which divides by the element count again. The correct function is np.nansum(w * x) since the weights already sum to 1.

This is consistent with how EMA.exp_weighted_mean is implemented (which already uses np.nansum).

Before

def weighted_mean(x):
    w = np.arange(len(x)) + 1
    w = w / w.sum()
    return np.nanmean(w * x)  # BUG: divides by count again

After

def weighted_mean(x):
    w = np.arange(len(x)) + 1
    w = w / w.sum()
    return np.nansum(w * x)  # correct: weights already sum to 1

Test Plan

  • Change is consistent with EMA implementation pattern
  • Single-line fix, minimal risk

…oft#1993)

The weighted_mean function normalizes weights to sum to 1, so
np.nanmean (which divides by count) produces incorrect results.
Use np.nansum instead, consistent with the EMA implementation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

WMA计算错误

1 participant