Financial Calculations in MATLAB - The Engineering Projects (2024)

Hello friends, today I am gonna share a MATLAB project related to finance which I have named as Financial Calculations in MATLAB. As this project is the ...

Posted at: 10 - Dec - 2014

Category: MATLAB

Author: syedzainnasir

0 Comments

Financial Calculations in MATLAB - The Engineering Projects (1)

Departments:

  1. Communication Engineering

Softwares:

  1. MATLAB

Buy This ProjectHello friends, today I am gonna share a MATLAB project related to finance which I have named as Financial Calculations in MATLAB. As this project is the outcome of our team efforts so its not free and you can buy it quite easily for just $20 by clicking on the above button. In finance studies, there are lot of calculations are required to be done so MATLAB plays a very important role in finance calculations and showing the pattern in graphical form. In this project, I am first gonna take the Historical Stock Data from web search online so in order to run this program, your computer must have internet access. After getting the historical stock data of 7 different markets or sectors, now there's a need to convert them into same currency so that we can compare it with each other. So, I took US$ as a common currency and convert all others to this currency.

After that I calculated Expected Returns & Covariance Matrix for all these data for the last 10 years and finally plot them. Moreover, I have also plotted the frontiers with risk free rate of 3% so that the ideal and realistic conditions can be compared. So, here are the overall steps we are gonna cover in this project:

  • Step 1: Getting Historical Stock Data
  • Step 2: Conversion of currencies
  • Step 3: Calculate Expected Returns & Covariance Matrix
  • Step 4: Plotting 11 different frontiers in one figure
  • Step 5: Plotting frontiers with risk free rate of 3%.
These are the first five steps of this project. The next five steps are discussed in Implementation of Black-Litterman Approach in MATLAB.

You may also like to read:

  • How to Create a GUI in MATLAB?
  • Protect Code in M File
  • Protect Simulink Design in Matlab

Step 1: Getting Historical Stock Data

  • First of all, I chose 7 financial stock indices for different markets or sectors. So, I used a function named hist_stock_data. The syntax of this function is as follows:

Stocks = hist_stock_data('X', 'Y', 'Z', 'frequency', 'm')

  • X is the starting date and is a string in the format ddmmyyyy.
  • Y is the ending date and is also a string in the format ddmmyyyy.
  • Z is the Ticker symbol, whose historical stock data is needed to be retrieved.
  • M denotes that the function will return historical stock data with a frequency of months.
Hist_stock_data function retrieves historical stock data for the ticker symbol Z between the dates specified by X and Y. The program returns the stock data in a structure giving the Date, Open, High, Low, Close, Volume, and Adjusted Close price adjusted for dividends and splits. I used 7 sectors and retrieved their data using this function. The commands used in MATLAB are:
snp500 = hist_stock_data('01111993','01112013','^GSPC','frequency','m');NDX=hist_stock_data('01111993','01112013','^NDX','frequency','m');GSPTSE=hist_stock_data('01111993','01112013','^GSPTSE','frequency','m');DAX = hist_stock_data('01111993','01112013','^GDAXI','frequency','m');CAC40=hist_stock_data('01111993','01112013','^FCHI','frequency','m');FTAS=hist_stock_data('01111993','01112013','^FTAS','frequency','m');SSMI=hist_stock_data('01111993','01112013','^SSMI','frequency','m');

Step 2: Conversion of currencies

The first two values were in US dollars, while third one was in CAD dollars, fourth and fifth values were in Euros, sixth were in GBP and the last one was in Swiss France. Hence, there was a need to convert all these currencies into one currency as instructed. I converted all of them into US dollars. In order to convert them, I first defined the exchange rate between these currencies and the US dollars using the below code:

GBP2USD=1.6;EURO2USD=1.34;CAD2USD=0.95;SF2USD=1.08;
After defining the exchange rate, I applied it to all the currencies using the below code:
GSPTSE=CurrencyConvert(GSPTSE, CAD2USD);DAX=CurrencyConvert(DAX, EURO2USD);CAC40=CurrencyConvert(CAC40, EURO2USD);FTAS=CurrencyConvert(FTAS, GBP2USD);SSMI=CurrencyConvert(SSMI, SF2USD);
Now all the currencies for the financial stock indices for 7 sectors are obtained in US dollars.

Step 3: Calculate Expected Returns & Covariance Matrix

In this part, we calculated the expected returns and covariance matrix in annual steps for a period of 10 years. I used the data for 7 markets or sectors were obtained in the first step and calculated their expected returns and covariance matrix. The expected rate of return is a probability-weighted average of the rates of return in each scenario. We may write the expected return as:

