Module 11 · Financial Risk and Performance Statistics Lesson 110 of 120
Covariance Matrices, Portfolio Variance, and Diversification
Why two individually quiet holdings can become a risky combination.
Transcript
19 sentences · select one to jump thereCheck your understanding
What changed between the two portfolio calculations?
Code lab
Run it yourself
The lesson source in 7 languages. Edit it, run TypeScript and Python right here, and compare with the expected output.
/**
* Fintech Math Bootcamp · Lesson 110 of 120
* Covariance Matrices, Portfolio Variance, and Diversification
* Module 11: Financial Risk and Performance Statistics
*
* Scenario: Why two individually quiet holdings can become a risky combination
* Rule: portfolio variance = wᵀΣw
*
* Try it: What changed between the two portfolio calculations?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-risk-and-performance-statistics/covariance-matrices-portfolio-variance-and-diversification/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*/
export function lesson110() {
const w=[.5,.5],vol=[.01,.01];
const variance=(rho:number)=>{ // w' Σ w
const cov=[[vol[0]**2,rho*vol[0]*vol[1]],[rho*vol[0]*vol[1],vol[1]**2]];
return w.reduce((s,wi,i)=>s+wi*w.reduce((t,wj,j)=>t+cov[i][j]*wj,0),0);};
const result={atMinusHalf:variance(-.5),atPointNine:variance(.9),
dollarSDLow:100000*Math.sqrt(variance(-.5)),
dollarSDHigh:100000*Math.sqrt(variance(.9))};
return result;
}
export const checkedResult = {"atMinusHalf":0.000025,"atPointNine":0.000095,"dollarSDLow":500,"dollarSDHigh":974.6794344808964};
// Run this file directly: npx tsx lessons/11-financial-risk-and-performance-statistics/110-covariance-matrices-portfolio-variance-and-diversification.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
console.log(JSON.stringify(lesson110(), null, 2));
}
Your output
Press Run to execute the code in your browser.
Expected output
{
"atMinusHalf": 0.000025,
"atPointNine": 0.000095,
"dollarSDLow": 500,
"dollarSDHigh": 974.6794344808964
}# Fintech Math Bootcamp · Lesson 110 of 120
# Covariance Matrices, Portfolio Variance, and Diversification
# Module 11: Financial Risk and Performance Statistics
#
# Scenario: Why two individually quiet holdings can become a risky combination
# Rule: portfolio variance = wᵀΣw
#
# Try it: What changed between the two portfolio calculations?
#
# Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-risk-and-performance-statistics/covariance-matrices-portfolio-variance-and-diversification/
# Free course: https://courses.thefintechbuilder.com
# Synthetic teaching example, not financial advice or a production library.
#
# Run: python main.py
import json
import math
def lesson_110():
w, vol = [0.5, 0.5], [0.01, 0.01]
def variance(rho): # w' Sigma w
cov = [[vol[0] ** 2, rho * vol[0] * vol[1]], [rho * vol[0] * vol[1], vol[1] ** 2]]
total = 0.0
for i, wi in enumerate(w):
inner = 0.0
for j, wj in enumerate(w):
inner += cov[i][j] * wj
total += wi * inner
return total
return {
"atMinusHalf": variance(-0.5),
"atPointNine": variance(0.9),
"dollarSDLow": 100000 * math.sqrt(variance(-0.5)),
"dollarSDHigh": 100000 * math.sqrt(variance(0.9)),
}
if __name__ == "__main__":
print(json.dumps(lesson_110(), indent=2))
Your output
Press Run to execute the code in your browser.
Expected output
{
"atMinusHalf": 0.000025,
"atPointNine": 0.000095,
"dollarSDLow": 500,
"dollarSDHigh": 974.6794344808964
}/*
* Fintech Math Bootcamp - Lesson 110 of 120
* Covariance Matrices, Portfolio Variance, and Diversification
* Module 11: Financial Risk and Performance Statistics
*
* Scenario: Why two individually quiet holdings can become a risky combination
* Rule: portfolio variance = w^T Sigma w
*
* Try it: What changed between the two portfolio calculations?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-risk-and-performance-statistics/covariance-matrices-portfolio-variance-and-diversification/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*
* Run: javac Main.java && java Main
*/
import java.util.*;
public class Main {
static final double[] W = {.5, .5};
static final double[] VOL = {.01, .01};
// w' Sigma w
static double variance(double rho) {
double[][] cov = {
{Math.pow(VOL[0], 2), rho * VOL[0] * VOL[1]},
{rho * VOL[0] * VOL[1], Math.pow(VOL[1], 2)}
};
double total = 0;
for (int i = 0; i < W.length; i++) {
double inner = 0;
for (int j = 0; j < W.length; j++) inner += cov[i][j] * W[j];
total += W[i] * inner;
}
return total;
}
static Map<String, Object> lesson110() {
return obj("atMinusHalf", variance(-.5), "atPointNine", variance(.9),
"dollarSDLow", 100000 * Math.sqrt(variance(-.5)),
"dollarSDHigh", 100000 * Math.sqrt(variance(.9)));
}
public static void main(String[] args) {
System.out.println(toJson(lesson110(), ""));
}
// Minimal JSON writer: insertion-ordered Map, List, Number, Boolean, String and null.
static String toJson(Object value, String indent) {
if (value == null) return "null";
if (value instanceof String) return quote((String) value);
if (value instanceof Boolean) return value.toString();
if (value instanceof Double) return formatNumber((Double) value);
if (value instanceof Number) return value.toString();
String inner = indent + " ";
StringBuilder sb = new StringBuilder();
if (value instanceof Map) {
Map<?, ?> map = (Map<?, ?>) value;
if (map.isEmpty()) return "{}";
sb.append("{\n");
int i = 0;
for (Map.Entry<?, ?> e : map.entrySet()) {
sb.append(inner).append(quote(e.getKey().toString())).append(": ").append(toJson(e.getValue(), inner));
sb.append(++i < map.size() ? ",\n" : "\n");
}
return sb.append(indent).append("}").toString();
}
List<?> list = (List<?>) value;
if (list.isEmpty()) return "[]";
sb.append("[\n");
for (int i = 0; i < list.size(); i++) {
sb.append(inner).append(toJson(list.get(i), inner)).append(i + 1 < list.size() ? ",\n" : "\n");
}
return sb.append(indent).append("]").toString();
}
// Integral doubles print without ".0", as JavaScript does; others use Java's round-trip form.
static String formatNumber(double x) {
if (x == Math.rint(x) && Math.abs(x) < 1e15) return Long.toString((long) x);
return Double.toString(x);
}
static String quote(String s) {
StringBuilder sb = new StringBuilder("\"");
for (char c : s.toCharArray()) {
if (c == '"' || c == '\\') sb.append('\\').append(c);
else if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
else sb.append(c);
}
return sb.append('"').toString();
}
// Builds an insertion-ordered object from alternating keys and values.
static Map<String, Object> obj(Object... keysAndValues) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
for (int i = 0; i < keysAndValues.length; i += 2) map.put((String) keysAndValues[i], keysAndValues[i + 1]);
return map;
}
static List<Object> list(double... values) {
List<Object> out = new ArrayList<Object>();
for (double v : values) out.add(v);
return out;
}
}
No browser runner for Java yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"atMinusHalf": 0.000025,
"atPointNine": 0.000095,
"dollarSDLow": 500,
"dollarSDHigh": 974.6794344808964
}// Fintech Math Bootcamp · Lesson 110 of 120
// Covariance Matrices, Portfolio Variance, and Diversification
// Module 11: Financial Risk and Performance Statistics
//
// Scenario: Why two individually quiet holdings can become a risky combination
// Rule: portfolio variance = wᵀΣw
//
// Try it: What changed between the two portfolio calculations?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-risk-and-performance-statistics/covariance-matrices-portfolio-variance-and-diversification/
// Free course: https://courses.thefintechbuilder.com
// Synthetic teaching example, not financial advice or a production library.
//
// Run: go run main.go
package main
import (
"encoding/json"
"fmt"
"math"
)
type Result struct {
AtMinusHalf float64 `json:"atMinusHalf"`
AtPointNine float64 `json:"atPointNine"`
DollarSDLow float64 `json:"dollarSDLow"`
DollarSDHigh float64 `json:"dollarSDHigh"`
}
func lesson110() Result {
w, vol := []float64{.5, .5}, []float64{.01, .01}
variance := func(rho float64) float64 { // w' Sigma w
cov := [2][2]float64{
{math.Pow(vol[0], 2), rho * vol[0] * vol[1]},
{rho * vol[0] * vol[1], math.Pow(vol[1], 2)},
}
total := 0.0
for i, wi := range w {
inner := 0.0
for j, wj := range w {
inner += cov[i][j] * wj
}
total += wi * inner
}
return total
}
return Result{
AtMinusHalf: variance(-.5),
AtPointNine: variance(.9),
DollarSDLow: 100000 * math.Sqrt(variance(-.5)),
DollarSDHigh: 100000 * math.Sqrt(variance(.9)),
}
}
func main() {
out, err := json.MarshalIndent(lesson110(), "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(out))
}
No browser runner for Go yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"atMinusHalf": 0.000025,
"atPointNine": 0.000095,
"dollarSDLow": 500,
"dollarSDHigh": 974.6794344808964
}// Fintech Math Bootcamp · Lesson 110 of 120
// Covariance Matrices, Portfolio Variance, and Diversification
// Module 11: Financial Risk and Performance Statistics
//
// Scenario: Why two individually quiet holdings can become a risky combination
// Rule: portfolio variance = wᵀΣw
//
// Try it: What changed between the two portfolio calculations?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-risk-and-performance-statistics/covariance-matrices-portfolio-variance-and-diversification/
// Free course: https://courses.thefintechbuilder.com
// Synthetic teaching example, not financial advice or a production library.
//
// Run: g++ -std=c++17 -O1 -o lesson main.cpp && ./lesson
#include <algorithm>
#include <charconv>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <deque>
#include <iostream>
#include <limits>
#include <map>
#include <optional>
#include <stdexcept>
#include <string>
#include <utility>
#include <variant>
#include <vector>
// Minimal JSON value: objects keep insertion order; numbers print in shortest round-trip form.
struct Json {
enum class Kind { Null, Bool, Number, String, Array, Object };
Kind kind = Kind::Null;
bool flag = false;
double number = 0.0;
std::string text;
std::vector<std::string> keys; // object keys, parallel to items
std::vector<Json> items; // array items, or object values
};
Json jnull() { return Json{}; }
Json jbool(bool value) { Json j; j.kind = Json::Kind::Bool; j.flag = value; return j; }
Json jnum(double value) { Json j; j.kind = Json::Kind::Number; j.number = value; return j; }
Json jstr(const std::string& value) { Json j; j.kind = Json::Kind::String; j.text = value; return j; }
Json jarr(std::vector<Json> items) { Json j; j.kind = Json::Kind::Array; j.items = std::move(items); return j; }
Json jobj(std::vector<std::pair<std::string, Json>> fields) {
Json j;
j.kind = Json::Kind::Object;
for (auto& field : fields) {
j.keys.push_back(field.first);
j.items.push_back(std::move(field.second));
}
return j;
}
Json jnums(const std::vector<double>& values) {
std::vector<Json> items;
for (double v : values) items.push_back(jnum(v));
return jarr(std::move(items));
}
Json jnums(const std::vector<std::optional<double>>& values) {
std::vector<Json> items;
for (const auto& v : values) items.push_back(v ? jnum(*v) : jnull());
return jarr(std::move(items));
}
std::string formatNumber(double value) {
char buffer[64];
auto result = std::to_chars(buffer, buffer + sizeof buffer, value); // shortest round-trip form
return std::string(buffer, result.ptr);
}
std::string quote(const std::string& text) {
std::string out = "\"";
for (char c : text) {
if (c == '"' || c == '\\') {
out += '\\';
out += c;
} else if (static_cast<unsigned char>(c) < 0x20) {
char buffer[8];
std::snprintf(buffer, sizeof buffer, "\\u%04x", static_cast<unsigned>(c));
out += buffer;
} else {
out += c;
}
}
return out + "\"";
}
void writeJson(std::ostream& out, const Json& value, const std::string& indent = "") {
const std::string inner = indent + " ";
switch (value.kind) {
case Json::Kind::Null: out << "null"; return;
case Json::Kind::Bool: out << (value.flag ? "true" : "false"); return;
case Json::Kind::Number: out << formatNumber(value.number); return;
case Json::Kind::String: out << quote(value.text); return;
case Json::Kind::Array:
case Json::Kind::Object: {
const bool isObject = value.kind == Json::Kind::Object;
if (value.items.empty()) {
out << (isObject ? "{}" : "[]");
return;
}
out << (isObject ? "{\n" : "[\n");
for (std::size_t i = 0; i < value.items.size(); ++i) {
out << inner;
if (isObject) out << quote(value.keys[i]) << ": ";
writeJson(out, value.items[i], inner);
out << (i + 1 < value.items.size() ? ",\n" : "\n");
}
out << indent << (isObject ? "}" : "]");
}
}
}
Json lesson110() {
const std::vector<double> w{.5, .5}, vol{.01, .01};
auto variance = [&](double rho) { // w' Sigma w
const double cov[2][2] = {{std::pow(vol[0], 2), rho * vol[0] * vol[1]},
{rho * vol[0] * vol[1], std::pow(vol[1], 2)}};
double total = 0;
for (std::size_t i = 0; i < w.size(); ++i) {
double inner = 0;
for (std::size_t j = 0; j < w.size(); ++j) inner += cov[i][j] * w[j];
total += w[i] * inner;
}
return total;
};
return jobj({{"atMinusHalf", jnum(variance(-.5))},
{"atPointNine", jnum(variance(.9))},
{"dollarSDLow", jnum(100000 * std::sqrt(variance(-.5)))},
{"dollarSDHigh", jnum(100000 * std::sqrt(variance(.9)))}});
}
int main() {
writeJson(std::cout, lesson110());
std::cout << "\n";
return 0;
}
No browser runner for C++ yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"atMinusHalf": 0.000025,
"atPointNine": 0.000095,
"dollarSDLow": 500,
"dollarSDHigh": 974.6794344808964
}// Fintech Math Bootcamp · Lesson 110 of 120
// Covariance Matrices, Portfolio Variance, and Diversification
// Module 11: Financial Risk and Performance Statistics
//
// Scenario: Why two individually quiet holdings can become a risky combination
// Rule: portfolio variance = wᵀΣw
//
// Try it: What changed between the two portfolio calculations?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-risk-and-performance-statistics/covariance-matrices-portfolio-variance-and-diversification/
// Free course: https://courses.thefintechbuilder.com
// Synthetic teaching example, not financial advice or a production library.
//
// Run: rustc -O main.rs && ./main
#![allow(dead_code)]
/// Minimal JSON value; objects keep insertion order.
enum Json {
Null,
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
fn obj(fields: Vec<(&str, Json)>) -> Json {
Json::Obj(fields.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
}
fn nums(values: &[f64]) -> Json {
Json::Arr(values.iter().map(|&v| Json::Num(v)).collect())
}
fn optional_nums(values: &[Option<f64>]) -> Json {
Json::Arr(values.iter().map(|v| v.map_or(Json::Null, Json::Num)).collect())
}
fn quote(text: &str) -> String {
let mut out = String::from("\"");
for c in text.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
// Display for f64 prints the shortest string that round-trips, as JavaScript does.
fn write_json(value: &Json, indent: &str, out: &mut String) {
let inner = format!("{} ", indent);
match value {
Json::Null => out.push_str("null"),
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Json::Num(n) => out.push_str(&format!("{}", n)),
Json::Str(s) => out.push_str("e(s)),
Json::Arr(items) if items.is_empty() => out.push_str("[]"),
Json::Obj(fields) if fields.is_empty() => out.push_str("{}"),
Json::Arr(items) => {
out.push_str("[\n");
for (i, item) in items.iter().enumerate() {
out.push_str(&inner);
write_json(item, &inner, out);
out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
}
out.push_str(indent);
out.push(']');
}
Json::Obj(fields) => {
out.push_str("{\n");
for (i, (key, item)) in fields.iter().enumerate() {
out.push_str(&inner);
out.push_str("e(key));
out.push_str(": ");
write_json(item, &inner, out);
out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
}
out.push_str(indent);
out.push('}');
}
}
}
fn lesson_110() -> Json {
let (w, vol): ([f64; 2], [f64; 2]) = ([0.5, 0.5], [0.01, 0.01]);
// w' Sigma w
let variance = |rho: f64| -> f64 {
let cov = [
[vol[0].powi(2), rho * vol[0] * vol[1]],
[rho * vol[0] * vol[1], vol[1].powi(2)],
];
w.iter().enumerate().fold(0.0, |s, (i, wi)| {
s + wi * w.iter().enumerate().fold(0.0, |t, (j, wj)| t + cov[i][j] * wj)
})
};
obj(vec![
("atMinusHalf", Json::Num(variance(-0.5))),
("atPointNine", Json::Num(variance(0.9))),
("dollarSDLow", Json::Num(100000.0 * variance(-0.5).sqrt())),
("dollarSDHigh", Json::Num(100000.0 * variance(0.9).sqrt())),
])
}
fn main() {
let mut out = String::new();
write_json(&lesson_110(), "", &mut out);
println!("{}", out);
}
No browser runner for Rust yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"atMinusHalf": 0.000025,
"atPointNine": 0.000095,
"dollarSDLow": 500,
"dollarSDHigh": 974.6794344808964
}// Fintech Math Bootcamp · Lesson 110 of 120
// Covariance Matrices, Portfolio Variance, and Diversification
// Module 11: Financial Risk and Performance Statistics
//
// Scenario: Why two individually quiet holdings can become a risky combination
// Rule: portfolio variance = wᵀΣw
//
// Try it: What changed between the two portfolio calculations?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-risk-and-performance-statistics/covariance-matrices-portfolio-variance-and-diversification/
// Free course: https://courses.thefintechbuilder.com
// Synthetic teaching example, not financial advice or a production library.
//
// Run: dotnet run
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
var options = new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
Console.WriteLine(JsonSerializer.Serialize(Lesson110(), options));
static object Lesson110()
{
double[] w = { .5, .5 }, vol = { .01, .01 };
double Variance(double rho) // w' Sigma w
{
double[,] cov =
{
{ Math.Pow(vol[0], 2), rho * vol[0] * vol[1] },
{ rho * vol[0] * vol[1], Math.Pow(vol[1], 2) },
};
double total = 0;
for (int i = 0; i < w.Length; i++)
{
double inner = 0;
for (int j = 0; j < w.Length; j++) inner += cov[i, j] * w[j];
total += w[i] * inner;
}
return total;
}
return new
{
atMinusHalf = Variance(-.5),
atPointNine = Variance(.9),
dollarSDLow = 100000 * Math.Sqrt(Variance(-.5)),
dollarSDHigh = 100000 * Math.Sqrt(Variance(.9)),
};
}
No browser runner for C# yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"atMinusHalf": 0.000025,
"atPointNine": 0.000095,
"dollarSDLow": 500,
"dollarSDHigh": 974.6794344808964
}Prefer your own machine? Every file is in the course repository · open it in Codespaces.
Lesson notes
The rule
portfolio variance = wᵀΣw