, , , , , , , ,

[SOLVED] MATH6017 Practical and Numerical Computation on Financial Portfolio Optimization Using P

$25

File Name: MATH6017_Practical_and_Numerical_Computation_on_Financial_Portfolio_Optimization_Using_P.zip
File Size: 828.96 KB

5/5 - (1 vote)

Practical and Numerical Computation on Financial Portfolio Optimization Using Python

1 Lesson Objectives

By the end of this lesson, students should be able to:

•  Understand the fundamentals of financial portfolio optimization.

Implement portfolio optimization techniques using Python.

•  Apply numerical methods to compute the minimum variance portfolio (MVP), mean-variance optimization (MVO), and constrained portfolios.

•  Use Python libraries such as NumPy,  Pandas,  SciPy,  and  CVXPY for optimization.

2 Introduction to Portfolio Optimization

2.1 What is Portfolio Optimization?

Portfolio optimization is the process of selecting the best portfolio (asset alloca- tion) according to an objective, typically maximizing returns while minimizing risk. Investors aim to balance risk and return based on their preferences.

2.2 Key Concepts

Expected  Return (μ):  The weighted  average  of asset returns, repre- senting the expected profit from a portfolio:

Risk (Variance & Standard Deviation): Measures portfolio volatility and uncertainty:

Covariance & Correlation: Measures how assets move relative to each other:

Sharpe Ratio: Return-to-risk ratio used for optimal portfolio selection:

Efficient Frontier:  The set of portfolios that provides the highest ex- pected return for a given level of risk.

2.3    Types of Portfolio Optimization

1. Minimum  Variance Portfolio  (MVP):  Minimizes portfolio risk by choosing weights that result in the lowest possible variance.

2. Mean-Variance Optimization (MVO): Maximizes return for a given risk level, following Markowitz’s modern portfolio theory.

3. Constrained Portfolio Optimization:  Introduces constraints such as no short-selling, maximum investment limits, or risk bounds.

3    Practical Example: Portfolio Optimization with Analysis

3.1    Problem Statement

Consider an investor who wants to optimize a portfolio composed of five tech- nology stocks: Apple (AAPL), Google (GOOGL), Microsoft (MSFT), Amazon (AMZN), and Tesla (TSLA). The objective is to construct an efficient portfolio by minimizing risk while achieving a target return.

3.2 Step 1: Data Collection and Preprocessing

We first fetch historical stock prices and compute daily returns:

import yfinance   as   yf

import numpy  as  np

import pandas   as  pd

stocks  =   [ ’AAPL’ ,   ’GOOGL’ ,   ’MSFT’ ,   ’AMZN’ ,   ’TSLA’ ]

data  =  yf . download ( stocks ,   start=’2020−01−01 ’ ,   end=’2023−01−01 ’ ) [ ’Adj – Close ’ ]

returns  =  data . pct change ( ) . dropna ()

mean returns  =  returns . mean()

cov matrix  =  returns . cov ()

3.3    Step 2:  Minimum Variance Portfolio Optimization

Using quadratic programming, we find the portfolio that minimizes risk:

def min variance portfolio ( cov matrix ) :

num assets  = len ( cov matrix )

w =  cp . Variable ( num assets )

objective  =  cp . Minimize ( cp . quad form. (w,   cov matrix ))

constraints  =  [ cp . sum(w)  ==  1 ,  w >=  0]

prob  =  cp . Problem( objective ,   constraints )

prob . solve ()

return w. value

mvp weights  =  min variance portfolio ( cov matrix )

print (”Minimum – Variance – Portfolio – Weights : ” ,   mvp weights )

3.4 Step 3: Portfolio Performance Analysis

To evaluate the portfolio, we compute the expected return and risk:

def portfolio performance ( weights ,   mean returns ,   cov matrix ) :

port return  =  np . dot ( weights ,   mean returns )

port volatility  =  np . sqrt (np . dot ( weights .T,  np . dot ( cov matrix ,   weights )))

return port return ,   port volatility

mvp return ,   mvp vol  =  portfolio performance ( mvp weights ,   mean returns , cov matrix )

print ( f ”MVP – Expected Return : – {mvp return : . 4 f } , –MVP – Risk : – {mvp vol : . 4 f }”)

3.5    Analysis and Interpretation

From the results:

•  The Minimum Variance Portfolio (MVP) provides the lowest risk but may not offer the highest return.

•  The Efficient Frontier shows a range of optimal portfolios balancing risk and return.

Investors can select portfolios based on their risk tolerance.

4    Working with a fixed dataset

Today, we will work with a fixed dataset and roundly generated data due to the rate limit on YahooFinance.