Where,
  • p(s) = Probability of each scenario
  • r(s) = Holding-price return in each scenario.
  • s = number of scenarios.
  • n = Maximum number of scenarios.

First of all, I initialized a column matrix and filled it with the above data and took log of each data separately by using MATLAB commands as follows:

covmat=cell(1,11);ret=flipud([log(SSMI.Close) log(FTAS.Close) log(CAC40.Close) log(DAX.Close) log(GSPTSE.Close) log(snp500.Close) log(NDX.Close)]);

Further, I calculated the differences between adjacent elements of each data using the diff command in MATLAB.

logRet=[diff(ret(:,1)) diff(ret(:,2)) diff(ret(:,3)) diff(ret(:,4)) diff(ret(:,5)) diff(ret(:,6)) diff(ret(:,7))];

Expected return is nothing other than a guaranteed rate of return. However, it can be used to forecast the future value of a market, and it also provides a guide from which to measure actual returns. Hence to calculate the expected return, I first take two indices with w as a variable where w = 1:10 and calculated these indices for all the values of w and finally took mean value of each data with these two indices as follows:

ind=[(w-1)*12+1 (w+10)*12];estReturn(w,:)=[mean(logRet(ind(1):ind(2),1)) mean(logRet(ind(1):ind(2),2)) mean(logRet(ind(1):ind(2),3)) mean(logRet(ind(1):ind(2),4)) mean(logRet(ind(1):ind(2),5)) mean(logRet(ind(1):ind(2),6)) mean(logRet(ind(1):ind(2),7))];

The above values calculated for all the 10 times and hence it is placed within a for loop. estReturn gives us the estimated return for a single month and now there’s a need to convert it to annual return, which is accomplished by below command, simply by mutilpying it with 12.

estReturn(w,:)=estReturn(w,:)*12;

After the calculation of expected return annually, I used the command var(X) to calculate the variance of the data. Although it was not asked to calculate in the problem but in order to calculate the covariance, it is required to first obtain the data such that each row of the matrix becomes an observation and each column is a variable. The command used for the calculation of variance is as shown below:

stdRet(w,:)=sqrt(12*var([ logRet(ind(1):ind(2),1) logRet(ind(1):ind(2),2) logRet(ind(1):ind(2),3) logRet(ind(1):ind(2),4) logRet(ind(1):ind(2),5) logRet(ind(1):ind(2),6) logRet(ind(1):ind(2),7)]));

Finally, I used the MATLAB command cov(x) to calculate the covariance of the data. The syntax used is:

Y = cov(X)
Where,
  • X = Matrix of data whose covariance is required.
  • Y = Covariance of data X.
As x is a matrix of data in our case where each row is an observation, and each column is a variable, cov(X) is the covariance matrix. Results for the expected return and covariance matrix are shown in the below tables.
Expected ReturnSSMIFTASCAC40DAXGSPTSESNP50NDX
1st year0.06250.03730.05240.06320.07000.08480.0644
2nd year0.09540.05310.07620.08460.08840.09210.1290
3rd year0.08720.05060.09720.09400.09150.07630.1004
4th year0.07420.04570.08140.09250.07470.06100.0835
5th year0.0006-0.00640.01220.01470.0321-0.00580.0110
6th year-0.01120.0007-0.00390.01030.0537-0.00550.0115
7th year-0.0144-0.0069-0.03560.01150.0494-0.0148-0.0307
8th year-0.0314-0.0034-0.0573-0.00410.0295-0.0048-0.0080
9th year0.00810.0180-0.02090.03590.04540.01980.0470
10th year0.04310.05290.02280.09070.06440.05750.1007

Table 1: Expected Returns for 10 years

Covariance Matrix for 1st year
SSMIFTASCAC40DAXGSPTSESNP50NDX
0.03340.01910.02850.03240.01680.01900.0196
0.01910.02010.02340.02710.01550.01690.0257
0.02850.02340.04340.04440.02110.02260.0380
0.03240.02710.04440.06090.02520.02800.0527
0.01680.01550.02110.02520.02680.01980.0342
0.01900.01690.02260.02800.01980.02340.0379
0.01960.02570.03800.05270.03420.03790.1411
Covariance Matrix for 2nd year
SSMIFTASCAC40DAXGSPTSESNP50NDX
0.03180.01790.02730.03220.01620.01850.0235
0.01790.01800.02130.02580.01510.01610.0269
0.02730.02130.04040.04270.02090.02190.0390
0.03220.02580.04270.05900.02550.02790.0503
0.01620.01510.02090.02550.02650.01930.0367
0.01850.01610.02190.02790.01930.02300.0394
0.02350.02690.03900.05030.03670.03940.1014
Covariance Matrix for 3rd year
SSMIFTASCAC40DAXGSPTSESNP50NDX
0.03140.01810.02800.03200.01640.01860.0237
0.01810.01810.02140.02610.01520.01600.0270
0.02800.02140.03970.04330.02120.02240.0399
0.03200.02610.04330.05790.02590.02820.0509
0.01640.01520.02120.02590.02660.01940.0371
0.01860.01600.02240.02820.01940.02270.0395
0.02370.02700.03990.05090.03710.03950.1014

