This commit is contained in:
@@ -312,7 +312,7 @@ def ols_regress(
|
|||||||
ss_tot = float(((y_arr - y_arr.mean()) ** 2).sum())
|
ss_tot = float(((y_arr - y_arr.mean()) ** 2).sum())
|
||||||
r_sq = 1.0 - ss_res / ss_tot if ss_tot > 0 else np.nan
|
r_sq = 1.0 - ss_res / ss_tot if ss_tot > 0 else np.nan
|
||||||
sigma2 = ss_res / max(n - k, 1)
|
sigma2 = ss_res / max(n - k, 1)
|
||||||
# 协方差矩阵 = sigma2 * (X'X)^-1
|
# 广义协方差矩阵 = sigma2 * (X'X)^+,伪逆兼容共线因子。
|
||||||
xtx_inv = np.linalg.pinv(x_arr.T @ x_arr) if sigma2 > 0 else np.full((k, k), np.nan)
|
xtx_inv = np.linalg.pinv(x_arr.T @ x_arr) if sigma2 > 0 else np.full((k, k), np.nan)
|
||||||
se = np.sqrt(np.diag(xtx_inv) * sigma2)
|
se = np.sqrt(np.diag(xtx_inv) * sigma2)
|
||||||
t_vals = coef / se if sigma2 > 0 else np.full_like(coef, np.nan)
|
t_vals = coef / se if sigma2 > 0 else np.full_like(coef, np.nan)
|
||||||
|
|||||||
@@ -5,14 +5,13 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
from numpy.typing import NDArray
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from numpy.typing import NDArray
|
||||||
|
|
||||||
def _validate_inputs(
|
|
||||||
weights: NDArray[Any], cov: NDArray[Any]
|
def _validate_inputs(weights: NDArray[Any], cov: NDArray[Any]) -> tuple[NDArray[Any], NDArray[Any]]:
|
||||||
) -> tuple[NDArray[Any], NDArray[Any]]:
|
|
||||||
"""Normalize a portfolio vector and its covariance matrix."""
|
"""Normalize a portfolio vector and its covariance matrix."""
|
||||||
w = np.asarray(weights, dtype=float).ravel()
|
w = np.asarray(weights, dtype=float).ravel()
|
||||||
covariance = np.asarray(cov, dtype=float)
|
covariance = np.asarray(cov, dtype=float)
|
||||||
@@ -20,9 +19,7 @@ def _validate_inputs(
|
|||||||
if k == 0:
|
if k == 0:
|
||||||
raise ValueError("weights must contain at least one asset")
|
raise ValueError("weights must contain at least one asset")
|
||||||
if covariance.shape != (k, k):
|
if covariance.shape != (k, k):
|
||||||
raise ValueError(
|
raise ValueError(f"cov shape {covariance.shape} does not match weights length {k}")
|
||||||
f"cov shape {covariance.shape} does not match weights length {k}"
|
|
||||||
)
|
|
||||||
return w, covariance
|
return w, covariance
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user