Real numbers and vectors

 

Have you ever wondered how real numbers and vectors are used in finance?

They play a really important role, especially in quantitative finance.

This is where they're used for modeling, portfolio optimisation and risk management.

We've put together some Python examples below to show you how real numbers and

vectors can be applied in a financial context.

In our article we will try to answer:

  • What are real numbers and vectors?

  • Where to find them in python?

  • Why do we need them in finance?


Let's start from the beginning. 


Real numbers are all numbers from the real world except complex numbers.

If we want to denoted the set of all real numbers we use

In Python we use the float or int data types.


# Real numbers 

rn_1 = 3.14 # float 

rn_2 = -5 # int 

rn_3 = 2.718 # float 


# Operations with real numbers 

sum_result = rn_1 + rn_2 

product_result = rn_2 * rn_3 


print("Sum:", sum_result) 

print("Product:", product_result)


Sum: -1.8599999999999999

Product: -13.59


In Finance we use real numbers to represent such financial quantities as

interest rates, returns, and prices .


Example of Simple Interest Calculation

# Simple Interest Calculation 

p = 1000.0 # Principal amount in dollars 

r = 5.0 / 100 # Annual interest rate as a decimal 

t = 3 # Time in years 


# Calculate simple interest 

simple_interest = p * r * t

print("Simple Interest:", simple_interest)

Simple Interest: 150.0

Example of Compound Interest Calculation 


# Compound Interest Calculation 

p = 1000.0 # Principal amount in dollars 

r = 5.0 / 100 # Annual interest rate as a decimal 

t = 3 # Time in years 

c_per_year = 4 # Quarterly compounding 


# Calculate compound interest 

amount = p * (1 + r / c_per_year) ** (c_per_year * t) 

c_interest = amount - p

print("Compound Interest:", c_interest)

Compound Interest: 160.75451772299812


Vectors are finite collections of real numbers which can be represented

in different forms.  There are 2 types of vectors: row and column vectors.


A row vector is represented as a horizontal list of numbers v = [v₁ v₂ ... vₙ].

For row vectors  we can use lists or NumPy arrays in Python.


NumPy is an open source project that enables numerical computing with Python. 


import numpy as np


# Row vector

row_vector = np.array([1, 2, 3, 4])

print("Row Vector:", row_vector)


# Operations on row vectors

# Scalar multiplication

scalar_mult = 2 * row_vector

print("Scalar Multiplication:", scalar_mult)


# Addition with another vector

another_vector = np.array([4, 3, 2, 1])

vector_sum = row_vector + another_vector

print("Vector Sum:", vector_sum)

Compound Interest: 160.75451772299812


A column vector is a vertical list of numbers

By default, vectors are considered column vectors unless otherwise specified. 


In Python column vectors can be represented as 2D NumPy arrays with a

single column.


# Column vector

column_vector = np.array([[1], [2], [3], [4]])

print("Column Vector:\n", column_vector)


# Transpose (converts to a row vector)

transpose_vector = column_vector.T

print("Transposed Vector:\n", transpose_vector)


# Dot product with another column vector

another_column_vector = np.array([[4], [3], [2], [1]])

dot_product = np.dot(column_vector.T, another_column_vector)

print("Dot Product:", dot_product)

Column Vector:

 [[1]

 [2]

 [3]

 [4]]

Transposed Vector:

 [[1 2 3 4]]

Dot Product: [[20]]

Very often it will be needed to transpose your matrices / vectors. NumPy arrays

have the properties T, .transpose(), .reshape().

To learn more about transposing and reshaping arrays, see transpose and reshape.

The dot product is a really handy method for multiplying a row and column vector

and getting the result.

The set of all vectors with n components is denoted by  

- each component of the vector is a real number, and the vector has 𝑛 dimensions.  

In Python, the numpy library allows for the creation and manipulation of vectors of
any dimension 𝑛.

# Creating a vector in R^4 (4-dimensional vector) 

vector_in_R4 = np.array([1.0, 2.0, 3.0, 4.0]) 

