Search code examples
pythonarraysnumpyfinancialquantitative-finance

A python script that returns expected returns, covariance and volatility of 2 assets


Inspired by my excel finance class test, I want to use Python as a tool to solve this problem. test

I want to learn how to calculate for expected returns, co variance and volatility of assets, especially with the inclusion of probability of events.

Expected return (ERi) = 𝛴 Prob(i) * Returns(i)

Here is my current WIP code plan in an attempt to solve this problem:

import numpy as np
import pandas as pd

p = np.array([0.25, 0.5, 0.25])
r1 = np.array([0.05, 0.075, 0.1])
r2 = np.array([0.2, 0.15, 0.1])

er1 = <<need help returning a single float as expected return of asset 1>>
er2 = <<need help returning a single float as expected return of asset 2>>

portfolio = pd.DataFrame([er1, er2])

weights = np.array([0.5, 0.5])
returns_portfolio = np.dot(weights, portfolio)

cov_matrix = <<need help returning the covariance matrix for the assests>>

portfolio_volatility = <<need help returning the std of returns of the two assets>>

I have stored the probabilities of events and returns of each asset is said events as numpy arrays. The confusion for me in python is the inclusion of the probabilities and associating returns.

Just like the formula states, I want to return a sum of the probability of event(i)* return on event(i) for each separate asset

With the values of the expected returns for each asset, I plan on creating a returns array to store these values:

returns = pd.DataFrame([er1, er2])

I hope to use np.dot(weights, portfolio) to get the returns of a portfolio made equally weighted of the two assets.

I also need direction with how to implement the .cov method and .std method to get the co-variance matrix and volatility of the portfolio.

Any tips also warmly welcomed.


Solution

  • It seems extremely simple using only array multiplication and numpy built in functions such as dot, var or std:

    er1 = (p * r1).sum()
    

    Why would portfolio or returns be a DataFrame and not a np.array? Just use np.array([er1, er2])

    Then use np.std(returns) or returns.std()