Compute pairwise covariance of columns in a DataFrame or between Series using the Pandas cov() method. Evaluate joint variability, measure directional relationships across financial asset returns, and configure sample size thresholds.
cov() method calculates sample covariance between numerical columns, excluding missing values by default. Unlike correlation, covariance retains the scale of the original variables, where positive values indicate variables move together and negative values indicate opposite movement.import pandas as pd
df = pd.DataFrame({
"ASSET_A": [10, 20, 30, 40, 50],
"ASSET_B": [12, 24, 33, 45, 57],
"VOLUME": [100, 150, 130, 180, 200]
})
print(df)
assert df.shape == (5, 3)
Expected output
ASSET_A ASSET_B VOLUME
0 10 12 100
1 20 24 150
2 30 33 130
3 40 45 180
4 50 57 200
cov() on the DataFrame to calculate the pairwise covariance matrix across numerical columns.cov_matrix = df.cov()
print(cov_matrix)
assert cov_matrix.loc["ASSET_A", "ASSET_B"] == 277.5
Expected output
ASSET_A ASSET_B VOLUME
ASSET_A 250.0 277.5 550.0
ASSET_B 277.5 310.5 605.0
VOLUME 550.0 605.0 1470.0
cov() directly on a Series, passing another Series as the argument to evaluate their pairwise covariance scalar value.s_cov = df["ASSET_A"].cov(df["ASSET_B"])
print(f"Covariance: {s_cov}")
assert s_cov == 277.5
Expected output
Covariance: 277.5
ret_x = pd.Series([1, 2, 3, 4, 5]) and ret_y = pd.Series([5, 4, 3, 2, 1]), compute their covariance and verify that the resulting value equals -2.5.cov().ret_x = pd.Series([1, 2, 3, 4, 5])
ret_y = pd.Series([5, 4, 3, 2, 1])
answer = ret_x.cov(ret_y)
print(answer)
assert answer == -2.5
Expected output
-2.5
Practice cov() examples interactively directly in your browser:
Reference: Pandas cov() documentation.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.