Skip to content

expanding_rsquare always return nan #14

@evanzd

Description

@evanzd

Reproduce the bug:

import numpy as np
import statsmodels.api as sm

from qlib.data._libs.rolling import rolling_rsquare, rolling_resi, rolling_slope, rolling_mean
from qlib.data._libs.expanding import expanding_rsquare, expanding_resi, expanding_slope, expanding_mean

x = np.random.randn(100)

print('test rolling')
# window size = 20
assert np.isclose(x[-20:].mean(), rolling_mean(x, 20)[-1])
model = sm.OLS(x[-20:], sm.add_constant(np.arange(20))).fit()
assert np.isclose(model.params[1], rolling_slope(x, 20)[-1])
assert np.isclose(model.resid[-1], rolling_resi(x, 20)[-1])
assert np.isclose(model.rsquared, rolling_rsquare(x, 20)[-1])

print('test expanding')
model = sm.OLS(x, sm.add_constant(np.arange(len(x)))).fit()
assert np.isclose(model.params[1], expanding_slope(x)[-1])
assert np.isclose(model.resid[-1], expanding_resi(x)[-1])
assert np.isclose(model.rsquared, expanding_rsquare(x)[-1]) # the bug one
print(expanding_rsquare(x)) # all nan

It can be fixed by changing this line

self.x2_sum += size
to

self.x2_sum += size * size

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions