Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Propagate missing values in Stats.cov from Stats.stdDev. #552

Merged
merged 1 commit into from
Nov 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Deedle.Math/Stats.fs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ type Stats =
static member covMatrix (df:Frame<'R, 'C>) =
// Treat nan as zero, the same as MATLAB
let corr = Stats.corrMatrix(df) |> Matrix.map(fun x -> if Double.IsNaN x then 0. else x)
let stdev = df |> Stats.stdDev |> Series.values |> Array.ofSeq
let stdev = df |> Stats.stdDev |> Series.valuesAll |> Seq.map (Option.defaultValue nan) |> Array.ofSeq
let stdevDiag = DenseMatrix.ofDiagArray stdev
stdevDiag * corr * stdevDiag

Expand Down
19 changes: 19 additions & 0 deletions tests/Deedle.Math.Tests/Stats.fs
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,22 @@ let ``cov2Corr and corr2Cov work`` () =
let actual = Stats.corr2Cov(std, corr).GetColumnAt<float>(0).GetAt(0)
let expected = cov.GetColumnAt<float>(0).GetAt(0)
actual |> should beWithin (expected +/- 1e-6)

[<Test>]
let ``cov propogates missing values when stddev produces missing values`` () =
let returns =
Frame.ofColumns [ "A"
=> series [ DateTime(2022, 11, 1) => 0.
DateTime(2022, 11, 2) => 0. ]
"B" => series [ DateTime(2022, 11, 1) => 0. ] ]

let cov = returns |> Stats.cov

let expected =
Frame.ofRowKeys [ "A"; "B" ]
|> Frame.addCol "A" (series [ "A" => 0. ])
|> Frame.addCol "B" (series [])

cov
|> Frame.toMatrix
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to just write this as cov |> shouldEqual expected but something was throwing the equality check off. I would guess some reference equality somewhere. Should shouldEqual work for two frames with the same contents? I'd like to write it as an equality on the frames if possible as that's a more correct assertion.

|> shouldEqual (expected |> Frame.toMatrix)