代做MATH6017 Practical and Numerical Computation on Financial Portfolio Optimization Using Python帮做Pyt

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.


热门主题

课程名

mktg2509 csci 2600 38170 lng302 csse3010 phas3226 77938 arch1162 engn4536/engn6536 acx5903 comp151101 phl245 cse12 comp9312 stat3016/6016 phas0038 comp2140 6qqmb312 xjco3011 rest0005 ematm0051 5qqmn219 lubs5062m eee8155 cege0100 eap033 artd1109 mat246 etc3430 ecmm462 mis102 inft6800 ddes9903 comp6521 comp9517 comp3331/9331 comp4337 comp6008 comp9414 bu.231.790.81 man00150m csb352h math1041 eengm4100 isys1002 08 6057cem mktg3504 mthm036 mtrx1701 mth3241 eeee3086 cmp-7038b cmp-7000a ints4010 econ2151 infs5710 fins5516 fin3309 fins5510 gsoe9340 math2007 math2036 soee5010 mark3088 infs3605 elec9714 comp2271 ma214 comp2211 infs3604 600426 sit254 acct3091 bbt405 msin0116 com107/com113 mark5826 sit120 comp9021 eco2101 eeen40700 cs253 ece3114 ecmm447 chns3000 math377 itd102 comp9444 comp(2041|9044) econ0060 econ7230 mgt001371 ecs-323 cs6250 mgdi60012 mdia2012 comm221001 comm5000 ma1008 engl642 econ241 com333 math367 mis201 nbs-7041x meek16104 econ2003 comm1190 mbas902 comp-1027 dpst1091 comp7315 eppd1033 m06 ee3025 msci231 bb113/bbs1063 fc709 comp3425 comp9417 econ42915 cb9101 math1102e chme0017 fc307 mkt60104 5522usst litr1-uc6201.200 ee1102 cosc2803 math39512 omp9727 int2067/int5051 bsb151 mgt253 fc021 babs2202 mis2002s phya21 18-213 cege0012 mdia1002 math38032 mech5125 07 cisc102 mgx3110 cs240 11175 fin3020s eco3420 ictten622 comp9727 cpt111 de114102d mgm320h5s bafi1019 math21112 efim20036 mn-3503 fins5568 110.807 bcpm000028 info6030 bma0092 bcpm0054 math20212 ce335 cs365 cenv6141 ftec5580 math2010 ec3450 comm1170 ecmt1010 csci-ua.0480-003 econ12-200 ib3960 ectb60h3f cs247—assignment tk3163 ics3u ib3j80 comp20008 comp9334 eppd1063 acct2343 cct109 isys1055/3412 math350-real math2014 eec180 stat141b econ2101 msinm014/msing014/msing014b fit2004 comp643 bu1002 cm2030
联系我们
EMail: 99515681@qq.com
QQ: 99515681
留学生作业帮-留学生的知心伴侣!
工作时间:08:00-21:00
python代写
微信客服:codinghelp
站长地图