Step 4: Plotting 11 different frontiers in one figure

In this part, it was asked to plot the 11 different frontiers in one figure. The concept of efficient frontier was introduced by Harry Markowitz and it is defined as if a portfolio or a combination of assets has the best expected rate of return for the level of risk, it is facing, then it will be referred as “efficient”.

Few more MATLAB Projects:

  • Find Roots of Quadratic Equation
  • Send Data to Serial Port in MATLAB
  • Speech Recognition using Correlation
  • DTMF Decoder using MATLAB
  • Hexapod Simulation in MATLAB

In order plot them, I used the below code in MATLAB, I used different markers for different plots so that they could be distinguished from one another quite easily. Moreover, I used the command legend in order to show the respective years for which the graphs are plotted. RF is a variable which indicate the risk-free rate and as it is asked to operate under efficient frontier that’s why risk-free rate is equal to zero.

RF=0;for w=1:10[xopt(:,w), muopt(w), sigopt(w)] = highest_slope_portfolio( covmat{1,w}, RF, estReturn(w,:)', stdRet(w,:) );endmker=['o' '+' '*' '.' 'x' 's' 'd' '^' '>' '<']figurefor w=1:10plot (sigopt(w), muopt(w) ,'Marker', mker(w));hold on;plot (0, RF, 'o');hold on;RF_p1 = [0 sigopt(w) 2* sigopt(w)];opt1_p = [.02 muopt(w) (2 * muopt(w) - RF) ];line(RF_p1, opt1_p );endlegend('Year 1994', 'Year 1995', 'Year 1996', 'Year 1997','Year 1998','Year 1999','Year 2000', 'Year 2001', 'Year 2002', 'Year 2003')
In this code, first of all I used highest_slope_portfolio function. This function finds the portfolio with the highest slope.Results are shown in the below figure annually:

Figure 1: Graph for 11 different efficient frontier

Step 5: Plotting frontiers with risk free rate of 3%

The plot in Part (c) was about the efficient frontier with risk rate equal to zero i.e. operating in an ideal condition while in this part, it was asked to plot the same graphs but this time include a risk-free rate of 3%. Hence I used the same code as for the previous part but only this time I used RF = 0.03 as I needed to include a risk free rate of 3%. The code used in MATLAB for this part is shown below:

RF=0.03; %the risk free ratefor w=1:10[xoptRF{w}, muoptRF(w), sigoptRF(w)] = highest_slope_portfolio( covmat{1,w}, RF, estReturn(w,:)', stdRet(w,:) );endfigurefor w=1:10plot (sigoptRF(w), muoptRF(w) ,'Marker', mker(w));hold on;plot (0, RF, 'o');hold on;RF_p1 = [0 sigoptRF(w) 2* sigoptRF(w)];opt1_p = [.02 muoptRF(w) (2 * muoptRF(w) - RF) ];line(RF_p1, opt1_p );endlegend('Year 1994', 'Year 1995', 'Year 1996', 'Year 1997','Year 1998','Year 1999','Year 2000', 'Year 2001', 'Year 2002', 'Year 2003')

The result for this part i.e. after including a risk-free rate of 3% is shown in the figure below. If the Figure 1 and Figure 2 are closely examined then one can see the clear difference. When the risk-free rate was considered zero, all the expected estimate graphs were in positive direction depicting the profit annually while after adding a risk-free rate of 3%, few of the graphs went in the negative direction depicting the loss in those years. Hence adding the risk factor may cause the business to get deceased and it may even cause it to decline continuously which results in disaster.

Figure 2: Graph for 11 different efficient frontier for risk-free rate of 3%

That's all for today, in the coming post, I will calculate more financial terms like Optimal asset allocation, average return, standard deviation and much more, so stay tuned and have fun.

Financial Calculations in MATLAB - The Engineering Projects (2024)

FAQs

Is MATLAB useful for finance? ›

MATLAB® products for computational finance enable you to develop quantitative applications for investment and risk management, econometrics, pricing and valuation, insurance, and algorithmic trading. By writing only a few lines of code, you can: Chart historical and live market data.

What is MATLAB used for in engineering? ›

MATLAB® is a programming platform designed specifically for engineers and scientists to analyze and design systems and products that transform our world. The heart of MATLAB is the MATLAB language, a matrix-based language allowing the most natural expression of computational mathematics.

Is MATLAB used in quant finance? ›

Quants and financial data scientists use MATLAB to develop and deploy various machine learning applications in finance, including algorithmic trading, asset allocation, sentiment analysis, credit analytics, and fraud detection.

What is MATLAB good for? ›

MATLAB Speaks Math

Engineers and scientists need a programming language that lets them express matrix and array mathematics directly. Linear algebra in MATLAB is intuitive and concise. The same is true for data analytics, signal and image processing, control design, and other applications.

Do engineers actually use MATLAB? ›

Mechanical engineers of Design and manufacturing field use MATLAB and Simulink heavily. You would be surprised to know that MATLAB also forms the based for different CAD software as well as designing software just like SOLIDWORKS.

Do engineers use MATLAB a lot? ›

MATLAB is widespread in engineering research and education but seldom used in industrial product development.

Why do engineers use MATLAB instead of Python? ›

MATLAB language is the first (and often only) programming language for many engineers and scientists because the matrix math and array orientation of the language makes it easy to learn and apply to engineering and scientific problem-solving.

Is MATLAB useful for mechanical engineers? ›

Engineers use MATLAB to develop, design, simulate, and test their models before it can be developed in the real world. In the field of mechanical engineering, MATLAB is used for solving problems related to dynamic and static systems, mechanical vibrations, control systems, statics, and more.

Why do we need MATLAB in solving engineering problems? ›

Why we need Matlab? MATLAB is a very important program that many engineering students and engineers must learn. It helps to perform mathematical calculation, design, analysis and optimization (structural and mathematical), as well as gives speed, accuracy and precision to results.

What is MATLAB for finance? ›

The MATLAB Computational Finance Suite is a set of 12 essential products that enables you to develop quantitative applications for risk management, investment management, econometrics, pricing and valuation, insurance, and algorithmic trading.

Do financial analysts use MATLAB? ›

Financial professionals worldwide use MATLAB and other MathWorks tools to rapidly develop financial models and freely deploy customized algorithms to decision makers such as investment managers, actuaries, and traders.

Do banks use MATLAB? ›

Financial professionals from more than 2300 organizations worldwide use MATLAB® to develop and implement financial models, analyze substantial volumes of data, and operate under tightening regulation.

What are 2 disadvantages of MATLAB? ›

Disadvantages of MATLAB
  • It isn't easy to extend the functionality through third parties due to its proprietary nature.
  • It is less expressive language.
  • It is quite expensive, which means code written in MATLAB can only be used the other person has a license.
May 17, 2021

What is biggest advantage of MATLAB? ›

Data Analysis and Visualization: MATLAB provides powerful tools for data analysis, manipulation, and visualization. It offers functions for data cleaning, filtering, statistics, plotting, and creating interactive visualizations.

Is MATLAB harder than Python? ›

The OOP in MATLAB is more advanced and complex, which to some can be more confusing. That being said, MATLAB is generally a more advanced language while Python is more of a beginner's language. Therefore, just because MATLAB may be more complex and confusing at first, with practice, it will become easier to grasp.

Is MATLAB used in investment banking? ›

Financial professionals from more than 2300 organizations worldwide use MATLAB® to develop and implement financial models, analyze substantial volumes of data, and operate under tightening regulation.

What is MATLAB in finance? ›

The MATLAB Computational Finance Suite is a set of 12 essential products that enables you to develop quantitative applications for risk management, investment management, econometrics, pricing and valuation, insurance, and algorithmic trading.

What is MATLAB used for in business? ›

Organizations worldwide use MATLAB® to power math-intensive systems for predictive analytics, financial modeling, image and signal processing, control systems, and many other applications.

Do economists use MATLAB? ›

MATLAB is used by many Economics educators to teach computation due to its built-in capabilities for working with time series data, performing fast numerical computations, and visualizing results of analyses.

Top Articles
Latest Posts
Article information

Author: Virgilio Hermann JD

Last Updated:

Views: 6104

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Virgilio Hermann JD

Birthday: 1997-12-21

Address: 6946 Schoen Cove, Sipesshire, MO 55944

Phone: +3763365785260

Job: Accounting Engineer

Hobby: Web surfing, Rafting, Dowsing, Stand-up comedy, Ghost hunting, Swimming, Amateur radio

Introduction: My name is Virgilio Hermann JD, I am a fine, gifted, beautiful, encouraging, kind, talented, zealous person who loves writing and wants to share my knowledge and understanding with you.