python covariance matrix

Table of Contents

				
					import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
				
			

Example 1 Manual

				
					stock_a = [100, 102, 104, 103, 105]
stock_b = [200, 198, 202, 204, 206]
				
			
				
					n = len(stock_a)
				
			
				
					# Step 1: Calculate the means of stock_a and stock_b
mean_a = sum(stock_a) / n
mean_b = sum(stock_b) / n
				
			
				
					# Step 2: Calculate the differences from the means and their products
diff_product_sum = 0
				
			
				
					for i in range(n):
        diff_a = stock_a[i] - mean_a
        diff_b = stock_b[i] - mean_b
        diff_product_sum += diff_a * diff_b
				
			
				
					# Step 3: Calculate the covariance
covariance = diff_product_sum / n
				
			
				
					print(covariance)
				
			
#The positive value of 3.6 indicates that the prices of Stock A and Stock B tend to move in the same
#direction. When the price of Stock A increases, the price of Stock B also tends to increase,
#and vice versa.

Example 2 Numpy Sample Covariance

				
					X = [2.1, 2.5, 3.6, 4.0]
Y = [8, 10, 12, 14]
				
			
				
					cov_matrix = np.cov(X, Y)
print("Covariance matrix:\n", cov_matrix)
				
			
				
					cov_xy = cov_matrix[0, 1]
print("Covariance between X and Y:", cov_xy)
				
			

Example 4 Pandas Sample - No Option

				
					data = {'X': [2.1, 2.5, 3.6, 4.0],
        'Y': [8, 10, 12, 14]}
				
			
				
					df = pd.DataFrame(data)
				
			
				
					cov_df = df.cov()
				
			
				
					print("Covariance DataFrame:\n", cov_df)
				
			
				
					cov_xy = cov_df.loc['X', 'Y']
				
			
				
					print("Covariance between X and Y:", cov_xy)
				
			

Example 5 Plot Covariance Matrix

				
					# Plot the covariance matrix as a heatmap
plt.figure(figsize=(8, 6))
sns.heatmap(cov_matrix, annot=True, cmap='coolwarm', fmt='.2f')
plt.title('Covariance Matrix')
plt.show()
				
			
				
					plt.scatter(X, Y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Scatter plot of X vs Y')
plt.show()
				
			

Free Community

Join 1,000+ AI Automation Builders

Weekly tutorials, live calls & direct access to Ryan & Matt.

Join Free →

Keep Learning

python quantiles statistics

In Python, a quantile is a statistical term used to describe a point or value below which a certain proportion of the...

python variance and standard deviation

https://youtu.be/p4H2b2x_nWc#population and sample variance/std deviationVariance measures how far each data point in the set is from the mean andthus from every other...

Python Z-Score

We are going to be looking at Python Z-score. Z-score tells us how far a data poin is from the mean. https://youtu.be/QjG1ljFNF9U...

Spearman Rank Correlation

Spearman Rank Correlation [Simply explained] https://youtu.be/TNQTd9gR1c0 Example 2 Fast wth scipy