import numpy as np
import pandas as pd

x = list(range(-10, 11)) #[-10, -9, ..., 10, 11]
y = [0, 2, 2, 2, 2, 3, 3, 6, 7, 4, 7, 6, 6, 9, 4, 5, 5, 10, 11, 12, 14]
x_, y_ = np.array(x), np.array(y)
x__, y__ = pd.Series(x_), pd.Series(y_)

################### Covariance using pure python ###########
n = len(x)
mean_x, mean_y = sum(x) / n, sum(y) / n
cov_xy = (sum((x[k] - mean_x) * (y[k] - mean_y) for k in range(n))/ (n - 1))

print("Covariance using pure python: ",cov_xy)

################### numpy.cov() ############################
cov_matrix = np.cov(x_, y_)
print("covariance matrix by numpy.cov(): \n",cov_matrix)
#[var(x)    cov(x,y)]
#[cov(y,x)   var(y) ]

print("variance of x: ",x_.var(ddof=1))
print("variance of y: ",y_.var(ddof=1))

cov_xy = cov_matrix[0, 1]
print("Covariance of x,y using numpy: ",cov_xy)

cov_yx = cov_matrix[1, 0]
print("Covariance of y,x using numpy: ",cov_yx)


################## using pandas series function #############
cov_xy = x__.cov(y__)
print("Covariance of x,y using pandas series function: ",cov_xy)

cov_xy = y__.cov(x__)
print("Covariance of y,x using pandas series function: ",cov_xy)