financial project portfolio
DESCRIPTION
My Financial ProjectsTRANSCRIPT
Projects Portfolio
Daniel Fei WangMaster in Financial Markets
Trading Strategies & Financial EngineeringIllinois Institute of Technology
Chicago, IL 60661312-927-2431
Trading Projects ListProject I: Page 2 – Page 25
Pair Trading Model with Equities, ETFS and Options
Project II: Page 26 – Page 28
Fixed Income Trading Portfolio Modeling with Ted Spreads, Yield Curve Trade, and Basis Trade
Project III: Page 29 – Page 41
Algorithmic Equity Trading System with Moving Averages and Oscillators in MATLAB
Project IV: Page 42 – Page 54
Portfolio Optimization Model by VBA
Project V: Page 55 – Page 69
Market Risk Management Report By VAR Analysis
Project VI: Page 70 – Page
77
Summary of Financial Modeling by MATLAB
1
Statistical Arbitrage Trading Model------With Stocks & ETFs For Short Term Intra-Day Trading and Long Term Back Testing
1). Equity Searching & Pairs Research
Stock Pair One:
ABX / NEM
Sector: Gold Mines for Both
Average Volume: 13168417 / 7819029
Float: 968M / 478.9625M
Short Interest: 8.695M / 7.141M
Historical Chart from 3/2/2009 to 9/14/2009, Data Time Interval : 1 hour
Regression Data:
Regression Statistics
Multiple R 0.6826
R Square 0.4660
Adjusted R Square
0.4654
Standard Error 2.1738
Observations 945.0000
2
ANOVA
df SS MS F Significanc
e F
Regression 1.0000
3,888.3976
3,888.3976
822.8359 0.0000
Residual 943.0000
4,456.2455 4.7256
Total 944.0000
8,344.6431
Stock Pair Two:
APA / APC
Sector: Energy Company / oil Gas Exploration
Average Volume: 4870352 / 7724989
Float: 333.81M / 488.27M
Short Interest: 4.228M / 10.573M
Historical Chart from 3/2/2009 to 9/14/2009, Data Time Interval : 1 hour
Regression Data: Regression Statistics
Multiple R 0.9396
R Square 0.8828
Adjusted R Square
0.8827
Standard Error 3.2803
Observations 954.0000
ANOVA
df SS MS F Significanc
e F
3
Regression 1.0000
77,170.4322
77,170.4322
7,171.8273 -
Residual 952.0000
10,243.7284
10.7602
Total 953.0000
87,414.1606
Stock Pair Three:
APA / MUR
Sector: Energy Company / oil Gas Exploration
Average Volume: 4870352 / 2269944
Float: 333.81M / 178.51M
Short Interest: 4.228M / 5.636M
Historical Chart from 3/2/2009 to 9/14/2009, Data Time Interval : 1 hour
Regression Data:Regression Statistics
Multiple R 0.943594R Square 0.890369Adjusted R Square 0.890254Standard Error 3.172775Observations 954
ANOVA
df SS MS FSignificance
FRegression 1 77830.85 77830.85 7731.668 0Residual 952 9583.31 10.0665Total 953 87414.16
Stock Pair Four:
ALTR / LSCC
Sector: Both Programmable logic Devices
4
Average Volume: 9065785 / 745356
Float: 293.63M / 114.89M
Short Interest: 18.629M / 2.006M
Historical Chart from 3/2/2009 to 9/14/2009, Data Time Interval : 1 hour
Regression Data:Regression Statistics
Multiple R 0.666213R Square 0.44384Adjusted R Square 0.443251Standard Error 0.996277Observations 946
ANOVA
df SS MS FSignificance
FRegression 1 747.7548 747.7548 753.3531 2.1E-122Residual 944 936.985 0.992569Total 945 1684.74
Stock Pair Five:
BNI / CSX
Sector: Both Transportation
Average Volume: 3842821 / 7092411
Float: 338.55M / 389.52M
Short Interest: 4.560M / 22.710M
Historical Chart from 3/2/2009 to 9/14/2009, Data Time Interval : 1 hour
5
Regression Data:Regression Statistics
Multiple R 0.959484R Square 0.92061Adjusted R Square 0.920527Standard Error 2.451596Observations 954
ANOVA
df SS MS FSignificance
FRegression 1 66351.03 66351.03 11039.51 0Residual 952 5721.83 6.010325Total 953 72072.86
Stock Pair Six:
BNI / UNP
Sector: Transportation / Electricity Transmission
Average Volume: 3842821 / 6288171
Float: 338.55M / 502.07M
Short Interest: 4.560M / 5.487M
Historical Chart from 3/2/2009 to 9/14/2009, Data Time Interval : 1 hour
6
Regression Data:Regression Statistics
Multiple R 0.98440392R Square 0.969051078Adjusted R Square 0.969018328Standard Error 1.53524198Observations 947
ANOVA
df SS MS FSignificance
FRegression 1 69740.75153 69740.75153 29589.18128 0Residual 945 2227.3347 2.356967936Total 946 71968.08623
2) Model Building, Back-testing & Results
Algorithm & Model Building:
The Algorithm of this pair trading model based on several straight-forward equation and definitions:
Step 1) Calculate Pair Price Ratio
Step 2) Determine Moving Average of Price Ratio by put an input parameter in VBA Program
Step 3) Calculate the Spread called Sigma by using the following formula:
Sigma = Price A - Moving Average ( A/B ) * Price B
7
Step 4) Compute the moving average of Sigma by put an input parameter in VBA Program again
Step 5) Calculate the moving standard deviation of Sigma
Step 6) Calculate the Z- Volatility Score Value by comparing Sigma with its moving average and standard deviation.
The formula is Z- Volatility Score = (Sigma – moving average) / moving standard deviation
Step 7) Based on the Z-Volatility Score, we determine the buy and sell signal, and we set up an benchmark in VBA program input field.
Important Notes: the price I used to generate buy and sell signal, long/short share amount is the average of bid and ask for each time. Based on these signal and long/short amount, I take bid and ask price and cost for each trade to calculate the Market-to-Market P&L for the spread.
Back testing by change the parameters
---Built Model in VBA to back-testing the pairs---Initial Portfolio 100,000 for each Pairs---Determine which moving average length, trade signal, and position sizing makes you the most money.
Back Testing Result & Market to Market Account Chart
------Results:
ABX / NEM APA / APC
Intial Portfolio $100,000.00 Intial Portfolio $100,000.00
Price Data 946 Percentage Price Data 955 Percentage
Net P&L $237.88 0.24% Net P&L $9,383.71 9.38%
Winning trades 39 63.93% Winning trades 17 60.71%
losing trades 22 36.07% losing trades 11 39.29%
Total Trades 61 Total Trades 28
Max Down -2.5156% Max Down -2.3627%
Max up 2.3174% Max up 2.7464%
8
APA / MUR ALTR / LSCCIntial Portfolio $100,000.00 Intial Portfolio $100,000.00Price Data 955 Percentage Price Data 947 Percentage
Net P&L $2,299.50 2.30% Net P&L $1,236.54 1.24%
Winning trades 11 61.11% Winning trades 18 62.07%
losing trades 7 38.89% losing trades 11 37.93%
Total Trades 18 Total Trades 29Max Down -2.4807% Max Down -37.7425%Max up 4.3969% Max up 61.1562%
BNI / CSX BNI / UNPIntial Portfolio $100,000.00 Intial Portfolio $100,000.00Price Data 955 Percentage Price Data 948 Percentage
Net P&L $2,304.74 2.30% Net P&L $2,776.72 2.78%
Winning trades 17 68.00% Winning trades 16 59.26%
losing trades 8 32.00% losing trades 11 40.74%
Total Trades 25 Total Trades 27
Max Down -2.0028%Max Percentage Down -2.5592%
Max up 2.2569%Max Percentage up 3.5574%
ABX / NEM
APA / APC
9
APA / MUR
ALTR / LSCC
BNI / CSX
BNI / UNP
10
2. ETF Pairs With Intraday Trading:
1). ETFS Searching & Pairs Research
ETFs Pair One:
IYR / URE
Sector: Real Estate Industry
Average Volume: 34195215 / 22932178
Float: 59.4M / 103.125M
Short Interest: 67.3M / 12.28M
Historical Chart from 3/2/2009 to 9/14/2009, Data Time Interval : 1 hour
Regression:Regression Statistics
Multiple R 0.987473407R Square 0.97510373Adjusted R Square 0.975076006Standard Error 0.690181083Observations 900
ANOVA
df SS MS FSignificance
FRegression 1 16754.01773 16754.01773 35171.66013 0
11
Residual 898 427.7622344 0.476349927Total 899 17181.77996
ETFs Pair Two:
XLF / FAS
Sector: Financial Select Sector
Average Volume: 191MLN / 32200597
Float: 510M/ 13.2489M
Short Interest: 111M / 4,488,052
Historical Chart from 3/2/2009 to 9/14/2009, Data Time Interval : 1 hour
Regression:Regression Statistics
Multiple R 0.965554314R Square 0.932295134Adjusted R Square 0.932219486Standard Error 0.465995702Observations 897
ANOVA
df SS MS FSignificance
FRegression 1 2676.211 2676.211 12324.14 0Residual 895 194.351 0.217152Total 896 2870.562
ETFs Pair Three:
XLF / UYG
Sector: Financial Select Sector / Dow Jones U.S. Financials Index
Average Volume: 191MLN / 108MLN
12
Float: 510M/ 405.75M
Short Interest: 111M / 26.33M
Historical Chart from 3/2/2009 to 9/14/2009, Data Time Interval : 1 hour
Regression:Regression Statistics
Multiple R 0.988323105R Square 0.976782561Adjusted R Square 0.97675662Standard Error 0.272884664Observations 897
ANOVA
df SS MS FSignificance
FRegression 1 2803.915193 2803.915193 37653.60964 0Residual 895 66.64710558 0.07446604Total 896 2870.562298
ETFs Pair Four:
VWO / FXI
Sector: emerging markets around the world / largest companies in the China equity market
Average Volume: 5404127 / 34709548
Float: 332.5M/ 221.4M
Short Interest: 8,448,043 / 30.75M
Historical Chart from 3/2/2009 to 9/14/2009, Data Time Interval : 1 hour
13
Regression:Regression Statistics
Multiple R 0.984253613R Square 0.968755175Adjusted R Square 0.968720574Standard Error 0.753412507Observations 905
ANOVA
df SS MS FSignificance
FRegression 1 15892.39456 15892.39456 27997.7859 0Residual 903 512.5702562 0.567630405Total 904 16404.96482
ETFs Pair Five:
IWM / SMH
Sector: 2000 Index Fund Growth-Small Cap / Fund-Technology
Average Volume: 73536673 / 14302000
Float: 200M/ 31.4M
Short Interest: 139M / 27.8M
Historical Chart from 3/2/2009 to 9/14/2009, Data Time Interval : 1 hour
14
Regression:Regression Statistics
Multiple R 0.93493514R Square 0.874103716Adjusted R Square 0.873963831Standard Error 1.869407541Observations 902
ANOVA
df SS MS FSignificance
FRegression 1 21837.38064 21837.38064 6248.741567 0Residual 900 3145.216098 3.494684554Total 901 24982.59673
2) Model Building, Back-testing & Results
Algorithm & Model Building:
The Algorithm of this pair trading model based on several straight-forward equation and definitions:
Step 1) Calculate Pair Price Ratio
Step 2) Determine Moving Average of Price Ratio by put an input parameter in VBA Program
Step 3) Calculate the Spread called Sigma by using the following formula:
Sigma = Price A - Moving Average ( A/B ) * Price B
Step 4) Compute the moving average of Sigma by put an input parameter in VBA Program again
Step 5) Calculate the moving standard deviation of Sigma
Step 6) Calculate the Z- Volatility Score Value by comparing Sigma with its moving average and standard deviation.
The formula is Z- Volatility Score = (Sigma – moving average) / moving standard deviation
Step 7) Based on the Z-Volatility Score, we determine the buy and sell signal, and we set up an benchmark in VBA
15
program input field.
Important Notes: the price I used to generate buy and sell signal, long/short share amount is the average of bid and ask for each time. Based on these signal and long/short amount, I take bid and ask price and cost for each trade to calculate the Market-to-Market P&L for the spread.
Back testing by change the parameters
(Same as Equity) ---Built Model in VBA to back-testing the pairs
---Initial Portfolio 100,000 for each Pairs---Determine which moving average length, trade signal, and position sizing makes you the most money.
Back Testing Result & Market to Market Account Chart
------Results:
Mid-Term 6 monthXLF / UYG IYR / URE
Intial Portfolio $100,000.00 Intial Portfolio $100,000.00Price Data 898 Percentage Price Data 901 Percentage
Net P&L $6,139.17 6.14% Net P&L $46,294.40 46.29%
Winning trades 19 55.88% Winning trades 38 73.08%
losing trades 15 44.12% losing trades 14 26.92%
Total Trades 34 Total Trades 52Max Down -2.3808% Max Down -2.7293%Max up 2.8235% Max up 2.7012%
XLF / FAS IWM / SMH Intial Portfolio $100,000.00 Intial Portfolio $100,000.00Price Data 898 Percentage Price Data 903 Percentage
Net P&L $9,639.91 9.64% Net P&L $18,187.02 18.19%
Winning trades 17 54.84% Winning trades 34 82.93%
losing trades 14 45.16% losing trades 7 17.07%
Total Trades 31 Total Trades 41Max Down -4.5232% Max Down -1.6654%Max up 6.3077% Max up 1.9746%
16
VWO / FXIIntial Portfolio $100,000.00Price Data 906 Percentage
Net P&L $2,869.84 2.87%
Winning trades 25 64.10%
losing trades 14 35.90%
Total Trades 39Max Down -2.8794%Max up 2.9260%
Long Term 3 yearsXLF UYG IYR URE
Intial Portfolio $100,000.00 Intial Portfolio $100,000.00Price Data 650 Percentage Price Data 656 Percentage
Net P&L $1,815,248.87 1815.25% Net P&L $15,483.82 15.48%
Winning trades 42 89.36% Winning trades 20 64.52%
losing trades 5 10.64% losing trades 11 35.48%
Total Trades 47 Total Trades 31
IWR IWP IWM SMHIntial Portfolio $100,000.00 Intial Portfolio $100,000.00Price Data 758 Percentage Price Data 758 Percentage
Net P&L $13,622.27 13.62% Net P&L $3,032.82 3.03%
Winning trades 82 77.36% Winning trades 13 46.43%
losing trades 24 22.64% losing trades 15 53.57%
Total Trades 106 Total Trades 28
Total PortfolioShort Term 6 monthIntial 500000End $583,130.34Net P&L $83,130.34Return 16.63%
Long Term 3 yearintial 400000End $1,847,387.78Net P&L $1,447,387.78Return 361.85%
17
Short Term Market-to-Market Chart 6 monthDaily Data Time Interval
XLF / UYG
IYR / URE
XLF / FAS
IWM / SMH
18
VWO / FXI
Some Long Term Market-to-Market Chart to Compare make money during Market Crsis 3 years
XLF / UYG
XLF / UYG
19
IYR / URE
IWR / IWP
IWR / IWP
IWM / SMH
20
3 Real Time Signal Generation
By pulling real time data from Bloomberg, I use the program keep doing the algorithm moving forward with the moving average and standard deviation to generate the buy and sell signal, and then to calculate the P&L for each time step.
VBA Code:
' The program use the C++ inline function call itself in the subroutine
Public Sub Cal()
Worksheets("data").Range("ai2", "ai32773").Cells(Worksheets("data").Range("d2"), 1) = Worksheets("data").Range("h8")
Worksheets("data").Range("aj2", "aj32773").Cells(Worksheets("data").Range("d2"), 1) = Worksheets("data").Range("h5")
Worksheets("data").Range("ak2", "ak32773").Cells(Worksheets("data").Range("d2"), 1) = Worksheets("data").Range("h9")
Worksheets("data").Range("al2", "al32773").Cells(Worksheets("data").Range("d2"), 1) = Worksheets("data").Range("h6")
Worksheets("data").Range("a2", "a32773").Cells(Worksheets("data").Range("d2"), 1) = 0.5 * (Worksheets("data").Range("ai2", "ai32773").Cells(Worksheets("data").Range("d2"), 1) + Worksheets("data").Range("aj2", "aj32773").Cells(Worksheets("data").Range("d2"), 1))
Worksheets("data").Range("b2", "b32773").Cells(Worksheets("data").Range("d2"), 1) = 0.5 * (Worksheets("data").Range("ak2", "ak32773").Cells(Worksheets("data").Range("d2"), 1) + Worksheets("data").Range("al2", "al32773").Cells(Worksheets("data").Range("d2"), 1))
Worksheets("data").Range("c2", "c32773").Cells(Worksheets("data").Range("d2"), 1) = Now()
If Worksheets("data").Range("d2") > 52 Then
Call ClearputsCall MainProgram
End If
Worksheets("data").Range("d2") = Worksheets("data").Range("d2") + 1
Application.OnTime Now + TimeValue(Worksheets("data").Range("d1").Value), "cal"End Sub
21
4. Long Term Statistic Hedging & Portfolio Management
1.) Equity Pairs with Daily Data
A. Pairs Historical Technique Research
Data Time Range: 97.01.02-----04.01.06
Equity Pairs:
WMT/COST (Wholesale) (Large Cap)
Close Correlation 0.29 COSTChange Correlation 0.98 WMT Differential Ratio Closing SpreadMean -15.52 0.71 -0.01Median -15.94 0.70 0.06Mode -16.52 0.69 0.28 Average Deviation 4.89 0.09 1.06Standard Deviation 6.25 0.11 1.57Population Standard Deviation 6.25 0.11 1.57
Differential Moving Averages
-5.0000
-4.0000
-3.0000
-2.0000
-1.0000
0.0000
1.0000
2.0000
3.0000
4.0000
20
02
/1/2
5
20
02
/3/2
5
20
02
/5/2
5
20
02
/7/2
5
20
02
/9/2
5
20
02
/11
/25
20
03
/1/2
5
20
03
/3/2
5
20
03
/5/2
5
20
03
/7/2
5
20
03
/9/2
5
20
03
/11
/25
90-Days 160-Days 250-Day
WERN/YELL
Close Correlation 0.71 WERN 18.11Change Correlation 0.93 YELL 14.25
22
Differential Ratio Closing SpreadMean -7.91 0.63 0.02Median -7.32 0.63 0.01Mode -7.54 0.55 0.00 Average Deviation 2.08 0.06 1.11Standard Deviation 2.79 0.07 5.69Population Standard Deviation 2.79 0.07 5.69
Differential Moving Averages
-5.0000
-4.0000
-3.0000
-2.0000
-1.0000
0.0000
1.0000
2.0000
3.0000
4.0000
19
97
/1
/2
19
97
/3
/2
19
97
/5
/2
19
97
/7
/2
19
97
/9
/2
19
97
/1
1/2
19
98
/1
/2
19
98
/3
/2
19
98
/5
/2
19
98
/7
/2
19
98
/9
/2
19
98
/1
1/2
90-Days 160-Days 250-Day
IP/BCC
Close Correlation 0.65 IP 43.6Change Correlation 0.99 BCC 34.11 Differential Ratio Closing SpreadMean 7.36 1.27 0.00Median 6.88 1.22 0.00Mode 10.97 1.12 0.00 Average Deviation 3.10 0.13 0.37Standard Deviation 3.58 0.16 0.52Population Standard Deviation 3.57 0.16 0.52
23
Differential Moving Averages
-5.0000
-4.0000
-3.0000
-2.0000
-1.0000
0.0000
1.0000
2.0000
3.0000
4.0000
20
02
/1
/2
5
20
02
/3
/2
5
20
02
/5
/2
5
20
02
/7
/2
5
20
02
/9
/2
5
20
02
/1
1/2
5
20
03
/1
/2
5
20
03
/3
/2
5
20
03
/5
/2
5
20
03
/7
/2
5
20
03
/9
/2
5
20
03
/1
1/2
5
90-Days 160-Days 250-Day
EOG/BR
Close Correlation 0.18 EOG 24.62Change Correlation 0.91 BR 47.39 Differential Ratio Closing SpreadMean -15.56 0.59 -0.03Median -17.83 0.51 -0.03Mode -21.03 0.48 0.24 Average Deviation 5.46 0.14 1.07Standard Deviation 7.49 0.24 2.58Population Standard Deviation 7.48 0.24 2.58
Differential Moving Averages
-4.0000
-2.0000
0.0000
2.0000
4.0000
6.0000
8.0000
10.0000
12.0000
14.0000
19
97
/1
/2
19
97
/3
/2
19
97
/5
/2
19
97
/7
/2
19
97
/9
/2
19
97
/1
1/2
19
98
/1
/2
19
98
/3
/2
19
98
/5
/2
19
98
/7
/2
19
98
/9
/2
19
98
/1
1/2
90-Days 160-Days 250-Day
B Model Building and Back-testing
Four Pairs I choose are (COST /WMT), (WERN/YELL), (IP/BCC ), (EOG/BR)
24
Basically, I choose the pairs who have high change correlation, and whose volatility ratio is normal.
Also I choose the pair from lower P/E ratio and same industry.
Intial Portfolio for each Pair 1,000,000
By keeping changing the parameter, I get the P&L as follow:
P&Lsingal 2 and -2 1.5 and -1.5 1 and -1
PL 1 Pair COST /WMT $1,545,782.67 $3,905,349.17 $8,728,578.15 Profits times 31.00 Loss times 18.00 Profit Factor 2.14
$519,067.56 $38,854.94 $1,037,323.32 WERN/YELLProfits times 28 Loss times 18 Profit Factor 2.136673883
$541,652.63 $1,577,210.95 $1,354,645.33 IP/BCCProfits times 28.00 Loss times 14.00 Profit Factor 2.00
$4,948,500.34 $43,238,730.73 $75,275,510.23 EOG/BRProfits times 33Loss times 6 Profit Factor 6.109747295
C. Option Pairs with Daily Data
Based on the four pairs of equities in the first portfolio, I build the model the option pair trading in VBA,
The algorithm is hedging pairs by Delta to generate the buy or sell at the money call or put at different signal point, which is generated by undervalued or overvalued spread price and undervalued or overvalued Volatility.
Finally, the result for the option pair trading is as follow
singal 2 and -2 1.5 and -1.5 1 and -1PL 1 Pair COST /WMT
$$79,123,812.98
$ $195,563,930.76
$ $1,052,834,845.18
PL 1 PairWERN/YELL
$ $8,837,609.97
$22,812,164.42
$ $37,358,989.52
PL 1 PairIP/BCC
$311,899,424.76
$ $3,881,076,833.44
$ $5,738,904,258.93
PL 1 PairEOG/BR
$88,426,672.09
$48,590,921,277.17
$16,269,381,046.76
25
Fixed Income Trading Strategies PortfolioNotes: All VBA Codes for this projects are attached at the back of the project portfolio
For this project, I build the Macro in Excel by using VBA. The process I did this as follow:
First, I calculate the Duration, Convexity and Yield for all 35 bonds, and I can also calculate more bonds if I input more bonds. And I calculate the Net Duration, Convexity and Yield for project 1. And this is called USTDurationCovex and Port1 in my VBA Code.
Portfolio at the last DayPar Amount Duration Covexity Yield Date
1 $100,000,000 0.8405094 0.0044779 2009/4/23 $100,000,000 1.8750005 4.4611338 0.0086958 2009/4/25 $100,000,000 2.7898725 9.2461094 0.0128316 2009/4/27 $100,000,000 4.6631282 24.591889 0.0204651 2009/4/29 $100,000,000 8.0146283 74.796798 0.0308571 2009/4/2
11 $100,000,000 16.620428 386.4433 0.0403963 2009/4/2Portfolio
1 $600,000,000 5.80 83.26 0.01962 2009/4/2
Second, I calculate all the carries and reverse carries per dollar trade in VBA and outputs in different excel spreadsheets. And then obtain the short and long P&L for 1 dollar for all 35 bonds by adding Carry and Capital gain. This Subroutine is called Carry.
The Trades I have done are as follow: Curve Steepener, Curve Flattner, Butterfly, Basis, and Ted Spread.
Moreover, I begin to do the different trades, and get the P&L by picking the right P&L from what I have done for all 35 bonds, and then multiply by the right par amount for each trade to get the P&L for all the trades at each day. This Subroutine in VBA is called Trade.
Then, I change the par amount to 1 million for the 1st instrument of each trade and acquire another P&L for each day, and calculate 2 standard deviation of 10 days P&L for each trade.
Finally, I start my money management approach as follow: I use the smallest Standard deviation one as a benchmark to relocate my capital for each trade to get the P&L for the 10 days and I also obtain the P&L for the last day which is 11th day on 5/8/2009.
The Result are:
With 1 million invested:
P&L for the last day on 5/8/2009
26
Curve steepener $6,137.85 Curve steepener $13,805.90 Curve flattener ($6,684.14)Curve flattener ($6,848.30)Butterfly $2,774.55 Butterfly ($3,982.31)Butterfly $1,638.56 basis $714.78 basis $1,407.79 basis ($2,531.37)basis $344.76 Ted 5253.70Ted 30331.00
2 standard deviation is as follow:
Obviously, the first basis trade is the smallest one with same amount of capital invested.
curve steepener $7,106.72
curve steepener $3,520.22
curve flattener $3,962.01
curve flattener $16,100.59
Butterfly $7,019.99
Butterfly $16,004.25
Butterfly $3,964.93
basis $2,903.40
basis $3,521.72
basis $3,189.99
basis $4,632.61Ted $4,174.64Ted $69,036.64
After the 2 standard deviation adjustment, the P&L for the last day on 5/8/2009 is
curve steepener $2,507.57 curve steepener $11,386.80 curve flattener ($4,898.20)curve flattener ($1,234.94)Butterfly $1,147.53 Butterfly ($722.45)Butterfly $1,199.86
27
basis $714.78 basis $1,160.62 basis ($2,303.95)basis $216.07 Ted 3650.14Ted 1282.09
28
Algorithm Equity Trading System with Moving Averages and Oscillators
Result:
Result Summary
LargestLoss =
-9367e+004
LargestWin =
339752
numloss =
381
numwin =
639
ProfitFactor =
1.0686
SortinoRatioAnnual =
0.1284
ExpectedProfit =
2.7445e+003
RRR =
-0.0567
29
0 500 1000 1500 2000 250020
30
40
50
60
70
80
90
100
110
120P
rice
Close
5-day Moving Average
20-day Moving Average
0 500 1000 1500 2000 25000
50
100
150Close
0 500 1000 1500 2000 25000
50
100Stochastic %K%D
%K
%D
30
0 500 1000 1500 2000 25000
50
100
150Close
0 500 1000 1500 2000 25000
50
100RSI
RSI
3070
0 500 1000 1500 2000 25000
100
200
Pric
e
Close
5-day Moving Average
20-day Moving Average
0 500 1000 1500 2000 25000
50
100Stochastic %K%D
%K
%D
0 500 1000 1500 2000 25000
50
100RSI
RSI
3070
MATLAB CODE:
By Daniel (Fei) Wang %We save the qqqq data as "data" in our folder and run the program.
31
clear all, clc load data open=data(:,1);high=data(:,2);low=data(:,3);close=data(:,4); s=size(data);m=s(1,1); nuMA=1;nuKD=1;nuRSI=1; %I. Signal Generation %1. By Moving Average: 5-day nd 20-day %1.1 find moving average%1.1.1 5-day moving averageclose5=zeros(m,1);for i=5:m close5(i,1)=mean(close(i-4:i,1));end close5MX=[close,close5]; %1.1.2 20-day moving averageclose20=zeros(m,1);d=20;d1=d+1;d2=d-1;for i=d:m close20(i,1)=mean(close(i-d2:i,1));end MAMX=[close,close5,close20]; %1.2 Plot 5-day and 20-day Moving Average with close%***since the first 19 periods are not applicableMAplot=MAMX(d:end,:); %&&&&&&&PLOT&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&777777plot(MAplot)ylabel('Price')legend('Close','5-day Moving Average','20-day Moving Average')%&&&&&&PLOT&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&777777 %1.3 Generate signals by moving averageMAsig(1,1)=0;for i=d1:m if (close5(i)> close20(i))&&(close5(i-1)<= close20(i-1)) MAsig(i)=1; elseif (close5(i)< close20(i))&&(close5(i-1)>= close20(i-1)) MAsig(i)=-1;
32
else MAsig(i)=0; endendMAsig=MAsig';MAsig=nuMA*MAsig;MAsigMX=[[1:m]',MAMX,MAsig]; %1.4 Number of MA signalsaMAsig=abs(MAsig); numMAsig=sum(aMAsig); %2. By Stochastic %K and %D %*** we assume the time period is 14p=14;p1=p+1;%just helps to match matrixesp2=p-1;%just helps to match matrixes %2.1 Find the highest high and lowest low prices in each 14 periodsL14=zeros(m,1);H14=zeros(m,1);for i=p:m L14(i,1)=min(low(i-13:i,1)); H14(i,1)=max(high(i-13:i,1));end %2.2 Calc %K K=zeros(m,1);for i=p:m K(i,1)=100*(close(i,1)-L14(i,1))/(H14(i,1)-L14(i,1));endKMX=[high,low,close,L14,H14,K]; %2.3 Find %D, 3-period moving averageD=zeros(m,1);p3=p+2;for i=p3:m D(i,1)=mean(K(i-2:i,1));endKDMX=[high,low,close,L14,H14,K,D]; %2.4 Plot %K and %D with closeKD=[K,D];%*** since the first 14 periods are not applicableKDplot=KD(p1:m,:);KDclose=close(p1:m,:); %&&&&&&&PLOT&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&777777figuresubplot(2,1,1); plot(KDclose)title('Close')subplot(2,1,2); plot(KDplot)title('Stochastic %K%D')legend('%K','%D')%&&&&&&&PLOT&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&777777 % 2.5 KD Signal Generation
33
KDsig=zeros(m,1);p4=p+3;for i=p4:m if (K(i,1)>D(i,1))&&(K(i-1,1)<=D(i-1,1)) KDsig(i,1)=1; elseif (K(i,1)<D(i,1))&&(K(i-1,1)>=D(i-1,1)) KDsig(i,1)=-1; endendKDsig=nuKD*KDsig;KDsigMX=[KDMX,KDsig]; %2.6 Numbers of KD signalaKD=abs(KDsig);numKDsig=sum(aKD); %3. BY RSI,Relative Strength Index, %technical momentum indicator that compares the magnitude of recent gains %to recent losses in an attempt to determine overbought %and oversold conditions of an asset. %3.1 Calc the changes of the close priceschg=zeros(m,1);for i=2:m chg(i,1)= close(i,1)-close(i-1,1);endchgMX=[close,chg]; %3.2 Seperate the advances and declines from the changesadva=zeros(m,1);decl=zeros(m,1);for i=1:m if chg(i,1)>0 adva(i,1)=chg(i,1); elseif chg(i,1)<0 decl(i,1)=-chg(i,1); endendadMX=[chgMX,adva,decl]; %3.3 Calc the average gains and average losses for 14 periodsp=14;p1=p+1;%just helps to match matrixesp2=p-1;%just helps to match matrixesavggain=zeros(m,1);avgloss=zeros(m,1);avggain(p1,1)=mean(adva(2:p1,1));avgloss(p1,1)=mean(decl(2:p1,1));for i=16:m avggain(i,1)= (avggain(i-1,1)*p2+adva(i,1))/p; avgloss(i,1)=(avgloss(i-1,1)*p2+decl(i,1))/p;endavgMX=[adMX,avggain,avgloss]; %3.4 Calc RSRS=zeros(m,1);for i=p1:m RS(i,1)=avggain(i,1)/avgloss(i,1);end %3.5 Calc RSI
34
RSI=zeros(m,1);for i=p1:m if avgloss==0 RSI(i,1)=100; else RSI(i,1)=100-(100/(1+RS(i,1))); endend RSIMX=[close,chg,adva,decl,avggain,avgloss,RS,RSI]; %3.6 Plot the RSI with closel30=30*ones(m,1);l70=70*ones(m,1);RSIband=[RSI,l30,l70]; %since the first 14 periods are not applicableRSIclose=close(p1:m,1);RSIplot=RSIband(p1:m,:); %&&&&&&&PLOT&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&777777figuresubplot(2,1,1); plot(RSIclose)title('Close')subplot(2,1,2); plot(RSIband)title('RSI')legend('RSI','30','70')%&&&&&&&PLOT&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&777777 %3.7 RSI Signal GenerationRSIsig=zeros(m,1);p3=p+2;for i=p3:m if (RSI(i,1)<70)&&(RSI(i-1,1)>70) RSIsig(i,1)=-1; elseif (RSI(i,1)>30)&&(RSI(i-1,1)<30) RSIsig(i,1)=1; endend RSIsig=nuRSI*RSIsig; RSIsigMX=[RSIMX,RSIsig]; %3.8 numbers of RSI signalaRSI=abs(RSIsig);numRSIsig=sum(aRSI); %4. Signal Combination %4.1 Plot the three parameters in the same figure %&&&&&&&PLOT&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&777777figuresubplot(3,1,1);plot(MAplot)ylabel('Price')
35
legend('Close','5-day Moving Average','20-day Moving Average')subplot(3,1,2); plot(KDplot)title('Stochastic %K%D')legend('%K','%D')subplot(3,1,3); plot(RSIband)title('RSI')legend('RSI','30','70')%&&&&&&&PLOT&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&777777 %4.2 Combine sigals into one matrixAllsig=[MAsig,KDsig,RSIsig];AllsigMX=[close,Allsig]; for i=1:m Tsig(i,1)=sum(Allsig(i,:));end TsigMX=[AllsigMX, Tsig]; %4.3 Only transition situationssigMX=[[1:m]',close,Tsig];sz=size(sigMX);sz=sz(1,2);trans=zeros(1,sz) ;for i=2:m if (Tsig(i)==1)||(Tsig(i)==-1)||(Tsig(i)==-2)||(Tsig(i)==2)||(Tsig(i)==3)||(Tsig(i)==-3) trans=[trans;sigMX(i,1:end)]; endendtrans=trans(2:end,:); %4.4 numbers of total trade signals[numsig c]=size(trans);clear c;numsig; %4.5 Considering that if the system provides more than one consecutive buy or%sell signals, we need to modify our "trans" matrix to reflect this fact.trsigOld=trans(:,end);trsig=zeros(numsig,1);trsig(1,1)=trsigOld(1,1);for i=2:numsig if trsigOld(i,1)*trsigOld(i-1,1)>0 trsig(i,1)=trsig(i-1,1)+trsigOld(i-1,1); else trsig(i,1)=trsigOld(i,1); endendtrsigMX=[trans,trsig]; %4.5 Therefore, we can create a new total signal listnewTsig=Tsig; for i=1:numsig j=trsigMX(i); newTsig(j,1)=trsig(i);endnewTsigMX=[sigMX,newTsig];
36
%5. P&L Calculation %5.1 To find the P&L we need to find the profit of each trade for i=1:numsigmktvalue(i,1)=trsigMX(i,2)*trsigMX(i,4);endmktvalueMX=[trsigMX,mktvalue]; %5.2 to find the net profit of each tradenetprofit(1,1)=0;for i=2:numsig netprofit(i,1)=-(mktvalue(i,1)+mktvalue(i-1,1));end %for the position of 100netprofit=netprofit*100;netprofitMX=[trans,mktvalue,netprofit]; %6. to find the largest winning trade and largest losing tradeLargestWin=max(netprofit); %(1)LargestLoss=min(netprofit); %(2) %7. to find the number of wintrade and losstradenumwin=0;numloss=0;for i=1:numsig if netprofit(i,1)>0 numwin=numwin+1; elseif netprofit(i,1)<0 numloss=numloss+1; endendnumwin; %(3)numloss ;%(4) %8. Find the GrossProfit and GrossLoss to calculate the Profit Factor GrossProfit=0;GrossLoss=0;for i=1:numsig if netprofit(i,1)>0 GrossProfit=GrossProfit+netprofit(i,1); elseif netprofit(i,1)<0 GrossLoss=GrossLoss+netprofit(i,1); endendGrossProfit;GrossLoss;CumuProfit=GrossProfit+GrossLoss;ProfitFactor=GrossProfit/(-GrossLoss); %(5) %9.Daily Mark-to-Market P&L and return %to find the daily return, we first calculate the actual daily market value %9.1 We make find our daily market positionactposi=zeros(m,1);for i=2:m if newTsig(i,1)==0
37
actposi(i,1)=actposi(i-1,1); elseif ((newTsig(i,1)<-0.1)||(newTsig(i,1)>0.1)) actposi(i,1)=newTsig(i,1); endendactposiMX=[newTsig,close,actposi]; %9.2 We make find our actual market values%for 100 positionsacctvalue=close*100;acctMX=[actposiMX,acctvalue]; %9.3 we calculate daily changes in our portfolio.shortV=zeros(m,1);longV=zeros(m,1); for i=2:m if acctMX(i-1,3)<0 shortV(i,1)=(acctMX(i,4)-acctMX(i-1,4))*acctMX(i-1,2); elseif acctMX(i-1,3)>0 longV(i,1)=(acctMX(i,4)-acctMX(i-1,4))*acctMX(i-1,2); endendacctMXX=[acctMX,longV,shortV]; %9.4 Daily Mark-to-Market P&L. Suppose our base is $1000000.M2MPL=zeros(m,1);M2MPL(1,1)=1000000;for i=2:m M2MPL(i,1)=longV(i,1)+shortV(i,1)+M2MPL(i-1,1);end M2MPLMX=[acctMXX,M2MPL]; %9.5 we calculate the daily returns based on the daily M2M P&L.dayreturn=zeros(m,1);for i=2:m dayreturn(i,1)=(M2MPL(i,1)-M2MPL(i-1,1))/M2MPL(i-1,1);enddayreturnMX=[M2MPLMX,dayreturn]; % 10. Sharpe Ratio (6)%%We assume that the risk-free rate is 0.stdday=std(dayreturn);stdannual=sqrt(stdday^2*256);ER=mean(dayreturn);ERannual=ER*256;%SharpeRatioDaily=ER/stdSharpeRatioAnnual=ERannual/stdannual; %11.Sortino Ratio (7)%%We assume that the risk-free rate is 0.%%11.1 Annulized Downside Standard Deviation downreturn=0;
38
for i=1:m if dayreturn(i,1)<0 downreturn=[downreturn;dayreturn(i,1)]; endenddownreturn=downreturn(2:end,:);stddown=std(downreturn);stddownannual=sqrt(stddown^2*256); %11.2 Calculation of Sortino RatioSortinoRatioAnnual=ERannual/stddownannual; %12.Expected Profit (8)%(Average Profit*Probability of Profit-Average Loss*Probability of Loss) (8) Gain=0;Loss=0; for i=1:numsig if netprofit(i,1)>0 Gain=[Gain;netprofit(i,1)]; elseif netprofit(i,1)<0 Loss=[Loss;netprofit(i,1)]; endendGain=Gain(2:end,:);Loss=Loss(2:end,:); AverageProfit=mean(Gain);ProbabilityofProfit=numwin/(numwin+numloss);AverageLoss=mean(Loss);ProbabilityofLoss=numloss/(numwin+numloss); ExpectedProfit=(AverageProfit*ProbabilityofProfit-AverageLoss*ProbabilityofLoss); %(8) %13.Return Retracement Ratio(9) %%13.1 We first find R, average annual compounded returnS=M2MPL(1,1);%starting equityE=M2MPL(end,1);%ending equityN=m/256;R=exp((1/N)*(log(E)-log(S)))-1;%%13.2 We calculate AMR%% We assume that each months has 22 trading days%%13.2.1 We find the equity at the end of each month.monthend=[22:22:m]';[monthnum w]=size(monthend);clear wEi=zeros(monthnum,1);for i=1:monthnum j=monthend(i,1); Ei(i,1)=M2MPL(j,1);endEiMX=[monthend, Ei]; %13.2.2 PEi and MEi
39
PEi=zeros(monthnum,1);PEi(1,1)=Ei(1,1); MEi=zeros(monthnum,1);MEi(1,1)=min(Ei); for i=2:monthnum PEi(i,1)=max(Ei(1:i,1)); MEi(i,1)=min(Ei(i:end,1));end PEMEMX=[Ei, PEi,MEi]; %13.2.2 MRPP,MRSL and MRMRPP=zeros(monthnum,1);MRSL=zeros(monthnum,1);MR=zeros(monthnum,1); for i=1:monthnum MRPP(i,1)=(PEi(i,1)-Ei(i,1))/PEi(i,1); MRSL(i,1)=(Ei(i,1)-MEi(i,1))/Ei(i,1); MR(i,1)=max(MRPP(i,1),MRSL(i,1)); end MRMX=[MRPP,MRSL,MR]; %13.2.3 AMRAMR=1/monthnum*(sum(MR)); %13.3 RRRRRR=R/AMR; %14. Calculate account mark-to-market P&L for each new price level%(row in excel) (10) AcctM2M=[M2MPLMX(:,1),M2MPLMX(:,3),M2MPLMX(:,2),M2MPLMX(:,5:end)]; %Result Summarydisp('Final Project II: Result Summary')LargestLoss LargestWin numloss numwin ProfitFactor SortinoRatioAnnual ExpectedProfit RRR disp('Important Note:')disp(' ')disp('The account mark-to-market P&L is saved in the variable names ACCTM2M') disp('Since it is really big,please type"AcctM2M" in MATLAB to see the matrix')disp(' ')disp('AcctM2M Column Labels:')disp('TradeSignal, AccountPostion, Close, M2MValueChangeOfLong, M2MValueChangeOfShort, M2MPL, M2MAccountValue')
40
Portfolio Optimization Model
---Efficiency Frontier by VBAResults for Equity Portfolio: Example Results:
Notes: Inputs can be changed to get different portfolio allocation resultsInputs:
ABT C GE IBM MSFT
Data: 05/02/97 to 05/01/07 Daily Close Price
30 points of Frontier
Add constraints stock # min wt. max. wt.
1 -1 12 -1 13 -1 14 -1 1
41
5 -1 1
Outputs: Historical stock return data
Expected returns & volatilitystock # ticker E[r]
1 ABT 0.93% 6.36%2 C 1.51% 8.48%3 GE 0.91% 6.72%4 IBM 1.20% 9.21%5 MSFT 1.29% 10.93%
Variance-covariance matrix ABT C GE IBM MSFTABT 0.40% 0.07% 0.10% 0.01% 0.06%C 0.07% 0.72% 0.28% 0.42% 0.30%GE 0.10% 0.28% 0.45% 0.26% 0.36%IBM 0.01% 0.42% 0.26% 0.85% 0.53%MSFT 0.06% 0.30% 0.36% 0.53% 1.20%
Efficiency Portfolio
0.00%
2.00%
4.00%
6.00%
8.00%
10.00%
12.00%
14.00%
0.00% 5.00% 10.00% 15.00% 20.00% 25.00%
Expected Returns
Vo
lati
litie
s
Minimum variance portfolio weights
p rp ABT C GE IBM MSFT w 4.83% 1.02% 0.4943 0.0873 0.2743 0.1424 0.0016 1Frontier points
p rp ABT C GE IBM MSFT w1 4.83% 1.02% 0.4943 0.0873 0.2743 0.1424 0.0016 2 6.51% 1.39% 0.3896 0.6480 -0.2431 0.0101 0.1955 1.00003 10.35% 1.76% 0.3005 1.0000 -0.9515 0.0935 0.5575 1.0000
42
4 19.70% 2.13% -0.8964 1.0000 -1.0000 0.8964 1.0000 1.00005 20.65% 2.50% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.00006 20.65% 2.87% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.00007 20.65% 3.24% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.00008 20.65% 3.61% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.00009 20.65% 3.98% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000010 20.65% 4.35% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000011 20.65% 4.72% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000012 20.65% 5.09% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000013 20.65% 5.46% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000014 20.65% 5.83% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000015 20.65% 6.20% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000016 20.65% 6.57% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000017 20.65% 6.94% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000018 20.65% 7.31% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000019 20.65% 7.68% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000020 20.65% 8.05% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000021 20.65% 8.42% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000022 20.65% 8.79% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000023 20.65% 9.16% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000024 20.65% 9.53% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000025 20.65% 9.90% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000026 20.65% 10.27% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000027 20.65% 10.64% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000028 20.65% 11.01% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000029 20.65% 11.38% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.000030 20.65% 11.75% -1.0000 1.0000 -1.0000 1.0000 1.0000 1.0000
Changing the Inputs by adding constrains:ABT C GE IBM MSFT
Data: 05/02/97 to 05/01/07 Daily Close Price
Add constraints stock # min wt. max. wt.
1 2 -1.5 1.53 -1 14 -1 15
Choose # of points on frontier30
Outputs Change to:Historical stock return data
Expected returns & volatilitystock # ticker E[r]
1 ABT 0.93% 6.36%2 C 1.51% 8.48%3 GE 0.91% 6.72%4 IBM 1.20% 9.21%5 MSFT 1.29% 10.93%
43
Variance-covariance matrix ABT C GE IBM MSFTABT 0.40% 0.07% 0.10% 0.01% 0.06%C 0.07% 0.72% 0.28% 0.42% 0.30%GE 0.10% 0.28% 0.45% 0.26% 0.36%IBM 0.01% 0.42% 0.26% 0.85% 0.53%MSFT 0.06% 0.30% 0.36% 0.53% 1.20%
Minimum variance portfolio weights
p rp ABT C GE IBM MSFT w 4.83% 1.02% 0.4943 0.0873 0.2743 0.1424 0.0016 1
Efficiency Portfolio
0.00%
2.00%
4.00%
6.00%
8.00%
10.00%
12.00%
14.00%
0.00% 50.00% 100.00% 150.00% 200.00% 250.00% 300.00% 350.00% 400.00%
Expected Returns
Vo
lati
litie
s
Frontier points
p rp ABT C GE IBM MSFT w1 4.83% 1.02% 0.4943 0.0873 0.2743 0.1424 0.0016 2 6.51% 1.39% 0.3896 0.6480 -0.2431 0.0101 0.1955 1.00003 9.97% 1.76% 0.2849 1.2087 -0.7605 -0.1223 0.3893 1.00004 15.08% 2.13% -0.3384 1.5000 -1.0000 -0.0464 0.8848 1.00005 25.03% 2.50% -1.4598 1.5000 -1.0000 0.2630 1.6968 1.00006 36.48% 2.87% -2.5811 1.5000 -1.0000 0.5724 2.5087 1.00007 48.37% 3.24% -3.7024 1.5000 -1.0000 0.8817 3.3207 1.00008 60.46% 3.61% -4.7746 1.5000 -1.0000 1.0000 4.2746 1.00009 72.73% 3.98% -5.8163 1.5000 -1.0000 1.0000 5.3163 1.000010 85.11% 4.35% -6.8580 1.5000 -1.0000 1.0000 6.3580 1.000011 97.56% 4.72% -7.8997 1.5000 -1.0000 1.0000 7.3997 1.000012 110.05% 5.09% -8.9413 1.5000 -1.0000 1.0000 8.4413 1.000013 122.57% 5.46% -9.9830 1.5000 -1.0000 1.0000 9.4830 1.0000
44
14 135.12% 5.83%-
11.0247 1.5000 -1.0000 1.0000 10.5247 1.0000
15 147.68% 6.20%-
12.0664 1.5000 -1.0000 1.0000 11.5664 1.0000
16 160.25% 6.57%-
13.1081 1.5000 -1.0000 1.0000 12.6081 1.0000
17 172.83% 6.94%-
14.1498 1.5000 -1.0000 1.0000 13.6498 1.0000
18 185.42% 7.31%-
15.1915 1.5000 -1.0000 1.0000 14.6915 1.0000
19 198.02% 7.68%-
16.2332 1.5000 -1.0000 1.0000 15.7332 1.0000
20 210.62% 8.05%-
17.2749 1.5000 -1.0000 1.0000 16.7749 1.0000
21 223.23% 8.42%-
18.3166 1.5000 -1.0000 1.0000 17.8166 1.0000
22 235.84% 8.79%-
19.3583 1.5000 -1.0000 1.0000 18.8583 1.0000
23 248.45% 9.16%-
20.4000 1.5000 -1.0000 1.0000 19.9000 1.0000
24 261.07% 9.53%-
21.4419 1.5000 -1.0000 1.0000 20.9419 1.0000
25 273.68% 9.90%-
22.4836 1.5000 -1.0000 1.0000 21.9836 1.0000
26 286.30% 10.27%-
23.5250 1.5000 -1.0000 1.0000 23.0250 1.0000
27 298.92% 10.64%-
24.5667 1.5000 -1.0000 1.0000 24.0667 1.0000
28 311.55% 11.01%-
25.6087 1.5000 -1.0000 1.0000 25.1087 1.0000
29 324.17% 11.38%-
26.6501 1.5000 -1.0000 1.0000 26.1501 1.0000
30 336.80% 11.75%-
27.6921 1.5000 -1.0000 1.0000 27.1921 1.0000
Code:'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Portfolio Effeciency Frontier VBA Code'' Daniel (Fei) Wang'' Financial Modeling Project''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Option Explicit
Dim j As Long, k As IntegerDim NumReturns As Long, Numstocks As IntegerDim rng_data As Range, rng_returns As Range, rng_returnticker As Range, rng_tickerlist As Range, rng_tickerchoice As Range
Private Sub MakeAllVisible()Dim wks As Worksheet, chrt As ChartFor Each wks In Worksheets wks.Visible = xlSheetVisibleNext wksFor Each chrt In Charts chrt.Visible = xlSheetVisibleNext chrtEnd Sub
45
Public Sub MainProgram()Application.ScreenUpdating = FalseApplication.DisplayAlerts = False Call CalcStockReturns Call CalcMeanReturns Call CalcVolatilities Call CalcCovarianceMatrix Call MinVariance Call ChoosePoints End Sub
Public Sub CalcStockReturns() Dim wks_wel As Worksheet, wks_data As Worksheet, wks_o As Worksheet, wks_returns As Worksheet Set wks_wel = Worksheets("Welcome") Set wks_data = Worksheets("Stock Price Data") Set wks_o = Worksheets("Optimization") 'Count how many Returns and Match the Date
Dim Date_1 As Double, Date_2 As Double, Rng_date As Range
Set wks_data = Worksheets("Stock Price Data") Set Rng_date = wks_data.Range("A7", "A32773") Set wks_returns = Worksheets("Returns") Set rng_data = wks_data.Range("A6") Set rng_returns = wks_returns.Range("A6")Date_1 = Worksheets("Optimization").Range("D7").ValueDate_2 = Worksheets("Optimization").Range("D8").Value
Dim Sdate As Integer, Edate As IntegerSdate = Application.WorksheetFunction.Match(Date_1, Rng_date, 0)Edate = Application.WorksheetFunction.Match(Date_2, Rng_date, 0)NumReturns = Edate - Sdate + 1wks_returns.Range("A5").Value = NumReturns
'input selected datesFor j = 0 To NumReturns - 1 rng_returns.Offset(j + 1, 0).Value = rng_data.Offset(j + Sdate, 0).ValueNext j
'input date and ticker title For k = 0 To 5 rng_returns.Offset(0, k) = rng_data.Offset(0, k) Next k
For j = 1 To NumReturns - 1'calculate first column of expected return For k = 1 To 5 rng_returns.Offset(j + 1, k) = ((rng_data.Offset(j + 1 + (Sdate - 1), k) - rng_data.Offset(j + (Sdate - 1), k)) / rng_data.Offset(j + (Sdate - 1), k)) Next kNext j
End Sub
Public Sub CalcMeanReturns()
46
Dim wks_wel As Worksheet, wks_data As Worksheet, wks_o As Worksheet, wks_returns As Worksheet Set wks_wel = Worksheets("Welcome") Set wks_data = Worksheets("Stock Price Data") Set wks_o = Worksheets("Optimization") Set wks_returns = Worksheets("Returns") Dim i As Integer, j As Integer, k As Integer, rng_in As Range, rng_out As Range, rng_returnticker As Range, rng_tickerlist As Range, rng_tickerchoice As RangeSet rng_in = wks_returns.Range("A8")Set rng_out = wks_returns.Range("H7")Set rng_returnticker = wks_returns.Range("H6")Set rng_tickerlist = Worksheets("Optimization").Range("C32")Set rng_tickerchoice = Worksheets("Optimization").Range("D12")
For i = 1 To 5
'Calculate annual mean on the "Return" worksheet ( paste the result of the calculation of the Average return to 5 right columns) With Worksheets("returns") rng_out.Cells(1, i) = Application.WorksheetFunction.Average(Range(rng_in.Offset(0, i), rng_in.Offset(0, i).End(xlDown))) rng_returnticker.Cells(1, i) = wks_returns.Range("A6").Offset(0, i) ' Worksheets("Returns").Range("G7").Value = "Mean" End With 'Display and Pasta the ticker list base on the user's choice With Worksheets("Optimization") rng_tickerlist.Cells(i, 1).Value = rng_tickerchoice.Cells(i, 1).Value End WithNext i
'Paste return base on the tickerlist, match the tickerlist("optimization") with the tickers from the ("returns")'if value is the same, so paste the expected return to the right columnWith Worksheets("Optimization") For j = 1 To 5 For k = 1 To 5 If rng_tickerlist.Cells(k, 1).Value = rng_returnticker.Cells(1, j).Value Then ''Macth the ticker name on the optimization sheet From the return sheet rng_tickerlist.Cells(k, 2).Value = rng_returnticker.Cells(2, j).Value ElseIf rng_tickerlist.Cells(k, 1).Value = 0 Then 'Leave the cell to be blank rng_tickerlist.Cells(k, 2).Value = 0 End If Next k Next jEnd WithEnd Sub
Public Sub CalcVolatilities()Dim i As Integer, j As Integer, k As Integer, rng_in As Range, rng_out As Range, rng_returnticker As Range, rng_tickerlist As RangeDim wks_optimization As Worksheet, wks_returns As Worksheet
Set wks_returns = Worksheets("returns")Set wks_optimization = Worksheets("Optimization")Set rng_in = wks_returns.Range("A8")Set rng_out = wks_returns.Range("H8")Set rng_tickerlist = wks_optimization.Range("C32")
47
Set rng_returnticker = wks_returns.Range("H6")
'on the return worksheet to caculate the Volatilities and paste to the 5 right Columns
With wks_returns .Range("G8").Value = "Volatilities" For i = 1 To 5 rng_out.Cells(1, i) = Application.WorksheetFunction.StDevP(Range(rng_in.Offset(0, i), rng_in.Offset(0, i).End(xlDown))) 'rng_out.Cells(1, i) = Application.WorksheetFunction.StDevP(rng_in.Offset(0, i), rng_in.Offset(0, i).End(xlDown)) Next i
End With
'Paste volatilities base on the tickerlist, match the tickerlist("optimization") with the tickers from the ("returns")'if value is the same, so paste the Volatilities to the second right column
With Worksheets("Optimization") For j = 1 To 5 For k = 1 To 5 If rng_tickerlist.Cells(k, 1).Value = rng_returnticker.Cells(1, j).Value Then rng_tickerlist.Cells(k, 3).Value = rng_returnticker.Cells(3, j).Value ElseIf rng_tickerlist.Cells(k, 1).Value = 0 Then rng_tickerlist.Cells(k, 3).Value = 0 End If Next k Next jEnd WithEnd Sub
Private Sub CalcCovarianceMatrix()Dim i As Integer, j As Integer, k As Integer, p As Integer, m As Integer, n As Integer, o As Integer, Numstocks As IntegerDim rng_in As Range, rng_out As Range, rng_tickerlist As Range, rng_ticker As Range, rng_matrix As RangeDim wks_optimization As Worksheet, wks_returns As WorksheetDim rng1 As Range, rng2 As Range, rng_Stickerlist As Range, rng_Htickerlist As RangeDim tickers As RangeSet wks_optimization = Worksheets("Optimization")Set wks_returns = Worksheets("returns")Set rng_in = wks_returns.Range("A8")Set rng_out = wks_returns.Range("H10")Set rng_ticker = wks_returns.Range("G10", "G14")Set rng_tickerlist = wks_optimization.Range("C32")Set rng_matrix = wks_optimization.Range("H32")
'get the row and column name for the return matrix on the optimization SheetFor o = 1 To 5Set rng_Stickerlist = wks_optimization.Range("G32")Set rng_Htickerlist = wks_optimization.Range("H31")rng_Stickerlist.Cells(o, 1).Value = rng_tickerlist.Cells(o, 1).Valuerng_Htickerlist.Cells(1, o).Value = rng_tickerlist.Cells(o, 1).ValueNext o'Caculate the return matrix for five Stocks on the return sheetFor j = 1 To 5 Set rng1 = Range(rng_in.Offset(0, j), rng_in.Offset(0, j).End(xlDown)) For i = 1 To 5 Set rng2 = Range(rng_in.Offset(0, i), rng_in.Offset(0, i).End(xlDown)) rng_out.Cells(j, i) = Application.WorksheetFunction.Covar(rng1, rng2)
48
Next i rng_out.Offset(j - 1, -1) = rng_in.Offset(-2, j) rng_out.Offset(-1, j - 1) = rng_in.Offset(-2, j)Next j'paste the return Matrix based on the users' choiceDim a As Integer, b As IntegerFor n = 1 To 5 For m = 1 To 5 If rng_matrix.Offset(-1, n - 1).Value = rng_out.Offset(-1, m - 1).Value Then For a = 1 To 5 For b = 1 To 5 If rng_matrix.Offset(a - 1, -1).Value = rng_out.Offset(b - 1, -1).Value Then rng_matrix.Cells(a, n).Value = rng_out.Cells(b, m).Value End If Next b Next a End If Next m Next nEnd Sub
Sub ClearOutputs() Worksheets("Optimization").Activate Range(Range("C32"), Range("E36")).ClearContents Range(Range("G31"), Range("L36")).ClearContents Range(Range("E40"), Range("I40")).ClearContents Range(Range("E43"), Range("I43")).ClearContentsDim rng_WholeMatrix As Range, i As IntegerSet rng_WholeMatrix = Range("H32") For i = 1 To 5 For j = 1 To 5 rng_WholeMatrix.Cells(j, i).Value = 0 Next j Next i
Range(Range("C41"), Range("J41")).ClearContents Range(Range("C44").Offset(0, 0), Range("C44").End(xlDown).End(xlToRight)).ClearContents Worksheets("Returns").Activate Worksheets("Returns").Cells.Clear Charts("Frontier Chart").Visible = FalseEnd Sub
Sub ClearInputs() Range(Range("D7"), Range("D8")).ClearContents Range(Range("D12"), Range("D16")).ClearContents Range(Range("H12"), Range("I16")).ClearContents Range("C19").ClearContents Charts("Frontier Chart").Visible = FalseEnd Sub
Sub ClearAll() Call ClearInputs Call ClearOutputs End Sub
49
Private Sub MinVariance()Dim i As Integer, j As Integer, n As Integer, Numstocks As Integer, index As IntegerDim MinVarWts As Range, rng_tickerlist As Range, ExpReturns As Range, CovarMatrix As Range, MinVarRet As Range, MinVar As RangeDim WName As Range ' rng_Dataticker As Range'Set rng_Dataticker = Worksheets("stock price data").Range("B6", "F6")Set rng_tickerlist = Worksheets("Optimization").Range("C32", "C36")'Count stocks available, use worksheet countBlank Functionn = Application.WorksheetFunction.CountBlank(rng_tickerlist)Numstocks = 5 - n
Set WName = Worksheets("Optimization").Range("E40")Set MinVarWts = Worksheets("Optimization").Range(Range("E41"), Range("E41").Cells(1, Numstocks))Set ExpReturns = Worksheets("Optimization").Range(Range("D32"), Range("D32").Cells(Numstocks, 1))Set CovarMatrix = Worksheets("Optimization").Range(Range("H32"), Range("H32").Cells(Numstocks, Numstocks))Set MinVarRet = Worksheets("Optimization").Range("D41")Set MinVar = Worksheets("Optimization").Range("C41")
'Paste Stock Names based on the user's selectionDim m As IntegerFor m = 1 To 5WName.Cells(1, m) = rng_tickerlist.Cells(m, 1)WName.Cells(4, m) = rng_tickerlist.Cells(m, 1)Next m
'Dim a As Integer'For a = 1 To 5'If WName.Cells(1, a) = 0 Then'WName.Cells(1, a).Select'Selection.Delete Shift:=xlToLeft'End If'Next a
With Worksheets("Optimization")'Input initial weights equally With rng_tickerlist For i = 1 To 5 If .Cells(i, 1) <> 0 Then MinVarWts.Cells(1, i) = 1 / Numstocks Else MinVarWts.Cells(1, i) = 0 End If Next i End With
'Find the first selected stock's index' With Range("MinVarWts")' For j = 1 To 5' If .Cells(1, j) <> 0 Then' index = j' Exit For' End If' ' Next j'' End With
MinVarRet.FormulaArray = "=sumproduct(Transpose(MinVarWts), ExpReturns)"MinVar.FormulaArray = "=(MMult(MinVarWts ,MMult(CovarMatrix, Transpose(MinVarWts))))^0.5"
50
Range("J41").FormulaR1C1 = "=SUM(MinVarWts)"
Range(Range("E41").Cells(1, 1), Range("E41").Cells(1, 1 + Numstocks - 1)).Name = "MinWts"'Range("J41").Value = Application.WorksheetFunction.Sum(Range("E41"), Range("F41"), Range("G42"), Range("H42"), Range("I42"))
SolverResetSolverOk SetCell:=Range("MinVar"), MaxMinVal:=2, ByChange:=("MinVarWts")solveradd cellref:=Range("J41"), Relation:=2, FormulaText:=1.00000000001
SolverOptions AssumeNonNeg:=FalseSolverSolve UserFinish:=True
End WithEnd Sub
Private Sub ChoosePoints()Dim Wts2 As Range, Exp2 As Range, Stdev2 As Range, rng_tickerlist As Range, ExpReturns As RangeDim h As Integer, i As Integer, j As Integer, k As Integer, Point As Integer, n As Integer, Numstocks As Integer, index As IntegerSet Wts2 = Worksheets("Optimization").Range("E45")Set Exp2 = Worksheets("Optimization").Range("D45")
Set rng_tickerlist = Worksheets("Optimization").Range("C32", "C36")Set ExpReturns = Worksheets("Optimization").Range("D32", "D36")
'use the count Blank Founction to get the number of the stocks the user's choicen = Application.WorksheetFunction.CountBlank(rng_tickerlist)Numstocks = 5 - n
'Choose points on frontierPoint = Worksheets("Optimization").Range("NumPoints").Value
With Worksheets("Optimization")'Copy the min variance row result first For i = 1 To 7 .Range("C44").Cells(1, i) = .Range("C41").Cells(1, i) Next i
For i = 1 To Point - 1
'Setting initial weights for every point For k = 1 To 5 If Range("C32").Cells(k, 1) <> 0 Then Range("MinVarWts").Cells(i + 4, k) = 1 / Numstocks Else Range("MinVarWts").Cells(i + 4, k) = 0 End If Next k 'Range("J41").Cells(3 + i, 1).Value = Application.WorksheetFunction.Sum(Range("E44").Cells(i, 1), Range("E44").Cells(i, 5))'Find the first selected stock's index' With Range("MinVarWts") ' For j = 1 To 5 ' If .Cells(1, j) <> 0 Then ' index = j ' Exit For ' End If
51
' Next j ' End WithDim SumW As RangeSet SumW = Worksheets("Optimization").Range("J45")Set Stdev2 = Worksheets("Optimization").Range("C45")'Name every row of weights Range(Stdev2.Cells(i, 3), Stdev2.Cells(i, 7)).Name = "Weight" & (i + 1)'Input formula for Stdev cell Stdev2.Cells(i, 1).FormulaArray = "= MMult(Weight" & (i + 1) & ", MMult(CovarMatrix, Transpose(Weight" & (i + 1) & ")))^0.5 "
'Adding Expected Returns by Ascending sequence as Target Range("D45").Offset(i - 1, 0) = Range("D45").Offset(i - 2, 0) + 0.0037
'For expected returns which should be adjusted Range("K41").Offset(i + 3, 0).FormulaArray = "=sumproduct(transpose(Weight" & (i + 1) & "), ExpReturns)"
'Name every row of weights with non-zero value (for solver adjusting) Range(Range("E45").Cells(i, 1), Range("E45").Cells(i, 1 + Numstocks - 1)).Name = "Wts" & (i + 1) 'Input formula for sum of the weightsSumW.Cells(i, 1).Formula = "=Sum(Weight" & (i + 1) & ")"
'solver efficient frontierSolverResetSolverOk SetCell:=Range("MinVar").Offset(i + 3, 0), MaxMinVal:=2, ByChange:=("Wts" & (i + 1) & "")solveradd cellref:=Range("J41").Offset(i + 3, 0), Relation:=2, FormulaText:=1.00000000001solveradd cellref:=Range("K41").Offset(i + 3, 0), Relation:=2, FormulaText:=Range("MinVarRet").Offset(i + 3, 0)
Dim c As IntegerFor c = 1 To NumstocksIf Range("H12").Cells(c, 1) <> "" Thensolveradd cellref:=Range("E45").Cells(i, c), Relation:=3, FormulaText:=Range("H12").Cells(c, 1).AddressEnd IfIf Range("H12").Cells(c, 2) <> "" Thensolveradd cellref:=Range("E45").Cells(i, c), Relation:=1, FormulaText:=Range("H12").Cells(c, 2).AddressEnd IfNext c
'Add constraints' For h = 1 To Numstocks ' If Range("H12").Cells(h, 1) <> "" And Range("H12").Cells(h, 2) <> "" Then ' SolverAdd CellRef:=Range("E41").Offset(i + 3, h - 1), Relation:=3, FormulaText:=Range("H12").Cells(h, 1).Address ' SolverAdd CellRef:=Range("E41").Offset(i + 3, h - 1), Relation:=1, FormulaText:=Range("H12").Cells(h, 2).Address ' ' ElseIf Range("H12").Cells(h, 1) = "" And Range("H12").Cells(h, 2) <> "" Then ' SolverAdd CellRef:=Range("E41").Offset(i + 3, h - 1), Relation:=1, FormulaText:=Range("H12").Cells(h, 2).Address ' ElseIf Range("H12").Cells(h, 1) = "" And Range("H12").Cells(h, 2) <> "" Then ' SolverAdd CellRef:=Range("E41").Offset(i + 3, h - 1), Relation:=1, FormulaText:=Range("H12").Cells(h, 1).Address ' Else
52
' Exit For ' End If
' Next h
SolverOptions AssumeNonNeg:=FalseSolverSolve UserFinish:=True
Range("K41").Offset(i + 3, 0).ClearContents
Next iEnd With
Charts("Frontier Chart").Visible = TrueCharts("Frontier Chart").Activate
End Sub
53
Final Report For Market Risk Management
Problem (1) Very Simple Portfolio VaR:
First, we begin to manage our data:
From the raw data, we found the TSE 3000 is in CAD currency, so we change the TSE 3000 into the US Dollar by applying the CAD/USD exchange rate. ( TSE 3000 in USD = TSE in CAD / exchange rate CAD/USD )
Chart 1 -----Percentage Movement of the Data
0
50
100
150
200
250
1 97 193 289 385 481 577 673 769 865 961 1057 1153 1249
S&P500
T-Bill
$/Yen
Oil Price
TSE300(USD)
From the chart 1, we plot the percentage term of the data to check there is no serious jump in the data. Then for each instrument, we calculate the log return for the time series data and access five columns of log returns for these assets. Moreover, I plot these returns data separately as follow to find the trend of the data:
54
S&P500 Log Returns
-0.08
-0.06
-0.04
-0.02
0
0.02
0.04
0.06
1 53 105 157 209 261 313 365 417 469 521 573 625 677 729 781 833 885 937 989 1041 1093 1145 1197 1249 S&P500
T-Bill Log Returns
-0.01
-0.005
0
0.005
0.01
0.015
1 59 117 175 233 291 349 407 465 523 581 639 697 755 813 871 929 987 1045 1103 1161 1219
T-Bill
$/Yen Log Returns
-0.04
-0.02
0
0.02
0.04
0.06
0.08
1 51 101 151 201 251 301 351 401 451 501 551 601 651 701 751 801 851 901 951 1001 1051 1101 1151 1201 1251
$/Yen
Oil Price Log Returns
-0.2
-0.15
-0.1
-0.05
0
0.05
0.1
0.15
1 58 115 172 229 286 343 400 457 514 571 628 685 742 799 856 913 970 1027 1084 1141 1198 1255 Oil Price
TSE300(USD) Log Returns
-0.1
-0.08
-0.06
-0.04
-0.02
0
0.02
0.04
0.06
1 66 131 196 261 326 391 456 521 586 651 716 781 846 911 976 1041 1106 1171 123 TSE300(USD)
55
Second, I begin with an approach called Mean-Variance Approximation
(a) By function COVAR ( ) to get the unconditional covariance matrix of these five assets, and also by using Sqrt (covar (two same asset time series) to calculate the volatility, so we get:
Covariance MatrixS&P500 T-Bill $/Yen Oil Price TSE300(USD)
S&P500 0.000158480 -0.000002049 -0.000006313 -0.000010825 0.000116993T-Bill 0.0000020493 0.0000009586 0.0000004778 0.0000007805 0.0000021167$/Yen -0.000006313 -0.000006313 0.000065685 0.000014431 0.0000030408
Oil Price 0.0000108249 -0.000010825 0.000014431 0.000672567 0.0000133742TSE300(USD) 0.000116993 0.000116993 0.000003041 0.000013374 0.000175618 The Volatility 0.012588886 0.000979092 0.008104606 0.025933887 0.013252103
Then I continuous to calculate the unconditional correlation matrix as follow:
Correlation Matrix S&P500 T-Bill $/Yen Oil Price TSE300(USD)
S&P500 1 0.166260364 0.061877759 0.033156675 0.70127346T-Bill 0.166260364 1 -0.06021044 0.030740045 -0.163137824$/Yen -0.061877759 -0.06021044 1 0.068660406 0.028312319
Oil Price -0.033156675 0.030740045 0.068660406 1 0.038914816TSE300(USD) 0.70127346 0.163137824 0.028312319 0.038914816 1
Furthermore, I implement the weights from:Portfolio Weights
S&P500 T-Bill $/Yen Oil Price TSE300(USD)Weights in USD 40,000,000 25,000,000 25,000,000 35,000,000 25,000,000
Weights in % 40.00% 25.00% -25.00% 35.00% 25.00%
From the equation: Volatility in Percentage Term of the Portfolio =sqrt (transpose (Percentage Weights) *Covariance Matrix * Percentage Weights))
So, 1-day, 99% % VaR of the portfolio = - Volatility in Percentage Term of the Portfolio * sqrt (1) *NormSInv (0.99) = - 2.8504%
Also, Volatility in Dollar Term of the Portfolio =sqrt (transpose (Dollar Amount Weights) *Covariance Matrix * Dollar Amount Weights))
So, 1-day, 99% % VaR of the portfolio = - Volatility in Percentage Term of the Portfolio * sqrt (1) *NormSInv (0.99) = $ - 2,850,430.78
(b) The Individual VaR for 1-day, 99% in Dollar Terms as follow:
$ VaR of S&P = - 0.012588886*40,000,000* sqrt (1) *NormSInv (0.99) = - $ 1,171,444.70 $ VaR of T-Bill = - 0.000979092* 25000000* sqrt (1) *NormSInv (0.99) = - $ 56,942.67 $ VaR of $/Yen = - 0.008104606*(-25,000,000)* sqrt (1) *NormSInv (0.99) = - $ 471,353.17$ VaR of Oil Price = - 0.025933887*35,000,000* sqrt (1) *NormSInv (0.99) = - $2,111,592.73 $ VaR of TSE in USD = - 0.01325210*25,000,000* sqrt (1) *NormSInv (0.99) = - $ 770,724.77
The Sum of these is - $ 4,582,058.05 which is bigger than the portfolio number, because by combining these short and long position, the short position in the (a) more or less decrease the Value of Risk, and the sum of individual VaR is just adding these absolute value together. So obviously, the Sum of individual VaR is more than the portfolio VaR.
56
(c) To calculate S$P VaR for 10-Days, 99% with non-zero meanFirst, we find the mean of S&P returns = 0.000347643 Then, I use the formula as follow:10-day, 99% $ VaR for S&P=- (0.000347643 *10 + 0.01258889* sqrt (10) *2.33) *40,000,000= - $3,843,490.61
(d) Because, the portfolio holding in oil future increases by another 25%, then the future holding amount becomes 35000000*(1+0.25) = 43,750,000
So the Weights matrix changes to :
Portfolio WeightsS&P500 T-Bill $/Yen Oil Price TSE300(USD)
Weight in USD 40,000,000 25,000,000 -25,000,000 43,750,000 25,000,000
Weight in % 0.37 0.23 (0.23) 0.40 0.23
From the Formula:
New Portfolio Volatility in $ terms =sqrt (transpose (New Weight matrix) *Covariance Matrix * New Weight Matrix))
1-day, 99% $ VaR of the New Portfolio = - New Portfolio Volatility * sqrt (1) *NormSInv (0.99) = -3,252,044.517
Incremental Overnight VaR = New Portfolio $VaR – Old Portfolio $VaR
=-(ABS(-3,252,044.517)-ABS(-2,850,430.78)))
= -401,613.7327 in Dollar Term
Furthermore, for calculating the VaR on 2nd January, GARCH Model can be applied: First, we use the GARCH method into the SP 500 time series calculation and then these will be the same for the other assets:
(a)
We calculate the log return for S&P 500 which is same as previous talked about, and then, we can acquire the daily variance by assuming the Omega, Alpha and Beta’s value: = 0.0002, = 0.1 and =0.8, The first variance equals to the square of the first return, Moreover,
Daily Variance of day N = + * (Daily Return of N-1 day) ^2 + * Daily Variance of N-1 day
We add a vector of log likelihoods.
Then, to find the accurate the Omega, Alpha and Beta’s value, I maximize the total log likelihood and use Excel Solver by adding constrains which are Alpha >=0 and Alpha + Beta <= 0.999999999.
Furthermore, we get the value for Omega =0.00001135, Alpha =0.10109087, Beta =0.82949528.
57
Then, by inputting the new Omega, Alpha and Beta’s value, I find the return and variance of the Dec 31st 2002.
Finally, by applying to the GARCH formula, I obtain the volatility for the next trading day Jan 2nd 2003, which is 0.01006609
For T-Bill, TSE index, Oil Future and Japanese Yen, I use the same method:
So I got:
The volatility for the next trading day Jan 2nd of T-Bill is 0.001487694The volatility for the next trading day Jan 2nd of $/Yen is 0.006323223The volatility for the next trading day Jan 2nd of Oil Price is 0.033930332The volatility for the next trading day Jan 2nd of TSE in USD is 0.010276841
From the unconditional correlation matrix in Mean-Variance approximation, I combine with the volatility calculated by the GARCH Model to obtain the GARCH Volatility Variance and Covariance Matrix.
GARCH S&P500 T-Bill $/Yen Oil Price TSE300(USD)
Volatility 0.01006609 0.00148769 0.006323223 0.0339303 0.0102768
Variance 0.000101326 0.00000221323 0.000039983143 0.001151267 0.00010561
GARCH S&P500 T-Bill $/Yen Oil Price TSE300(USD)S&P500 0.0001013 -0.0000025 -0.0000039 -0.0000113 0.0000725T-Bill -0.0000025 0.0000022 -0.0000006 -0.0000016 -0.0000025$/Yen -0.0000039 -0.0000006 0.0000400 0.0000147 0.0000018Oil Price -0.0000113 -0.0000016 0.0000147 0.0011513 0.0000136TSE300 0.0000725 -0.0000025 0.0000018 0.0000136 0.0001056
Adding Weighs as follows:S&P500 T-Bill $/Yen Oil Price TSE300(USD)
Weight in USD 40,000,000 25,000,000 -25,000,000 35,000,000 25,000,000Weight
in % 0.40 0.25
(0.25)
0.35
0.25
From the equation: Volatility in Percentage Term of the Portfolio =sqrt (transpose (Percentage Weights) *Covariance Matrix * Percentage Weights))
So, 1-day, 99% % VaR of the portfolio = - Volatility in Percentage Term of the Portfolio * sqrt (1) *NormSInv (0.99) = -0.030964254
Also, Volatility in Dollar Term of the Portfolio =sqrt (transpose (Dollar Amount Weights) *Covariance Matrix * Dollar Amount Weights))So, 1-day, 99% % VaR of the portfolio = - Volatility in Percentage Term of the Portfolio * sqrt (1) *NormSInv (0.99) = -$ 3,096,425.43
(b) So the Individual VaR by adding GARCH for 1-day, 99% in Dollar Terms as follow:
$ VaR of S&P = - 0.01006609*40,000,000* sqrt (1) *NormSInv (0.99) = - $ 936,688.77 $ VaR of T-Bill = - 0.001487694* 25000000* sqrt (1) *NormSInv (0.99) = - $ 86,522.32 $ VaR of $/Yen = - 0.006323223*(-25,000,000)* sqrt (1) *NormSInv (0.99) = - $ 67,750.25$ VaR of Oil Price = - 0.033930332*35,000,000* sqrt (1) *NormSInv (0.99) = - $ 2,762,680.42
58
$ VaR of TSE in USD = - 0.010276841*25,000,000* sqrt (1) *NormSInv (0.99) = - $ 597,687.45
(c) To calculate S$P VaR for 10-Days, 99% with non-zero mean
First, we find the mean of S&P returns = 0.000347643 which is the same as Mean-VarianceThen, I use the formula as follow:
10-day, 99% $ VaR for S&P=- (0.000347643 *10 + 0.01006609* sqrt (10) *2.33) *40,000,000= - $3,101,127.158
(d)Because, the portfolio holding in oil future increases by another 25%, then the future holding amount becomes 35000000*(1+0.25) = 43,750,000So the Weights matrix changes to :
Portfolio WeightsS&P500 T-Bill $/Yen Oil Price TSE300(USD)
Weight in USD 40,000,000 25,000,000 -25,000,000 43,750,000 25,000,000
Weight in % 0.37 0.23 (0.23) 0.40 0.23
From the Formula:
New Portfolio Volatility in $ terms =sqrt (transpose (New Weight matrix) *Covariance Matrix * New Weight Matrix))
1-day, 99% $ VaR of the New Portfolio = - New Portfolio Volatility * sqrt (1) *NormSInv (0.99) = - $ 3,719,106.35
Incremental Overnight VaR = New Portfolio $VaR – Old Portfolio $VaR=-(ABS(-$ 3,719,106.35)-ABS(-$ 3,096,425.43)))= -622,680.9204in Dollar Term
(e)
i)
By the information of the three stock, we first calculate the Covariance Matrix as follow:
Covariance Matrix
0.0225 0.009 0.00120.009 0.0144 0
0.0012 0 0.0001
Weights:
0.222222 0.333333 0.444444
By adding Weights vector and the method from the previous calculation:
The volatility of the individual stock method is $2,951,271.
1-day, 99% $ VaR of this Portfolio = - Volatility * sqrt (1) *NormSInv (0.99) = - 6865680
ii)
59
By assuming the Volatility is Daily, then
Nevertheless, By VaR based on a mapping into the S&P Index using the stock Betas, we got
Volatility = MVx * beta(x) * Vol of SP + MVx * beta(x) * Vol of SP + MVx * beta(x) * Vol of SP = 10,000,000*1.4*0.07+15000,000 * 1.2 *0.07 + 20,000,000*0.8*0.07 =$ 3,360,000
1- day, 99% $ VaR of this Portfolio = - Volatility * sqrt (1) *NormSInv (0.99) = - 7816526
In conclusion:
The second VaR is larger than the first one, because the first one assume the firm specific component risk can by diversified away, and the second one has the exposure to individual component risk.
Problem 2.
Before doing this problem, I start with identifying the risk factors:
There are two different risk factors for bonds and options: For bonds, the risk factor is yield.For options, the risk factor is underlying assets.
Because the bonds and options are based on two different underlying assets and bond holding and the option positions are not correlated at all, we can calculate the VaR separately.
First, I calculate the bond’ VaR by implementing linear approach:
We know that bond Value = $ 6 million, duration = 5.2, volatility = 0.09%. Then,
$VaR of the bond = - 5.2 * 0.09% * sqrt (20) * NormSInv (0.95) * $ 6,000,000 = -206556.715
Second, I apply the Quadratic Cornish-Fisher VaR calculation into the OptionsWe know that option value = $ 4 million, delta =12000, gamma = -2600, the underlying stock price = $ 10, the volatility = 2%/day
Then we need to calculate the Cornish-Fisher Mean, Cornish-Fisher Variance, and Cornish-Fisher Skewness to plug into Cornish-Fisher VaR Calculation Formula:
So, Cornish-Fisher Mean = 0.5 * Gamma* Underlying Price^2 * Vol^2 * T= - 1040
And,Cornish-Fisher Variance = Delta^2 * Underlying Price^2 * Vol^2 * T + 0.5* Gamma^2 * Underlying Price^4 * Vol^4 * T^2= 117363200
Moreover,Cornish-Fisher Skewness= 1/(Cornish-Fisher Variance^1.5) * (9/2*Delta^2 * Gamma * Underlying Price^4 * Vol^4 * T^2 + 15/8 * Gamma^3 * Underlying Price^6 * Vol^6 * T ^3 + 3 * (Delta^2 * Underlying Price^2 * Vol^2 * T+ ¾ * Gamma^2 * Underlying Price^4 * Vol^4 * T^2 ) * Cornish-Fisher Mean + 2* Cornish-Fisher Mean^3 )= -0.572456024
60
$VaR of the option = -abs(-1040 + sqrt (117363200)*(1.645+ 1/6*((1.645) ^2-1)* -0.57245602) ) = -15016.538
Also, because the correlation is zero;
Finally, I combined them together to get the Portfolio VaR as:
$VaR of Portfolio = sqrt ($VaR of the bond^2 + $VaR of the option^2 + 2* $VaR of the bond *$VaR of the option * Correlation)= - $207,101.84
Problem 3 VaR Mapping
Result for Problem 3 is the 10-day, 95% confidence lever VaR for this portfolio using standardized positions is $ 9,935.065078.
Because the bond pays semiannual coupon payments at the 0.3year and 0.8year time points, with $1 million principal and 8% annual coupon rates( which is 4% semiannually ), I get the Cash flow for 0.3 and 0.8 year as follow:
Then, I begin the Cash Flow Mapping Procedure as:First, for the -40,000 paid on 0.3 year, we incorporate the 3-month rate of 4.5% and 6-month rate of 5% from the standardized position to get the 0.3 year rate of 4.6%. ( 5% - (5%-4%)*(0.5-0.3)/(0.5-0.25) ). And then, the present value of the cash flow to be paid in 0.3 year is -40000/(1+4.6%)^0.3 = -39463.94. We also get between the 0.05% volatility for the 3-month bond and the 0.1% volatility for the 6-month bond to get a 0.06% volatility for the 0.3 year bond. ( 0.1% - (0.1%-0.05%)*(0.5-0.3)/(0.5-0.25) ).
Furthermore, I begin allocate an of the present value to the 0.25 year bond and (1-Alpha) of the present value to the 0.5 year bond. By using equation and matching variances we obtain an equation as follow: 0.06%^2 = 0.05%^2 * ^2+ 0.1%^2 *(1- ) ^2 +2 * 0.85 * 0.05% * 0.1%* *(1-)and I use solver from excel to solve this equation, then I got the result of which is 0.754560581, and 1 - 0.24543942. So, the 75.4560581% should be allocated to a 3-month zero coupon bond, and 24.543942% should be allocated to a 6-month zero coupon bond.
Finally, by the standardized position, the standardized 3-month bond is$-39463.94 * 75.4560% = $ -29777.9365
And a 6-month bond worth $-39463.94 * 24.5439% = $ - 9686.00748
Then, I use the same method to calculate the 10400000 cash flow into the standardized zero coupon bonds, and the only difference here is by incorporating the 104000000 into 6-month and 1-year position, I got the following results:
6 month 1 year
Weights 0.342095576 0.657904424
Position by Incorporate -
340603.9367-
655035.7621
Time Total CF0.3 -400000.8 -1040000
61
Obviously, the 10400000 cash flow is mapped into a position worth $-340603.9367 in a 6-month bond and a position worth $ -655035.762 in a 1-year bond.
I summarize the result as:
Cash Flow Mapping Summary in dollar terms Sum
3ms -29777.9365 -29777.93656ms -9686.007481 -340603.9367 -350289.94411yr -655035.7621 -655035.7621
In conclusion, the short position in U.S. Treasury bond Portfolio is mapped into a position $ -29777.93 in a 3-month bond, a position $ -350289.9 in a 6-month bond, a position $ -655035.76 in a 1-year bond.
Then combine the vector of sum of cash flow result and the price covariance matrix (by using the bond price volatility and correlation matrix):
Standardized Position Covariance Matrix
Maturity 0.25 0.5 1
0.25 0.00000025 0.00000043 0.000000810.5 0.00000043 0.00000100 0.00000175
1 0.00000081 0.00000175 0.00000625
Cash Flow VectorSum
-29777.9365-350289.9441-655035.7621
Using the formula: Variance of the Portfolio = sqrt (transpose (Position Matrix) * Bond price Covariance Matrix * Position Matrix)= $ 3648270.225
Volatility of the Portfolio = sqrt (Variance of the Portfolio) = $ 1910.044561
$ VaR of the Portfolio = - 1910.04 * sqrt (10) * NormSInv (0.05) = $ -9935.065078
Problem 4
(a) Linear approximation:
Result: the 10-day, 95% VaR of the portfolio is -4621.242
The process for getting this VaR as follow:
First, calculate the Delta and Gamma for each of these options, For instance,
A call option T = 23, K = 870, S = 917.8, q = 0.00436%, r = 0.004521%, sigma = 0.015 per calendar day.
62
So d1 = (LN (S/K) +(r –q+0.5*sigma^2)*T)/ (sigma*sqrt (T)) = 0.779991. Delta in short position= - exp (-q*T) * NormSDist (d) = - 0.781518Gamma in short position = - NormDist (d, 0, 1, false) * exp (-q*T) /(S * sigma *sqrt (T)) = - 0.004453
By implement all similar calculation, I got the delta and gamma for all the short options separately.
Because of the property of delta and gamma, I can add all deltas and gammas together to obtain the portfolio delta and gamma. The portfolio delta = -53.6224The portfolio gamma = -0.26629
The volatility of the portfolio per trading day is: 0.015*sqrt (365/252) = 0.181
Finally, 10-day, 95% linear $VaR = - abs(Portfolio Delta * S * 0.181* NormSInv (0.05) *sqrt (10) ) = $ -4621.24157
(b) Quadratic approximation:
Result: the 10-day, 95% VaR of the portfolio is -5064.303736
The process for getting this VaR as follow:
First, I use the same procedure as the linear one to calculate the portfolio delta and gamma, which are:The portfolio delta = -53.6224The portfolio gamma = -0.26629
Then, using the Quadratic formula to calculate the Portfolio Mean and Portfolio Variance as follow:
Portfolio Mean = - 0.5 * Portfolio Gamma* S * 0.0181^2 * 10 = -365.50
Portfolio Variance = Portfolio Delta^2 * S^2 * 0.0181^2 * 10 + 0.5* Portfolio Gamma^2 * S^4 * 0.0181^4 * 10^2= 8160560.195
Finally, I obtain this 10-day, 95% VaR of the portfolio as:
$VaR = -365.50+ sqrt (8160560.195)*(-1.645) = $ -5064.3037
(c) Cornish-Fisher approximation:
Result: the 10-day, 95% VaR of the portfolio is -5680.878
The process for getting this VaR as follow:
First, I use the same procedure as the linear and Quadratic one to calculate the portfolio delta and gamma, which are:The portfolio delta = -53.6224The portfolio gamma = -0.26629
63
Moreover, because we want to use the Cornish-Fisher formula, we need to first obtain the Cornish-Fisher Mean, Variance and Skewness as follow:
Cornish-Fisher Mean = 0.5 * Portfolio Gamma* S * 0.0181^2 * 10 = -365.50
Cornish-Fisher Variance = Delta^2 * S^2 * 0.0181^2 * 10 + 0.5*Gamma^2 * S^4 * 0.0181^4 * 10^2= 8160560.195
Cornish-Fisher Skewness= 1/(Cornish-Fisher Variance^1.5) * (9/2* Delta^2 * Gamma * S^4 * 0.181^4 * 10^2 + 15/8 * Gamma^3 * S^6 * 0.0181^6 * 10^3 + 3 * (Delta^2 * S^2 * 0.0181^2 * 10 + ¾ * Gamma^2 * S^4 * 0.0181^4 * 10^2 ) * Cornish-Fisher Mean + 2* Cornish-Fisher Mean^3 )= -0.75930139
Finally, by Cornish-Fisher $VaR formula, we obtain this 10-day, 95% VaR of the portfolio as:
Cornish-Fisher $VaR = -365.50+ sqrt (8160560.195)*(-1.645+ 1/6*((-1.645) ^2-1)* -0.75930139) = $ -5680.878282
(d) Monte Carlo simulation with at least 5,000 trials:
Result: the 10-day, 95% Linear VaR of the portfolio is -4624.19the 10-day, 95% Quadratic VaR of the portfolio is -5619.396829
The process for getting this VaR as follow:
First, we simulate the 5000 normal distributed random numbers with mean zero and standard deviation one by Excel random number generator by setting a large number for the seed, like 1234567.
Secondly, we use these normal distributed random numbers to simulate a vector of returns by this formula: Retrun = 0.181*sqrt (10) * simulated ramdom number.
Then, I will do two parts calculation for approx the VaR of the Portfolio:
The first one is a linear approximation:
We use these returns to calculate the change value of portfolio for each options as follow:
Change of portfolio Value = Stock Index price * Portfolio Delta * Return for that option we just simulatedFor example, Change of portfolio Value for the first Option = 917.8*(-53.6224)* 0.052402 = -2578.95Our next step is to find 5% percentile value of the change of the option value which is our final Value of Linear VaR.
Linear $VaR = -percentile (the vector of change of portfolio value, 0.05) = $ -4624.19
The second one is the quadratic approximation:
First, we obtain a vector of changes in portfolio value by applying the quadratic equation which is
Portfolio Value Change for each trial = - Portfolio Delta * Stock Price * Return for that option we just simulated+ 0.5*(Portfolio Gamma) * Stock Price ^2 * Return for that option we just simulated
64
^2
For example,Portfolio Value Change for this first option approx = -53.62237 * 917.8 * 0.052402 + 0.5*(-0.266285627) * 917.8^2 * 0.052402 ^2 = -2886.925014
Our next step is to find 5% percentile value of the change of the option value which is our final Value of quadratic VaR. (Same thing as the quadratic one)
Quadratic $VaR = -percentile (the vector of change of portfolio value, 0.05) = $ -5619.396829
At last but not least, the distribution of the Change of portfolio value will be plot and analysis as follow:
First, we need to figure out the maximum and minimum value of changes of the portfolio value.For the Linear One:the maximum value of changes of the portfolio value is 26793.63 The minimum value of changes of the portfolio value is -10793.3We need to set up Bins for our histogram based on these maximum and minimum values,So the bins we set up is from -27000 to + 27000 which steps up 1000 each time. Then use Tools/Data Analysis/ Histogram function to find the frequency, and draw a graph of the frequency distribution as follow:
Distribution for Linear Vol
0
200
400
600
800
1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55
Chart 1
For the Quadratic One: the maximum value of changes of the portfolio value is 5352.649The minimum value of changes of the portfolio value is -16187.7we carry the same bin and same methods for the quadratic change value of the portfolio and get another chart as follow:
Distribution for Quar Vol
0
200
400
600
800
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51
Chart 2
In conclusion
65
The chart 1 for the linear approach looks like almost a normal distribution and the chart 2 for the quadratic approach seems a fat left side tail. And in reality, the actual distribution of the short-position call option should have fat left tail, because the short call position will have nearly no value when the option is going deep in-the-money. Obviously, by doing the Monte carol simulation, we found the quadratic approach will be more accurate than the linear approach.
(e) Full valuation:
Result: the 10-day, 95% VaR of the portfolio is
We carry out the following procedure:
First, I get a vector of 5000 Future index prices from the 5000 paths by getting each simulated future price: The formula is S (Future) =Current Index Price * exp (0.0181* sqrt (10))* Simulated Number for each path For example,S = 917.80* exp (0.0181* sqrt (10))* 0.917935 = 967.1771
Then, Because we have 106 calls on one underlying asset, we need to price 106*5000 calls by using these 5000 future index prices we simulated, and the time to maturity should be original time to maturity minus 10 to acquire the new time to maturity.
There are several steps I did to calculate the Call prices:
I set up a new worksheet called Call5000 and input the Strike, Dividend, New DTM and Interest rate as row vectors, and also input the 5000 underlying into the first column as the column vector.
Then I begin to build Macro in VBA for this Call5000 sheet as follow:
--------------------------------Begin of VBA Code-----------------------------------
'''''''First Define BSM Function'''''''''''''''
Function bsm(dtm As Double, K As Double, q As Double, r As Double, S As Double) As Double
bsm = S * Exp(-q * dtm) * WorksheetFunction.NormSDist((Log(S / K) + (r - q + 0.5 * 0.015 ^ 2) * dtm) / (0.015 * Sqr(dtm))) - K * Exp(-r * dtm) * WorksheetFunction.NormSDist((Log(S / K) + (r - q + 0.5 * 0.015 ^ 2) * dtm) / (0.015 * Sqr(dtm)) - 0.015 * Sqr(dtm))
End Function
‘’’’’’’’’’’’’write a macro to calculate the value of 106*5000 Calls and get the different with the previous adjusted Calls:
Public Sub Call5000()
Dim Wks_Call5000 As Worksheet
66
Set Wks_Call5000 = Worksheets("Call5000")
Dim C, S, T, K, r, D, pC, sum As Range
Set C = Wks_Call5000.Range("b6", "DC5005")Set S = Wks_Call5000.Range("a6", "a5005")Set T = Wks_Call5000.Range("b2", "DC2")Set K = Wks_Call5000.Range("b3", "DC3")Set r = Wks_Call5000.Range("b5", "DC5")Set D = Wks_Call5000.Range("b4", "DC4")Set pC = Wks_Call5000.Range("b1", "DC1")Set sum = Wks_Call5000.Range("dd6", "Dd5005") '''''''''sum for each path'''''''''''''
Dim i, j, m As Integer For j = 1 To 5000 For i = 1 To 106
'''''''''''''by using the BSM Function I defined and calculate the call price and the subtract the addjusted each previous call price''' C.Cells(j, i) = bsm(T.Cells(1, i), K.Cells(1, i), D.Cells(1, i), r.Cells(1, i), S.Cells(j, 1)) - pC(1, i) Next i Next j
End Sub
----------------------------------End of VBA Code-----------------------------------
By running the VBA Code above, I got the Call difference between the New calls and their adjusted previous call.
Moreover, by adding the difference within each path, I obtained the change of the portfolio value of each path for 5000 path.
Finally, we use the EXCEL function of percentile to get the Full-Valuation VaR by the vector of changes in portfolio value.
Full Valuation $VaR = percentile (change of portfolio value, 0.05) = -$ 6,009.73
In order to plot the histogram, we still need the Max and Min value of the change of the portfolio value:
The maximum value of changes of the portfolio value is 6752.441The minimum value of changes of the portfolio value is -17459.5
In order to compare the histogram with the previous one, we use the same bin as before,And plot the histogram as follow:
67
Distribution for Full Valuation
0
200
400
600
800
1000
1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55
Series1
Chart 3Draw another conclusion:
Obviously, the distribution of Chart 3 has a fatter left tail than the Chart 2, also because the short call position will have nearly no value when the option is going deep in-the-money, and the Full Valuation get the biggest number among these methods, so the Full Valuation will be the most accurate method among these five ones.
68
Summary of Financial Modeling by MATLAB
Wiener Process
function [WienerPath] = WienerProcess(NumPaths, NumTimeSteps, Maturity, ranState)SqrtTimeStep = sqrt(Maturity/NumTimeSteps);% Simulates but does not plot a Wiener Process% Requires the state of randn, so you can reset its seeds.WienerPath = zeros(NumPaths, NumTimeSteps+1);randn('state',ranState);NormRandNums = SqrtTimeStep*randn(NumPaths, NumTimeSteps);for i = 2:NumTimeSteps+1 WienerPath(:,i) = WienerPath(:,i-1) + NormRandNums(:,i-1 );endend
Monte Carlo simulation that evolves the 5-stocks over one week
Download two years of weekly returns for the following 5 stocks: AAPL, GOOG, JNJ, MMM and XOM.
a. Assume that you have a portfolio with equal $ amounts split between the five stocks ($10,000 of each stock). Write a one-period Monte Carlo simulation that evolves the 5-stocks over one week. Assume that the set of five stocks has log returns that are multivariate normally distributed with zero mean and with the covariance matrix estimated in part (a). (You can assume that the log returns have zero mean, as the effect of a small non-zero mean is generally negligible over one week.) What is the most you could lose on the portfolio, with 99% confidence? 1
b. Repeat (b), assuming the stocks are uncorrelated.c. Repeat (b), assuming that the stocks are perfect correlated.
% do b c d problem in one function named as StockVaranceTest
function StockVaranceTest(covMatrix, numPaths, percentile, numTrials)% first, we intialize some vectors initValOfStock = 10000.0; initStockPrice = [1;1;1;1;1]; M = [0;0;0;0;0]; PortfolioValue = zeros(1, numPaths);
1
69
covMatVar = zeros(1, numTrials); uncorrVar = zeros(1, numTrials); perfCorrVar = zeros(1, numTrials); uncorrCovMat = diag(diag(covMatrix));
%Then, we do several times of trials by passing through the Value into my revised EvolveCorrelatedStocks functions to obtain the value for b c d.
for i = 1:numTrials StockPrice = EvolveCorrelatedStocksR(initStockPrice, M, covMatrix, numPaths); PortfolioValue = sort(sum(StockPrice(1:5,:)));% b Initial value = 50000. get the changes in portfolio value. PortfolioValue = initValOfStock * (PortfolioValue - 5); %%%%%%%%%%%%%%%% covMatVar(i) = PortfolioValue(max(1,floor((1 - percentile)*numPaths)));%%%% c for uncorrelated case %%%%%%%%%% StockPrice = EvolveCorrelatedStocksR(initStockPrice, M, uncorrCovMat, numPaths); PortfolioValue = sort(sum(StockPrice(1:5,:))); PortfolioValue = initValOfStock *(PortfolioValue - 5); uncorrVar(i) = PortfolioValue(max(1,floor((1 - percentile)*numPaths)));%%%% d for perfect correlated case %%%%%%%%%% StockPrice = EvolveCorrelatedStocksPCorr(initStockPrice, M, covMatrix, numPaths); PortfolioValue = sort(sum(StockPrice(1:5,:))); PortfolioValue = initValOfStock *(PortfolioValue - 5); perfCorrVar(i) = PortfolioValue(max(1,floor((1 - percentile)*numPaths))); end
%%%% summarized by sprintf %%%%%%%%%%
sprintf('Portfolio Variance with the covariance Matrix is %g with standard deviation %g,\n for uncorrelated case, it is %g and standard deviation is %g,\n moreover for perfect correlated case, it is %g and standard deviation is stddev %g.\n',mean(covMatVar), std(covMatVar), mean(uncorrVar), std(uncorrVar), mean(perfCorrVar), std(perfCorrVar)), end
M-file for revised function of EvolveCorrelatedStock Named as EvolveCorrelatedStocksR
% We modify the function EvolveCorrelatedStock as following named as% EvolveCorrelatedStocksR function [StockPrice]=EvolveCorrelatedStocksR(initStockPrices, m, CovMa, NumPaths)
% Count number of rows NumStocks = length(initStockPrices);initStockPrice = repmat(initStockPrices,1,NumPaths);m = repmat(m,NumPaths,1);CholeskyMatrix = chol(CovMa);UncorrelatedRanNums = randn(NumStocks, NumPaths);StockPrice = initStockPrices.*exp(m + (CholeskyMatrix * UncorrelatedRanNums));end
we further revised the EvolveCorrelatedStock for the perfect correlated case, then named as EvolveCorrelatedStocksPCorr
% We remodel the function EvolveCorrelatedStock as following named as% EvolveCorrelatedStocksPCorr
70
function [StockPrice]=EvolveCorrelatedStocksPCorr(initStockPrices, m, CovMa, NumPaths) %We should delete off-diagonal elements in the CovMatrix for perfect correlated caseNumStocks = length(initStockPrices); InitStockPrice = repmat(initStockPrices,1,NumPaths);m = repmat(m, NumPaths,1 );CholeskyMatrix = diag(sqrt(diag(CovMa)));% draws the same random numbers for each stock, so that they can be perfectly correlated.
CorrelatedRanNums = randn(1, NumPaths);CorrelatedRanNums = repmat(CorrelatedRanNums, NumStocks, 1);StockPrice = initStockPrice.*exp (m + ( CholeskyMatrix * CorrelatedRanNums ));End
Solve Equation Method:
BisectionMethod:
function [midGuess, midDelta, i] = BisectionMethod(funct, targetVal, lowGuess, highGuess, maxTries, tolerance)% Applies Newton's method to find solution to funct(guess) = targetVallowDelta = targetVal - funct(lowGuess);highDelta = targetVal - funct(highGuess);if ((lowDelta > tolerance)&&(highDelta > tolerance)) sprintf('Both guesses are below targetVal; bisection method may fail\n'),end if((lowDelta < -tolerance)&&(highDelta < -tolerance)) sprintf('Both guesses are above targetVal; bisection method may fail\n'),endif (lowGuess > highGuess) sprintf('lowGuess should be less than highGuess');end success = 0; for i = 1:maxTries try midGuess = .5*(lowGuess + highGuess); midDelta = targetVal - funct(midGuess); if (abs(midDelta) < tolerance) success = 1; break; end if (((midDelta >0)&& (lowDelta>0))||((midDelta <0)&& (lowDelta<0))) % mid point and low point are on same side of root, so throw low point out. lowGuess = midGuess; % guess should be between midGuess & highGuess else highGuess = midGuess; % otherwise throw high point out, guess should be between lowGuess and midGuess end catch % go here if there are errors following try sprintf('Came within %g, failure at step %d\n',midDelta,i), %if there is an error, we come here... lasterr, break; endendif (success == 0) sprintf('Failed to converge within tolerance of the correct answer after %d tries\n',i),
71
endend
BoxMulLinConGen
function [nran, newseed] = BoxMulLinConGen(seed, N)% Implements Box Muller, calling a LCG Generatorm = 2^24;a = 1140671485;c = 12820163;ran1 = zeros(1,N);ran2 = zeros(1,N);nran1 = zeros(1,N);nran2 = zeros(1,N);nran = zeros(1, 2*N);z1 = zeros(1,N);z2 = zeros(1,N);[ran1,z1] = LCG(a,c,m,seed,N);newseed = z1(N);[ran2, z2] = LCG(a,c,m,newseed,N);newseed = z2(N);R = sqrt(-2*log(ran1));Theta = 2*pi*ran2;nran1 = R.*cos(Theta);nran2 = R.*sin(Theta);nran = [nran1; nran2];end
Option Collar Calculation:
% I write a function to compute the Strike for the Callfunction [CallStrike] =Collar(spot,Putstrike,r,mat,vol);% Caculate the put price by blsprice function[call, put] = blsprice(spot,Putstrike,r,mat,vol); Collar = @(CallStrike) blsprice(spot,CallStrike,r,mat,vol) - put;% Computes call strike of the collar by fzeroCallStrike = fzero(Collar,spot); sprintf('the strike of the Call is %f\n',CallStrike), end
Delta Hedge to replicate a call option:
function [stockPrice, stockHedge] = computeStockAndDeltas(initStockPrice, strike, rate, mat, estimatedVol, realizedVol,stockMu, numPaths, numTimesteps, ranState)%Generates stock price at multiple timesteps and paths, as driven by a%Wiener process. Process has volatility equal to realized vol.% Also returns deltas for a call option, which are the hedge position if% one delta hedges at each timestep on each path. 'Estimated Vol' is used% to evaluate the deltas; it indicates the market's implied vol for the
72
% option (which may differ from the realized vol...).stockPrice = zeros(numPaths, numTimesteps+1);simTimes = zeros(numPaths, numTimesteps+1);stockHedge = zeros(numPaths, numTimesteps + 1); %stockHedge contains deltas for a call optionverySmallNumber = .000001;sqrtMat =sqrt(mat);for i = 1:1:numTimesteps+1 simTimes(:,i) = mat*(i-1)/numTimesteps;end stockPrice = initStockPrice.*exp(simTimes.*(stockMu - realizedVol.*realizedVol*.5) + realizedVol.*WienerProcess(numPaths, numTimesteps, mat, ranState));simTimes(:,numTimesteps+1)=mat - verySmallNumber; % Kluge maybe needed because blsdelta will choke when time to maturity equals zero (d1 will contain a division by sqrt(0),% so time to maturity is set to be very small.% We don't really need delta's at maturity anyhow, but it simplifies the% code to return delta's for all time steps, including the final one.stockHedge = blsdelta(stockPrice, strike, rate, mat - simTimes, estimatedVol);end
MATLAB Function for Stop Loss Strategies to replicate a call option:
simulate the stop loss strategy when replicating a call option.computes the stock price at all paths and timesteps, but computes the ‘stop-loss’ hedge ratios rather than Black-Scholes deltas. These ratios are defined by:
i. Δi(tk) = 1 if Si(tk) > Kexp(-r(T-tk))ii. Δi(tk) = 0 if Si(tk) < Kexp(-r(T-tk))
iii. Δi(tk) = 1/2 if Si(tk) = Kexp(-r(T-tk)).
Matlab Function :
function [stockPrice, stockHedge] = computeStopLossStockHedge(initStockPrice, strike, rate, mat, estimatedVol, realizedVol,stockMu, numPaths, numTimesteps, ranState) %%%% rewrite the computestockanddelta function as follow %[Generates stock price at multiple timesteps and paths, as driven by a%Wiener process. Process has volatility equal to realized vol.% Also returns deltas for a call option, which are the hedge position if% one delta hedges at each timestep on each path. 'Estimated Vol' is used% to evaluate the deltas; it indicates the market's implied vol for the% option (which may differ from the realized vol...).]stockPrice = zeros(numPaths, numTimesteps+1);simTimes = zeros(numPaths, numTimesteps+1);stockHedge = zeros(numPaths, numTimesteps + 1); %stockHedge contains 1 or 0verySmallNumber = .000001;sqrtMat =sqrt(mat);for i = 1:1:numTimesteps+1 simTimes(:,i) = mat*(i-1)/numTimesteps;
73
end stockPrice = initStockPrice.*exp(simTimes.*(stockMu - realizedVol.*realizedVol*.5) + realizedVol.*WienerProcess(numPaths, numTimesteps, mat, ranState));simTimes(:,numTimesteps+1)=mat - verySmallNumber; % adjust the hedge ratio by looping through the paths and timestepsfor i=1 : numPaths for j=1 : numTimesteps+1 if stockPrice(i,j)>strike*exp(-rate*(mat-simTimes(i,j))) stockHedge(i,j)=1; else if stockPrice(i,j)==strike*exp(-rate*(mat-simTimes(i,j))) stockHedge(i,j)=.5; else stockHedge(i,j)=0; end end end end end
function [portfolioVal, payoff, stockPrice, stockHedge] = simReplPortCallsStopAndLoss(initStockPrice, strike, rate, mat, estimatedVol, realizedVol, stockMu, numPaths, numTimesteps, ranState) %intialize vectors%%%%%%%%%%%%%%%%%%%%%%%%%portfolioVal = zeros(numPaths, numTimesteps+1); depositAmount = zeros(numPaths, numTimesteps+1);trackingError = zeros(numPaths,1); payoff = zeros(numPaths,1);%intialize three vectors for question d and enumberCrossings = zeros(numPaths,1);CostCrossings = zeros(numPaths,1);Zero = zeros(numPaths, 1) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Small = Zero + .000000001; %computing the hedge ratio[stockPrice, stockHedge] = computeStockAndStopLossHedge(initStockPrice, strike, rate, mat, estimatedVol, realizedVol, stockMu, numPaths, numTimesteps, ranState); portfolioVal(:,1) = blsprice(initStockPrice, strike, rate, mat, estimatedVol); % initial portfolio value equal to value of call we want to replicate% portfolioVal(:,1) = 0.0; % initial portfolio is worth zero, as we can replicate with no cost!depositAmount(:,1) = portfolioVal(:,1)-initStockPrice*stockHedge(:,1); % deposit is total portfolio minus stock amountaccruedInterestOverPeriod = exp(rate*mat/numTimesteps)-1;payoff = max(stockPrice(:, numTimesteps+1)-strike,0);for i = 2:1:numTimesteps+1 portfolioVal(:,i) = portfolioVal(:,i-1)+stockHedge(:,i-1).*(stockPrice(:,i)-stockPrice(:,i-1)); % Portfolio grows by capital gains portfolioVal(:,i) = portfolioVal(:,i)+ accruedInterestOverPeriod*depositAmount(:,i-1); %We add accrued interest (negative in this case, since the deposit amount is negatvie)
74
depositAmount(:,i)=depositAmount(:,i-1)+ accruedInterestOverPeriod*depositAmount(:,i-1)-stockPrice(:,i).*(stockHedge(:,i)-stockHedge(:,i-1));% The deposit amount changes by the additional funds needed to adjust our stock hedge plus accrued interest. numberCrossings = numberCrossings + abs(stockHedge(:,i)-stockHedge(:,i-1)); % adding Number of Crossings DifferentStrike = strike*exp(-rate*mat*(numTimesteps+1-i)/numTimesteps); CostCrossings = CostCrossings + (stockHedge(:,i)-stockHedge(:,i-1)).*(stockPrice(:,i)-DifferentStrike); % adding the difference of the discounted strike end%adding the small number for make the equation meaningfulCostCrossings = CostCrossings./(numberCrossings + Small); trackingError = portfolioVal(:,numTimesteps+1)-payoff;sprintf('Excess portfolio value averages to %g with a standard deviation of %g\n',mean(trackingError), std(trackingError)), % Shows how well our replicating portfolio captures the payoffsprintf('The number of crossings averages to %g, and it has a standard deviation of %g\n',mean(numberCrossings), std(numberCrossings)), % Measures distribution of crossing times...sprintf('The average value of crossings cost is %g, and standard deviation are %g\n',mean(CostCrossings), std(CostCrossings)), %Measures typical deviation of stock from discounted strike when rebalancingend
Explicit Finite Difference Method for option pricing
the function as follow:
function price = EuCallExplExp(S0,K,r,T,sigma,Smax,dS,dt)% set up grid and adjust increments if necessary% changing the max and min S ValueSmax = log(S0)+5*sigma*sqrt(T)Smin = log(S0)-5*sigma*sqrt(T)M = round((Smax-Smin)/dS);dS = (Smax-Smin)/M;N = round(T/dt);dt = T/N;matval = zeros(M+1,N+1);vetS = linspace(Smin,Smax,M+1)'; vetj = 0:N;% set up boundary conditionsmatval(:,N+1) = max(exp(vetS)-K,0);matval(M+1,:) = exp(Smax) - K*exp(-r*dt*(N-vetj));matval(1,:) = 0;% set up coefficients a = 0.5*dt*(0.5*sigma^2 - r+sigma^2/dS)/dS;b = 1- dt*(-sigma^2/dS^2 + r);c = 0.5*dt*(r-sigma^2*(0.5-1/dS))/dS;% solve backward in time
75
for j=N:-1:1 for i=2:M matval(i,j) = a*matval(i-1,j+1) + b*matval(i,j+1)+ ... c*matval(i+1,j+1); endend% return price, possibly by linear interpolation outside the gridprice = interp1(vetS, matval(:,1), S0);
Then Run the function in command window as follow:
>> K=35;>> T=1.5;r=0.05;sigma=0.38;S0=32;Smax=5;dS=log(3.2);dt=0.001;
ans =3.824343256545
By using tic-toc method, the time for this problem is a little faster than the example on the class and also pretty stable.
AppendixVBA Code For Fix Income Portfolio:
Public Sub USTDurationCovex()
Dim Data As Worksheet, Dat1 As Range, Instru1 As Range, Mat As Range, Coupon As Range, Ask_P As RangeDim redemption As Double, Basis As IntegerDim Wks_Yield As Worksheet, Yie As RangeDim Wks_Copy As Worksheetredemption = 100Basis = 2Dim Dat2, Instru2 As Range
Dim Bill As RangeSet Data = Worksheets("Data")
Set Wks_Yield = Worksheets("Yield")
76
Set Wks_Copy = Worksheets("DataCopy")Set Dat1 = Data.Range("i3", "iv3")
Set Instru1 = Data.Range("b7", "b32773")
Set Dat2 = Wks_Copy.Range("i3", "iv3")
Set Instru2 = Wks_Copy.Range("b7", "b32773")
Set Mat = Wks_Copy.Range("e7", "e32773")
Set Coupon = Wks_Copy.Range("d7", "d32773")
Set Bill = Data.Range("i7", "iv32773")
Set Ask_P = Wks_Copy.Range("i7", "IV32773")
Set Yie = Wks_Yield.Range("i7", "IV32773")
Dim Cell1 As Range, Cell2, cell3, cellSe As Range, i, j, m, n, p As Integer
i = 1j = 0n = 0p = 1Dim o As IntegerFor Each Cell1 In Data.Range("A7", "a32773")
If Cell1 <> "" Then j = j + 1 End If Next Cell1
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' For Each Cell2 In Instru1 If Cell2 = "Tbill" Then For m = 1 To 6 Wks_Copy.Range("B7", "B32773").Cells(p, m) = Cell2.Offset(0, m - 1).Value Wks_Copy.Range("A7", "B32773").Cells(p, 1) = Cell2.Offset(0, -1).Value Next m
For m = 7 To j - 1''''''''''''''''''''''''''''''''''''''''''T-Bill calculation'''''''''''''''''''''''''''''''''''''''' Wks_Copy.Range("B7", "B32773").Cells(p, m) = TBILLPRICE(Cell2.Offset(p - 1 - 4, m - 1).Value, Cell2.Offset(0, 3), Cell2.Offset(0, m - 1).Value * 0.01) Next m p = p + 1 End If
77
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If Cell2 = "UST" Then For m = 1 To j - 1 Wks_Copy.Range("B7", "B32773").Cells(i + p - 1, m) = Cell2.Offset(0, m - 1).Value Wks_Copy.Range("A7", "B32773").Cells(i + p - 1, 1) = Cell2.Offset(0, -1).Value Next m i = i + 1 End If Next Cell2
For Each cell3 In Dat2
If cell3 <> "" Then n = n + 1 End If Next cell3
Wks_Copy.Range("a1", "iv6").Value = Data.Range("a1", "iv6").Value
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Wks_Yield.Range("a1", "iv6").Value = Wks_Copy.Range("a1", "iv6").ValueWks_Yield.Range("a7", "g32773").Value = Wks_Copy.Range("a7", "h32773").Value
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Dim a, b As Integer
For a = 1 To n 'colomn
For b = 2 To i - 1 + p - 1 ' row''''''''''''''''''''''''''''For UST''''''''''''''''''''''''''''''''Yie.Cells(b, a).Value = Yield(Dat2.Cells(1, a).Value, Mat.Cells(b, 1).Value, Coupon.Cells(b, 1).Value, Ask_P.Cells(b, a).Value, redemption, Basis) '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Next b''''''''''''''''''''''''''''Need adjustment for t-bill''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Yie.Cells(1, a).Value = 365 * Bill.Cells(1, a) / (100 * (360 - Bill.Cells(1, a) * DateDiff("d", Dat2.Cells(1, a), Mat.Cells(1, 1)) / 100))
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Next a
Dim Wks_YieldAdd, Wks_YieldSub, Wks_AskPriceAdd, Wks_AskpriceSub As Worksheet
78
Set Wks_YieldAdd = Worksheets("YieldAdd")Set Wks_YieldSub = Worksheets("YieldSub")Set Wks_AskPriceAdd = Worksheets("AskPriceAdd")Set Wks_AskpriceSub = Worksheets("AskpriceSub")
Wks_YieldAdd.Range("a1", "iv6").Value = Wks_Yield.Range("a1", "iv6").ValueWks_YieldAdd.Range("a7", "h32773").Value = Wks_Yield.Range("a7", "h32773").Value
Wks_YieldSub.Range("a1", "iv6").Value = Wks_Yield.Range("a1", "iv6").ValueWks_YieldSub.Range("a7", "h32773").Value = Wks_Yield.Range("a7", "h32773").Value
Wks_AskPriceAdd.Range("a1", "iv6").Value = Wks_Yield.Range("a1", "iv6").ValueWks_AskPriceAdd.Range("a7", "h32773").Value = Wks_Yield.Range("a7", "h32773").Value
Wks_AskpriceSub.Range("a1", "iv6").Value = Wks_Yield.Range("a1", "iv6").ValueWks_AskpriceSub.Range("a7", "h32773").Value = Wks_Yield.Range("a7", "h32773").Value
Dim C, D As Integer
For C = 1 To n 'colomn
For D = 2 To i - 1 + p - 1 ' row Wks_YieldAdd.Range("i7", "IV32773").Cells(D, C).Value = Yie.Cells(D, C).Value + 0.0001 Wks_YieldSub.Range("i7", "IV32773").Cells(D, C).Value = Yie.Cells(D, C).Value - 0.0001
Next DNext C
Dim e, f As Integer
For e = 1 To n ' colomn
For f = 2 To i - 1 + p - 1 'row Wks_AskPriceAdd.Range("i7", "IV32773").Cells(f, e).Value = PRICE(Dat2.Cells(1, e).Value, Mat.Cells(f, 1).Value, Coupon.Cells(f, 1).Value, Wks_YieldAdd.Range("i7", "IV32773").Cells(f, e), redemption, Basis) Wks_AskpriceSub.Range("i7", "IV32773").Cells(f, e).Value = PRICE(Dat2.Cells(1, e).Value, Mat.Cells(f, 1).Value, Coupon.Cells(f, 1).Value, Wks_YieldSub.Range("i7", "IV32773").Cells(f, e), redemption, Basis)
Next f''''''''''''''''''''''''''''''''''''''Extra Addjustment for T_Bill'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' Wks_AskPriceAdd.Range("i7", "IV7").Cells(1, e).Value = TBILLPRICE(Dat2.Cells(1, e).Value, Mat.Cells(1, 1).Value, Cell2.Offset(0, m - 1).Value) ' Wks_AskpriceSub.Range("i7", "IV7").Cells(1, e).Value = TBILLPRICE(Dat2.Cells(1, e).Value, Mat.Cells(1, 1).Value, Cell2.Offset(0, m - 1).Value) Next e
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Duration'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim Wks_Duration, Wks_Covex As Worksheet
Set Wks_Duration = Worksheets("Duration")Set Wks_Covex = Worksheets("Covexity")
Wks_Duration.Range("a1", "iv6").Value = Wks_Yield.Range("a1", "iv6").ValueWks_Duration.Range("a7", "h32773").Value = Wks_Yield.Range("a7", "h32773").Value
Wks_Covex.Range("a1", "iv6").Value = Wks_Yield.Range("a1", "iv6").Value
79
Wks_Covex.Range("a7", "h32773").Value = Wks_Yield.Range("a7", "h32773").Value
Dim g, h As Integer
For g = 1 To n ' colomn
For h = 2 To i - 1 + p - 1 'row
Wks_Duration.Range("i7", "IV32773").Cells(h, g).Value = (Wks_AskpriceSub.Range("i7", "IV32773").Cells(h, g).Value - Wks_AskPriceAdd.Range("i7", "IV32773").Cells(h, g).Value) / (2 * 0.0001 * Ask_P.Cells(h, g)) Wks_Covex.Range("i7", "IV32773").Cells(h, g).Value = (Wks_AskpriceSub.Range("i7", "IV32773").Cells(h, g).Value + Wks_AskPriceAdd.Range("i7", "IV32773").Cells(h, g).Value - 2 * Ask_P.Cells(h, g)) / (0.0001 * 0.0001 * Ask_P.Cells(h, g))
Next h
Wks_Duration.Range("i7", "IV32773").Cells(1, g).Value = MDURATION(Dat2.Cells(1, g), Mat.Cells(1, 1), Coupon.Cells(1, 1), Yie.Cells(1, g), 2, 1)
Next g
'''''''''''''''''''''Accrute interest
Dim Wks_AI, Wks_Data As Worksheet
Dim IDate, FIDate As Range
Set Wks_AI = Worksheets("AI")Set Wks_Data = Worksheets("DataCopy")Set IDate = Wks_AI.Range("C7", "C32773")Set FIDate = Wks_AI.Range("iv7", "iv32773")
Wks_AI.Range("a1", "iv6").Value = Wks_Data.Range("a1", "iv6").ValueWks_AI.Range("a7", "g32773").Value = Wks_Data.Range("a7", "g32773").Value
Dim Wks_DP As Worksheet
Set Wks_DP = Worksheets("DP")
Wks_DP.Range("a1", "iv6").Value = Wks_Data.Range("a1", "iv6").ValueWks_DP.Range("a7", "g32773").Value = Wks_Data.Range("a7", "g32773").Value
Dim r, s As Integer
For r = 1 To n ' colomn
For s = 2 To i - 1 + p - 1 'row Wks_AI.Range("i7", "IV32773").Cells(s, r).Value = ACCRINT(IDate.Cells(s, 1), FIDate.Cells(s, 1), Dat2.Cells(1, r).Value, Coupon.Cells(s, 1).Value, redemption, Basis, 1) Wks_DP.Range("i7", "IV32773").Cells(s, r).Value = Wks_AI.Range("i7", "IV32773").Cells(s, r).Value + Wks_Copy.Range("i7", "IV32773").Cells(s, r).Value Wks_DP.Range("i7", "IV32773").Cells(1, r).Value = Wks_Copy.Range("i7", "IV32773").Cells(1, r).Value
Next s Next r
'''''''''''''''''''''''''''''''''''''''
End Sub
80
Public Sub Port1()' using port1 value to caculate the portfolio Duration, Covexity, and YieldDim Wks_Duration, Wks_Covex As Worksheet, Wks_Yield As WorksheetDim Wks_Project1 As Worksheet
Set Wks_Duration = Worksheets("Duration")Set Wks_Covex = Worksheets("Covexity")Set Wks_Yield = Worksheets("Yield")Set Wks_Project1 = Worksheets("Project1")
Dim Port_a As Range
Dim Num_Y, Num_D, Num_C, D, Y, C As Range
Set Port_a = Wks_Project1.Range("b4")Set Num_Y = Wks_Yield.Range("A7", "A32773")Set Num_D = Wks_Duration.Range("A7", "A32773")Set Num_C = Wks_Covex.Range("A7", "A32773")Set D = Wks_Project1.Range("b18", "iv18")
Set Y = Wks_Project1.Range("b20", "iv20")Set C = Wks_Project1.Range("b19", "iv19")
Dim i, j As Integer
For j = 1 To 12
For i = 0 To 5
Dim Cell1, Cell2, cell3 As Range For Each Cell1 In Num_Y
If Port_a.Offset(i, 0) = Cell1.Value Then
Port_a.Offset(i, 4) = Cell1.Offset(0, 7 + j)
End If
Next Cell1
For Each Cell2 In Num_D
If Port_a.Offset(i, 0) = Cell2.Value Then
Port_a.Offset(i, 2) = Cell2.Offset(0, 7 + j)
End If
Next Cell2
For Each cell3 In Num_C
If Port_a.Offset(i, 0) = cell3.Value Then
Port_a.Offset(i, 3) = cell3.Offset(0, 7 + j)
End If
Next cell3
Next i
81
D.Cells(1, j) = Wks_Project1.Range("d10")C.Cells(1, j) = Wks_Project1.Range("e10")Y.Cells(1, j) = Wks_Project1.Range("f10")
Next j
End Sub
Public Sub Carry()''''''''''''''''''''''Count Row and Column'''''''''''''''''''''''Dim Wks_Copy As WorksheetSet Wks_Copy = Worksheets("DataCopy")
Dim Dat2, RowCount As Range
Set Dat2 = Wks_Copy.Range("i3", "iv3")Set RowCount = Wks_Copy.Range("a7", "a32773")
Dim m, n As Integer
Dim Cell1, Cell2 As Range
For Each Cell1 In Dat2
If Cell1 <> "" Then n = n + 1 End If Next Cell1 For Each Cell2 In RowCount
If Cell2 <> "" Then m = m + 1 End If Next Cell2
''''''''''''''''''''''' the period length calculation'''''''''''''''''
Dim Wks_PerCarry As Worksheet
Set Wks_PerCarry = Worksheets("PeriodCarry")
Wks_PerCarry.Range("a1", "iv6").Value = Wks_Copy.Range("a1", "iv6").Value
Wks_PerCarry.Range("a7", "g32773").Value = Wks_Copy.Range("a7", "g32773").Value
Dim Mat, PerC, Settle As Range
Set Mat = Wks_PerCarry.Range("e7", "e32773")Set PerC = Wks_PerCarry.Range("i7", "IV32773")Set Settle = Wks_PerCarry.Range("i3", "iv3")
Dim C, D As Integer
For C = 1 To m 'row
For D = 1 To n 'column
82
PerC.Cells(C, D) = COUPDAYS(Settle.Cells(1, D), Mat.Cells(C, 1), 2, 1) Next D
Next C
''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''Carry Calculation & PL for each day'''''''''''''''''''''''''''''''''''''''Dim Wks_Carry, Wks_DP, Wks_RCarry, Wks_LPL, Wks_SPL As Worksheet
Set Wks_Carry = Worksheets("CofCarry")Set Wks_DP = Worksheets("DP")
Set Wks_RCarry = Worksheets("RCarry")Set Wks_LPL = Worksheets("L_P&L")Set Wks_SPL = Worksheets("S_P&L")
Dim R_Carry, Rev_Carry As Range
Set R_Carry = Wks_Carry.Range("i7", "iv32773")Set Rev_Carry = Wks_RCarry.Range("i7", "iv32773")
Wks_Carry.Range("a1", "iv6").Value = Wks_Copy.Range("a1", "iv6").Value
Wks_Carry.Range("a7", "g32773").Value = Wks_Copy.Range("a7", "g32773").Value
Wks_RCarry.Range("a1", "iv6").Value = Wks_Copy.Range("a1", "iv6").Value
Wks_RCarry.Range("a7", "g32773").Value = Wks_Copy.Range("a7", "g32773").Value
Wks_LPL.Range("a1", "iv6").Value = Wks_Copy.Range("a1", "iv6").Value
Wks_LPL.Range("a7", "g32773").Value = Wks_Copy.Range("a7", "g32773").Value
Wks_SPL.Range("a1", "iv6").Value = Wks_Copy.Range("a1", "iv6").Value
Wks_SPL.Range("a7", "g32773").Value = Wks_Copy.Range("a7", "g32773").Value
Dim Coupon, DP, Settle2, Repo, Repo_Rev, L_PL, S_PL, CP As Range
Set Coupon = Wks_Carry.Range("D7", "D32773")Set DP = Wks_DP.Range("i7", "IV32773")Set Settle2 = Wks_Carry.Range("i3", "iv3")Set Repo = Wks_Carry.Range("F7", "F32773")Set Repo_Rev = Wks_Carry.Range("g7", "g32773")Set L_PL = Wks_LPL.Range("i7", "IV32773")Set S_PL = Wks_SPL.Range("i7", "IV32773")Set CP = Worksheets("DataCopy").Range("i7", "iv32773")
Dim e, f As Integer
For e = 1 To m 'row
For f = 2 To n 'column R_Carry.Cells(e, f) = Coupon.Cells(e, 1) * 0.5 * DateDiff("d", Settle2.Cells(1, f - 1), Settle2.Cells(1, f)) / PerC.Cells(e, f) - DP.Cells(e, f) * 0.01 * DateDiff("d", Settle2.Cells(1, f - 1), Settle2.Cells(1, f)) / 360 * Repo.Cells(e, 1) * 0.01
83
Rev_Carry.Cells(e, f) = Coupon.Cells(e, 1) * 0.5 * DateDiff("d", Settle2.Cells(1, f - 1), Settle2.Cells(1, f)) / PerC.Cells(e, f) - DP.Cells(e, f) * 0.01 * DateDiff("d", Settle2.Cells(1, f - 1), Settle2.Cells(1, f)) / 360 * Repo_Rev.Cells(e, 1) * 0.01 Next f
Next e
'''''''''''''''''''''''''''finish the carry caculation'''''''''''''''''''''''''''''
'''''''''''''''''''''''''''Entry the P&L caculation''''''''''''''''''''''''''''''''
Dim g, h As Integer
For g = 1 To m 'row
For h = 2 To n 'column
'''''''''long P&L = capital gain + Carry''''''''''''''''''' L_PL.Cells(g, h) = (CP.Cells(g, h) - CP.Cells(g, h - 1)) / 100 + R_Carry.Cells(g, h)
'''''''''Short P&L= capital gain - Carry'''''''''''''''''''' S_PL.Cells(g, h) = (CP.Cells(g, h - 1) - CP.Cells(g, h)) / 100 - Rev_Carry.Cells(g, h)
Next h
Next g
End Sub
Public Sub Trade()
Dim Wks_Trade, Wks_LPL, Wks_SPL, Wks_Cash, Wks_Duration, Wks_Covex As Worksheet
Set Wks_Trade = Worksheets("Trade")Set Wks_LPL = Worksheets("L_P&L")Set Wks_SPL = Worksheets("S_P&L")
Set Wks_Cash = Worksheets("DataCopy")Set Wks_Duration = Worksheets("Duration")Set Wks_Covex = Worksheets("Covexity")
Dim rng_Cash, rng_Duration, rng_Covex As RangeDim NumInTo, NumInFrom As RangeDim PL As Range
Set rng_Cash = Wks_Cash.Range("I7", "iv32773")Set rng_Duration = Wks_Duration.Range("I7", "iv32773")Set rng_Covex = Wks_Covex.Range("I7", "iv32773")
84
''''''''''''''''''''''Count Row and Column'''''''''''''''''''''''Dim Wks_Copy As WorksheetSet Wks_Copy = Worksheets("DataCopy")
Dim Dat2, RowCount As Range
Set Dat2 = Wks_Copy.Range("i3", "iv3")Set RowCount = Wks_Copy.Range("a7", "a32773")
Dim m, n As Integer
Dim Cell1, Cell2 As Range
For Each Cell1 In Dat2
If Cell1 <> "" Then n = n + 1 End If Next Cell1 For Each Cell2 In RowCount
If Cell2 <> "" Then m = m + 1 End If Next Cell2''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''calculate the par amount of the second or the third instrument''''''''''''''''''
Dim Trade_T, NumI, NumDP, NumC, NumCP, NumLCarry, NumSCarry, NumLPL, NumSPL As Range
Dim a As Integer, Wks_DP As Worksheet
Set Trade_T = Wks_Trade.Range("a1", "a32773")Set NumI = Wks_Duration.Range("a1", "a32773")Set Wks_DP = Worksheets("DP")
Set NumDP = Wks_DP.Range("a1", "a32773")Set NumC = Wks_Covex.Range("a1", "a32773")Set NumCP = Wks_Cash.Range("a1", "a32773")Set NumLCarry = Worksheets("CofCarry").Range("a1", "a32773")Set NumSCarry = Worksheets("RCarry").Range("a1", "a32773")Set NumLPL = Worksheets("L_P&L").Range("a1", "a32773")Set NumSPL = Worksheets("S_P&L").Range("a1", "a32773")
Dim cell3, cell4, cell5, cell6, cell9, cell7, cell8, cell10, cell11, cell12, Cell_Type, Cell_LCarry, Cell_SCarry, Cell_LPL, Cell_SPL, Cell_LPL1, Cell_LPL2 As RangeDim j As Integer
For Each cell3 In Trade_T
If cell3 = "Duration neutral" Then For Each cell4 In NumI If cell4 = cell3.Offset(0, 2) Then
85
For Each cell5 In NumI If cell5 = cell3.Offset(0, 4) Then For Each cell7 In NumDP If cell7 = cell3.Offset(0, 2) Then For Each cell8 In NumDP If cell8 = cell3.Offset(0, 4) Then ' For Each Cell_Type In Wks_Trade.Range("b11", "b32773") If cell3.Offset(0, 1) = "curve steepener" Then For Each Cell_LPL In NumLPL If Cell_LPL = cell3.Offset(0, 2) Then For Each Cell_SPL In NumSPL If Cell_SPL = cell3.Offset(0, 4) Then For a = 1 To n cell3.Offset(0, 7 + a) = cell3.Offset(0, 3) * cell4.Offset(0, 7 + a) * cell7.Offset(0, 7 + a) / (cell5.Offset(0, 7 + a) * cell8.Offset(0, 7 + a)) Next a For j = 1 To n - 1 cell3.Offset(0, 32 + j) = cell3.Offset(0, 3) * Cell_LPL.Offset(0, 8 + j) + cell3.Offset(0, 7 + j) * Cell_SPL.Offset(0, 8 + j) Next j End If Next Cell_SPL End If Next Cell_LPL ElseIf cell3.Offset(0, 1) = "curve flattener" Then For Each Cell_LPL In NumLPL If Cell_LPL = cell3.Offset(0, 4) Then For Each Cell_SPL In NumSPL If Cell_SPL = cell3.Offset(0, 2) Then For a = 1 To n cell3.Offset(0, 7 + a) = cell3.Offset(0, 3) * cell4.Offset(0, 7 + a) * cell7.Offset(0, 7 + a) / (cell5.Offset(0, 7 + a) * cell8.Offset(0, 7 + a)) Next a For j = 1 To n - 1 cell3.Offset(0, 32 + j) = cell3.Offset(0, 3) * Cell_SPL.Offset(0, 8 + j) + cell3.Offset(0, 7 + j) * Cell_LPL.Offset(0, 8 + j) Next j End If
86
Next Cell_SPL End If Next Cell_LPL End If ' Next Cell_Type End If Next cell8 End If Next cell7 End If Next cell5 End If Next cell4 ElseIf cell3 = "30/70" Then For Each cell4 In NumI If cell4 = cell3.Offset(0, 2) Then For Each cell5 In NumI If cell5 = cell3.Offset(0, 4) Then For Each cell6 In NumI If cell6 = cell3.Offset(0, 6) Then For Each cell7 In NumDP If cell7 = cell3.Offset(0, 2) Then For Each cell8 In NumDP If cell8 = cell3.Offset(0, 4) Then For Each cell9 In NumDP If cell9 = cell3.Offset(0, 6) Then For Each Cell_Type In Wks_Trade.Range("b11", "b32773") If Cell_Type = "Butterfly" Then For Each Cell_SPL In NumSPL If Cell_SPL = cell3.Offset(0, 2) Then For Each Cell_LPL1 In NumLPL If Cell_LPL1 = cell3.Offset(0, 4) Then For Each Cell_LPL2 In NumLPL If Cell_LPL2 = cell3.Offset(0, 6) Then For a = 1 To n
87
cell3.Offset(0, 7 + a) = 0.3 * cell3.Offset(0, 3) * cell4.Offset(0, 7 + a) * cell7.Offset(0, 7 + a) / (cell5.Offset(0, 7 + a) * cell8.Offset(0, 7 + a)) cell3.Offset(0, 19 + a) = 0.7 * cell3.Offset(0, 3) * cell4.Offset(0, 7 + a) * cell7.Offset(0, 7 + a) / (cell6.Offset(0, 7 + a) * cell9.Offset(0, 7 + a)) Next a For j = 1 To n - 1 cell3.Offset(0, 32 + j) = cell3.Offset(0, 3) * Cell_SPL.Offset(0, 8 + j) + cell3.Offset(0, 7 + j) * Cell_LPL1.Offset(0, 8 + j) + cell3.Offset(0, 19 + j) * Cell_LPL2.Offset(0, 8 + j) Next j End If Next Cell_LPL2 End If Next Cell_LPL1 End If Next Cell_SPL End If Next Cell_Type End If Next cell9 End If Next cell8 End If Next cell7 End If Next cell6 End If Next cell5 End If Next cell4 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ElseIf cell3 = "Cash & Duration Neutral" Then For Each cell4 In NumI If cell4 = cell3.Offset(0, 2) Then For Each cell5 In NumI
88
If cell5 = cell3.Offset(0, 4) Then For Each cell6 In NumI If cell6 = cell3.Offset(0, 6) Then For Each cell7 In NumDP If cell7 = cell3.Offset(0, 2) Then For Each cell8 In NumDP If cell8 = cell3.Offset(0, 4) Then For Each cell9 In NumDP If cell9 = cell3.Offset(0, 6) Then For Each cell10 In NumCP If cell10 = cell3.Offset(0, 2) Then For Each cell11 In NumCP If cell11 = cell3.Offset(0, 4) Then For Each cell12 In NumCP If cell12 = cell3.Offset(0, 6) Then '''''''''''''''''''''''''''''''''''''''''''''''''' For Each Cell_Type In Wks_Trade.Range("b11", "b32773") If Cell_Type = "Butterfly" Then For Each Cell_SPL In NumSPL If Cell_SPL = cell3.Offset(0, 2) Then For Each Cell_LPL1 In NumLPL If Cell_LPL1 = cell3.Offset(0, 4) Then For Each Cell_LPL2 In NumLPL If Cell_LPL2 = cell3.Offset(0, 6) Then ''''''''''''''''''''''''''''''''''''''''''''' For a = 1 To n '''''''''''''''''y matrix''''''''''''''''''''''' Wks_Trade.Range("a101") = cell3.Offset(0, 3) * cell4.Offset(0, 7 + a) * cell7.Offset(0, 7 + a) Wks_Trade.Range("a102") = cell3.Offset(0, 3) * cell10.Offset(0, 7 + a) * cell7.Offset(0, 7 + a) ''''''''''''''''x matrix'''''''''''''''''''''''' Wks_Trade.Range("b101") = cell5.Offset(0, 7 + a) * cell8.Offset(0, 7 + a) Wks_Trade.Range("b102") = cell11.Offset(0, 7 + a) * cell8.Offset(0, 7 + a) Wks_Trade.Range("c101") = cell6.Offset(0, 7 + a) * cell9.Offset(0, 7 + a) Wks_Trade.Range("c102") = cell12.Offset(0, 7 + a) * cell9.Offset(0, 7 + a) ''''''''''matrix calculation'''''''''''' Wks_Trade.Range("d101", "e102") = Application.WorksheetFunction.MInverse(Wks_Trade.Range("b101", "c102")) Wks_Trade.Range("f101", "f102") = Application.WorksheetFunction.MMult(Wks_Trade.Range("d101", "e102"), Wks_Trade.Range("a101", "a102"))
89
cell3.Offset(0, 7 + a) = Wks_Trade.Range("f101") cell3.Offset(0, 19 + a) = Wks_Trade.Range("f102") ' cell3.Offset(0, 7 + a) = (cell3.Offset(0, 3) * cell4.Offset(0, 7 + a) * cell7.Offset(0, 7 + a) - cell3.Offset(0, 19 + a) * cell6.Offset(0, 7 + a) * cell9.Offset(0, 7 + a)) / (cell5.Offset(0, 7 + a) * cell8.Offset(0, 7 + a)) 'cell3.Offset(0, 19 + a) = (cell3.Offset(0, 3) * cell10.Offset(0, 7 + a) * cell7.Offset(0, 7 + a) - cell3.Offset(0, 7 + a) * cell11.Offset(0, 7 + a) * cell8.Offset(0, 7 + a)) / (cell12.Offset(0, 7 + a) * cell9.Offset(0, 7 + a)) Next a For j = 1 To n - 1 cell3.Offset(0, 32 + j) = cell3.Offset(0, 3) * Cell_SPL.Offset(0, 8 + j) + cell3.Offset(0, 7 + j) * Cell_LPL1.Offset(0, 8 + j) + cell3.Offset(0, 19 + j) * Cell_LPL2.Offset(0, 8 + j) Next j '''''''''''''''''''''''''''''' End If Next Cell_LPL2 End If Next Cell_LPL1 End If Next Cell_SPL End If Next Cell_Type ''''''''''''''''''''''''''''''''''''''''''''''' End If Next cell12 End If Next cell11 End If Next cell10 End If Next cell9 End If Next cell8 End If Next cell7 End If Next cell6 End If Next cell5 End If Next cell4 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ElseIf cell3 = "Duration & Covexity neutral" Then
90
For Each cell4 In NumI If cell4 = cell3.Offset(0, 2) Then For Each cell5 In NumI If cell5 = cell3.Offset(0, 4) Then For Each cell6 In NumI If cell6 = cell3.Offset(0, 6) Then For Each cell7 In NumDP If cell7 = cell3.Offset(0, 2) Then For Each cell8 In NumDP If cell8 = cell3.Offset(0, 4) Then For Each cell9 In NumDP If cell9 = cell3.Offset(0, 6) Then For Each cell10 In NumC If cell10 = cell3.Offset(0, 2) Then For Each cell11 In NumC If cell11 = cell3.Offset(0, 4) Then For Each cell12 In NumC If cell12 = cell3.Offset(0, 6) Then For Each Cell_Type In Wks_Trade.Range("b11", "b32773") If Cell_Type = "Butterfly" Then For Each Cell_SPL In NumSPL If Cell_SPL = cell3.Offset(0, 2) Then For Each Cell_LPL1 In NumLPL If Cell_LPL1 = cell3.Offset(0, 4) Then For Each Cell_LPL2 In NumLPL If Cell_LPL2 = cell3.Offset(0, 6) Then For a = 1 To n '''''''''''''''''y matrix''''''''''''''''''''''' Wks_Trade.Range("a103") = cell3.Offset(0, 3) * cell4.Offset(0, 7 + a) * cell7.Offset(0, 7 + a) Wks_Trade.Range("a104") = cell3.Offset(0, 3) * cell10.Offset(0, 7 + a) * cell7.Offset(0, 7 + a) ''''''''''''''''x matrix'''''''''''''''''''''''' Wks_Trade.Range("b103") = cell5.Offset(0, 7 + a) * cell8.Offset(0, 7 + a) Wks_Trade.Range("b104") = cell11.Offset(0, 7 + a) * cell8.Offset(0, 7 + a) Wks_Trade.Range("c103") = cell6.Offset(0, 7 + a) * cell9.Offset(0, 7 + a) Wks_Trade.Range("c104") = cell12.Offset(0, 7 + a) * cell9.Offset(0, 7 + a) ''''''''''matrix calculation''''''''''''
91
Wks_Trade.Range("d103", "e104") = Application.WorksheetFunction.MInverse(Wks_Trade.Range("b103", "c104")) Wks_Trade.Range("f103", "f104") = Application.WorksheetFunction.MMult(Wks_Trade.Range("d103", "e104"), Wks_Trade.Range("a103", "a104")) cell3.Offset(0, 7 + a) = Wks_Trade.Range("f103") cell3.Offset(0, 19 + a) = Wks_Trade.Range("f104") ' cell3.Offset(0, 7 + a) = (cell3.Offset(0, 3) * cell4.Offset(0, 7 + a) * cell7.Offset(0, 7 + a) - cell3.Offset(0, 19 + a) * cell6.Offset(0, 7 + a) * cell9.Offset(0, 7 + a)) / (cell5.Offset(0, 7 + a) * cell8.Offset(0, 7 + a)) 'cell3.Offset(0, 19 + a) = (cell3.Offset(0, 3) * cell10.Offset(0, 7 + a) * cell7.Offset(0, 7 + a) - cell3.Offset(0, 7 + a) * cell11.Offset(0, 7 + a) * cell8.Offset(0, 7 + a)) / (cell12.Offset(0, 7 + a) * cell9.Offset(0, 7 + a)) Next a For j = 1 To n - 1 cell3.Offset(0, 32 + j) = cell3.Offset(0, 3) * Cell_SPL.Offset(0, 8 + j) + cell3.Offset(0, 7 + j) * Cell_LPL1.Offset(0, 8 + j) + cell3.Offset(0, 19 + j) * Cell_LPL2.Offset(0, 8 + j) Next j End If Next Cell_LPL2 End If Next Cell_LPL1 End If Next Cell_SPL End If Next Cell_Type End If Next cell12 End If Next cell11 End If Next cell10 End If Next cell9 End If Next cell8 End If Next cell7 End If Next cell6 End If Next cell5 End If Next cell4
92
End If Next cell3
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim cella, cellb As RangeDim t, q As Integer
Dim Wks_CF As WorksheetDim rng_CF As Range
Set Wks_CF = Worksheets("CF")Set rng_CF = Wks_CF.Range("a1", "a32773")
Dim CellF As RangeDim CellBond, CellFuture, Par, Cellbondc As Range
For Each cella In Wks_Trade.Range("B11", "b32773")
If cella = "basis" Then For Each cellb In rng_CF
If cellb = cella.Offset(0, 1) Then For t = 1 To n cella.Offset(0, t + 6) = -cella.Offset(0, 2) * cellb.Offset(0, 1) / 100000 '''''''''''''how many futures'''' cella.Offset(0, t + 6).NumberFormat = "0" Next t End If Next cellb If cella.Offset(0, 1).Value > 0 Then For Each CellBond In Wks_LPL.Range("a7", "a32773")
If CellBond = cella.Offset(0, 1) Then For Each CellFuture In Worksheets("Data").Range("b7", "b32773") If CellFuture = cella.Offset(0, 3) Then For q = 1 To n - 1 cella.Offset(0, q + 31) = cella.Offset(0, 2) * CellBond.Offset(0, 8 + q) + cella.Offset(0, 7 + q) * (CellFuture.Offset(0, 7 + q) - CellFuture.Offset(0, 6 + q)) * 1000 Next q
93
End If
Next CellFuture
End If Next CellBond ElseIf cella.Offset(0, 1).Value < 0 Then For Each CellBond In Wks_SPL.Range("a7", "a32773")
If CellBond = cella.Offset(0, 1) Then For Each CellFuture In Worksheets("Data").Range("b7", "b32773") If CellFuture = cella.Offset(0, 3) Then For q = 1 To n - 1 cella.Offset(0, q + 31) = (-cella.Offset(0, 2)) * CellBond.Offset(0, 8 + q) + cella.Offset(0, 7 + q) * (-CellFuture.Offset(0, 6 + q) + CellFuture.Offset(0, 7 + q)) * 1000 Next q End If
Next CellFuture
End If Next CellBond End If
End If
Next cella
End Sub
Public Sub Color()
Dim TradePL As Range
Set TradePL = Worksheets("Trade").Range("AH11", "AR23")
Dim j, i As Integer
94
For j = 1 To 11
For i = 1 To 13 If TradePL.Cells(i, j).Value > 0 Then TradePL.Cells(i, j).Select With Selection.Interior .ColorIndex = 3 .Pattern = xlSolid End With ElseIf TradePL.Cells(i, j).Value < 0 Then TradePL.Cells(i, j).Select With Selection.Interior .ColorIndex = 4 .Pattern = xlSolid End With End If Next iNext j
End Sub
Public Sub StdevAdj()
Dim Wks_Trade As Worksheet
Set Wks_Trade = Worksheets("Trade")
Dim Stdev As Range
Set Stdev = Wks_Trade.Range("AT11", "AT23")
''''''''''''''''find the minimum stdev'''''''''''''''''Dim MinS As Double
MinS = Application.WorksheetFunction.Min(Stdev)
Wks_Trade.Range("AT26") = MinS
''''''''''''''find the number of benckmark trade'''''''''''Dim i As Integer
i = 1
Dim Cell1 As Range
For Each Cell1 In Stdev
95
If Cell1 = MinS Then Wks_Trade.Range("AT27") = i End If
i = i + 1
Next Cell1
''''''''''''''go back to change the par amount for 1st portfolio of each trade''''''''''''''
Dim Benck, r, s As Integer
Benck = Wks_Trade.Range("AT27")r = Stdev.Count
''Wks_Trade.Range("AT28") = r
Dim Par As Range
Set Par = Wks_Trade.Range("d11", "d23")
For s = 1 To r
Par.Cells(s, 1) = Par.Cells(Benck, 1) * Stdev(Benck, 1) / Stdev(s, 1)
Next s
Par.Cells(9, 1) = Par.Cells(9, 1) * (-1)Par.Cells(11, 1) = Par.Cells(11, 1) * (-1)
Call TradeCall Color
End Sub
Public Sub Mill()
''''''''''''''''''''set up 1 million for each trade'''''''''''''''''''''
Dim Wks_Trade As Worksheet
Set Wks_Trade = Worksheets("Trade")
Dim Par As Range
Set Par = Wks_Trade.Range("d11", "d23")
Dim r As Integer
r = Par.Count
Dim s As Integer
For s = 1 To r
Par.Cells(s, 1) = 1000000
96
Next s
Par.Select
Selection.Style = "Currency" Par.Cells(9, 1) = Par.Cells(9, 1) * (-1)Par.Cells(11, 1) = Par.Cells(11, 1) * (-1) Call TradeCall ColorEnd Sub
97