Consider that you are working for a firm that manages 5 assets given in the dataset asset returns .xlsx.

5 Conclusion

•  The efficient frontier provides valuable insights into optimal asset allo- cation.

•  Portfolio optimization techniques can be extended to factor investing, risk parity, and machine learning-based asset selection.

•  Future work could involve dynamic  rebalancing  and  robust  opti- mization models to handle market changes.

1. Importing Libraries

The following Python libraries are imported:

NumPy: For numerical operations such as matrix multiplication.

Pandas: For handling datasets.

Matplotlib: For plotting the efficient frontier.

SciPy: For portfolio optimization using the minimize function.

Listing 1: Importing Required Libraries

import numpy  as  np import pandas   as  pd

import matplotlib . pyplot   as   plt

from scipy . optimize import minimize

2. Loading Dataset

The asset returns dataset is loaded from an Excel file:

Listing 2: Loading Asset Returns Dataset

file path  =  ”/mnt/data/ asset returns . xlsx ”

returns df  =  pd . read excel ( file path )

3. Calculating Key Metrics

We calculate the mean returns and the covariance matrix:

mean returns  =  returns df . mean()

cov matrix  =  returns df . cov ()

num assets  =  len ( mean returns )

4. Defining Portfolio Variance Function

def   portfolio variance ( weights ,   cov matrix ) :

return  np . dot ( weights .T,   np . dot ( cov matrix ,   weights ))

5. Defining Constraints and Bounds

The optimization problem has the following constraints:

The sum of portfolio weights must equal 1:

•  Each weight must be between 0 and 1 (no short selling):

constraints  =  ({ ’ type ’ :    ’eq ’ ,    ’ fun ’ :   lambda  weights :   np . sum( weights )  −  1}) bounds  =  tuple ((0 ,   1)   for   asset   in   range ( num assets ))

init guess  =  np . ones ( num assets )   /  num assets

6. Portfolio Optimization

The optimization problem minimizes the portfolio variance using the Sequential Least Squares Programming (SLSQP) method:

subject to:

opt results  =  minimize ( portfolio variance  ,   init guess  ,   args=(cov matrix ,) ,

method=’SLSQP’ ,   bounds=bounds ,   constraints=constraints )

7. Extracting Optimization Results

The optimal weights, return, and risk of the minimum variance portfolio are extracted:

min var weights  =  opt results . x

min var return  =  np . dot ( min var weights ,   mean returns )

min var risk  =  np . sqrt ( opt results . fun )

8. Efficient Frontier Simulation

We generate 5000 random portfolios to plot the efficient frontier. For each portfolio:

Portfolio return:

Portfolio risk (standard deviation):

Sharpe ratio:

num portfolios  =  5000

results  =  np . zeros ((3 ,   num portfolios ))

for   i   in   range ( num portfolios ) :

weights  =  np . random . random( num assets ) weights  /=  np . sum( weights )

port return  =  np . dot ( weights ,   mean returns )

port risk  =  np . sqrt (np . dot ( weights .T,   np . dot ( cov matrix ,   weights )))

results [0 ,   i ]  =  port risk

results [1 ,   i ]  =  port return

results [2 ,   i ]  =  port return   /   port risk

9. Plotting the Efficient Frontier

We visualize the efficient frontier along with the minimum variance portfolio.

plt . figure ( fig size =(10,   6))

plt . scatter ( results [0 ,   : ] ,   results [1 ,   : ] ,   c=results [2 ,   : ] ,   cmap=’ viridis  ’ ,

alpha =0.7)

plt . colorbar ( label=”Sharpe   Ratio ”)

plt . scatter ( min var risk ,   min var return ,   color =’red ’ ,   marker= ’ * ’ ,

s=200,   label=”Minimum  Variance   Portfolio ”) plt . title (” Efficient   Frontier ”)

plt . xlabel (” Risk   ( Standard   Deviation )”) plt . ylabel (” Return ”)

plt . legend () plt . grid ()

plt . show ()

10. Displaying Results

Finally, the optimal portfolio details are displayed:

Listing 3: Displaying Results print (”Minimum– Variance – Portfolio : ”)

print ( f ”Risk : – { min var risk : . 4 f }”)

print ( f ”Return : – {min var return : . 4 f }”) print ( f ”Weights : – {min var weights}”)

Conclusion

This approach identifies the optimal portfolio that minimizes risk while main- taining the desired level of return.  The efficient frontier represents the set of portfolios that offer the best possible return for a given level of risk.

Shopping Cart

No products in the cart.

No products in the cart.

[SOLVED] MATH6017 Practical and Numerical Computation on Financial Portfolio Optimization Using P
$25