print("Vector in R^4:", vector_in_R4

# Length (magnitude) of the vector magnitude = np.linalg.norm(vector_in_R4) 

print("Magnitude of Vector:", magnitude)

Vector in R^4: [1. 2. 3. 4.]

Magnitude of Vector: 5.477225575051661


numpy.linalg.norm is used to calculate the norm of a vector or a matrix or able to return one of matrix norms.


Vectors are a great way to represent portfolios! Each element of the vector

represents the value of a specific asset or the weight of an asset in a portfolio.

Portfolio weight is the % of asset value to the total portfolio value and can be

calculated by dividing the dollar value of an asset by the total dollar value

of the portfolio.


Portfolio Returns

Let's assume you have a portfolio consisting of different assets. The portfolio

return can be calculated using vectors.


import numpy as np


# Asset returns

a_returns = np.array([0.05, 0.10, 0.02])  # Returns for three assets


# Portfolio weights (summing to 1)

p_weights = np.array([0.4, 0.4, 0.2])


# Calculate portfolio return

p_return = np.dot(p_weights, a_returns)

print("Portfolio Return:", p_return)

Portfolio Return: 0.06400000000000002


The portfolio return of approximately 0.064 means that the weighted average
return of the assets in your portfolio is 6.4%. This result suggests that if you
invested according to the specified weights in the assets with the given returns,
your portfolio would yield a return of 6.4% on average.

Portfolio Variance (Risk)

Portfolio variance is a fantastic way to measure risk! And you can even calculate

it using vectors and matrices!


# Covariance matrix (3x3 matrix for 3 assets)

cov_matrix = np.array([

    [0.1, 0.02, 0.04],

    [0.02, 0.15, 0.03],

    [0.04, 0.03, 0.2]

])


# Portfolio variance (risk)

p_variance = np.dot(portfolio_weights.T, np.dot(cov_matrix, p_weights))

print("Portfolio Variance (Risk):", p_variance)

Portfolio Variance (Risk): 0.0656

The portfolio variance of 0.0656 shows the level of risk in the portfolio's

return, including the risks of each asset and how they affect each other.

A higher variance means a higher level of risk, as the returns are more spread out. 

The risk is about 25.6% if you express it as a standard deviation 0.0656 = 0.256.

This is a more intuitive measure of portfolio risk.

Portfolio variance shows how returns are expected to vary. Managing this risk

is an important part of portfolio management. It is often done to achieve

the right balance between risk and returns.


Capital Asset Pricing Model (CAPM) 

The CAPM model is an amazing tool that helps us determine the expected return

on an asset. It uses vectors to represent the market portfolio and the asset's

sensitivity (beta) to the market, which is really useful!


# Example: CAPM formula

r_f_rate = 0.03  # Risk-free rate of return

m_return = 0.08   # Expected market return

b = 1.2             # Beta of the asset


# Expected return using CAPM

e_return = r_f_rate + b * (m_return - r_f_rate)

print("Expected Return (CAPM):", e_return)

Expected Return (CAPM): 0.09

This is the expected return based on the asset's risk level and the market

return. It includes the risk-free return and the additional return needed to

compensate for the asset's higher risk.

A beta greater than 1 means the asset is more volatile than the market. The

expected return of 9% includes the risk-free rate and an additional premium

due to the asset's higher risk.


Portfolio theory uses vectors to show the returns of different assets and

how they affect each other. Here's an example of a portfolio of assets.


Monte Carlo Simulation for Portfolio Returns


import numpy as np


# Simulate asset returns (e.g., 1000 scenarios for 3 assets)

s_returns = np.random.normal(0.05, 0.1, (1000, 3))  # mean=0.05, std=0.1


# Portfolio weights

weights = np.array([0.4, 0.4, 0.2])


# Portfolio returns for each scenario

p_returns = np.dot(s_returns, weights)


# Calculate expected return and standard deviation (risk) of the portfolio

e_p_return = np.mean(p_returns)

p_risk = np.std(p_returns)


print("Expected Portfolio Return:", e_p_return)

print("Portfolio Risk (Standard Deviation):", p_risk)

Expected Portfolio Return: 0.04997984394141561

Portfolio Risk (Standard Deviation): 0.058258217004745844

Expected Return 4.998% is what you expect to earn on your portfolio. It's the

return you're likely to receive if the assets perform as expected. A risk

of 5.826% indicates how much the returns are expected to deviate from the

expected return. Investors seek to balance this risk against the expected

return to achieve a desirable risk-return trade-off.

If you are risk-averse, you may wish to consider a portfolio with a lower

standard deviation, even if it means accepting a lower expected return.


Summary

  • In financial contexts, real numbers are used to represent key financial quantities such as interest rates, returns and prices.

  • Vectors are a means of representing collections of financial data, such as the returns of multiple assets in a portfolio.

  • Vector operations, including dot products and matrix multiplications, are employed to calculate portfolio returns, risk (variance), and to apply financial models such as CAPM.

References:

  1. "Financial Engineering and Risk Management". Coursera, www.coursera.org/specializations/financialengineering. Last accessed 24 Aug. 2024.

  2. "NumPy documentation — NumPy v2.1 Manual". NumPy -, numpy.org/doc/stable. Last accessed 24 Aug 2024.

  3. "WQU | Master of Science in Financial Engineering · WQU". WQU | A Leader in Global Education · WQU, www.wqu.edu/mscfe?utm_term=worldquant%20university&utm_campaign=GA_MScFE_SEA_GKW+BKW_WW&utm_source=adwords&utm_medium=ppc&hsa_acc=1450481729&hsa_cam=18879661171&hsa_grp=142652472959&hsa_ad=634265330876&hsa_src=g&hsa_tgt=kwd-365833978550&hsa_kw=worldquant%20university&hsa_mt=b&hsa_net=adwords&hsa_ver=3&gad_source=1&gclid=CjwKCAjwiaa2BhAiEiwAQBgyHk5oR6aQvbAQDkK_znzHUT5523KyleBQZJW2wiqJB_x6reoBOECdGRoCPIsQAvD_BwE. Last accessed 24 Aug 2024.

Коментарі

Популярні дописи з цього блогу

Basis

Learn how to build games with HTML

Four Stances of Zhan Zhuang