辅导案例-FM06

欢迎使用51辅导,51作业君孵化低价透明的学长辅导平台,服务保持优质,平均费用压低50%以上! 51fudao.top
11/9/2020 Coursework-1-2020
file:///home/user/Assignments/Topic5/Coursework-1-2020.tmp.html 1/8
FM06 Coursework 1 - 2020
Before you begin
Every student has a slightly different coursework assignment. To generate your personal
coursework assignment you should first execute every cell in this Jupyter notebook (which you can
do by clicking Validate). You must then answer the questions given in the notebook.
The first cell in this Notebook generates your question for you.
You must complete this assignment by editing the Jupyter notebook distributed to you in your
Assignments folder on CoCalc. You must also create pdf version of the Notebook and upload it to
Keats.
The Jupyter notebook containing your work will be automatically collected after the submission
deadline. You should not make any modifications to your assignment after the deadline until you
have received your mark. Your code will be automatically marked. There are a small number of tests
that you can see will be performed yourself, but most of the tests that will earn marks are hidden
from you. This is why many of the cells that run tests appear to be blank.
The pdf file that you upload will also marked manually. It must be uploaded to Keats so that it can
be viewed using the plagiarism detection software Turnitin. You will find that you get a very high
similarity score on Turnitin because the pdf will include a lot of identical material for different
students. The similarity score will not be used to detect plagiarism, instead other more detailed
Turnitin screens will be used to identify if you have copied other parts of your project from other
students or from other sources.
Reading stock price data from a file
The file stock-data.csv contains weekly historic stock prices for two companies ACME and
BigBank. All prices are in dollars. At each historic time point , you can represent the stock prices as
a vector whose first component is the price of ACME and whose second component is the price
of BigBank. The logs of the stock prices can similarly be represented as vector . Let be
the time interval of 1 week (so for the purposes of this question 1 year contains exactly 52 weeks
and we are using the financial convention of using the year as our unit of time). Write
.
Read the file stock-data.csv into Python and use this to do the following:
In [1]: import pandas
import numpy as np
from math import *
import coursework1lib

question = coursework1lib.Question()
t
S
t
Z
t
δt =
1
52
(δZ)
t
= Z
t+δt
− Z
t
11/9/2020 Coursework-1-2020
file:///home/user/Assignments/Topic5/Coursework-1-2020.tmp.html 2/8
Create a matrix called dZ with rows and columns containing all the weekly changes
in the log stock price. Here is the number of weeks in the sample.
The sample average value of the vector . Store the value as a numpy 2-vector in a
variable mu .
The sample covariance matrix for the change . Store the value as a numpy array in a
variable Sigma .
We have not seen how to read a csv file in the course. You can do this using
pandas.read_csv , or you can use Excel to save the file in the Excel format that we have seen
how to read, or you can use the Python library csv , or you could use some other approach. It is
entirely up to you.
[[1485.211 299.267]
[1568.737 305.82 ]
[1693.157 321.839]
...
[2327. 2437. ]
[2321.5 2476. ]
[2292. 2416. ]]
[[1568.737 305.82 ]
[1693.157 321.839]
[1753.192 362.615]
...
[2327. 2437. ]
[2321.5 2476. ]
[2292. 2416. ]]
[[1485.211 299.267]
[1568.737 305.82 ]
[1693.157 321.839]
...
[2375. 2373. ]
[2327. 2437. ]
[2321.5 2476. ]]
[[ 0.05471399 0.02166054]
[ 0.076324 0.05105473]
[ 0.03484329 0.11929024]
...
N − 1 2
N
(δZ)
t
(δZ)
t
In [2]: # YOUR CODE HERE
#1
stock=np.array(pandas.read_csv('./stock-data.csv').iloc[:,1:])
print(stock)

a=stock[1:,:]
print(a)
b=stock[:-1,:]
print(b)
dZ=np.log(a)-np.log(b)
print(dZ)

#2
mu=np.mean(dZ,axis=0)
print(mu)

#3
Sigma=np.cov(dZ.transpose())
print(Sigma)
11/9/2020 Coursework-1-2020
file:///home/user/Assignments/Topic5/Coursework-1-2020.tmp.html 3/8
[-0.02041755 0.0266128 ]
[-0.00236636 0.01587658]
[-0.01278873 -0.02453107]]
[0.00059191 0.00284929]
[[0.0013018 0.00041908]
[0.00041908 0.00102101]]
Help on built-in function sqrt in module math:
sqrt(x, /)
Return the square root of x.
Simulating stock prices
Assume that over future weekly intervals, the changes in the log stock prices will follow a
mutlivariate normal distribution with mean and covariance matrix . You should assume that each
week's increments are independent of each other. Write for the final time in the historic data
so that give the stock prices at the final time in the historic data. Generate simulated stock
price vectors prices at time . You should store your simulation in a variable called
simulated_S which should be a numpy array with rows and 2 columns.
You must also explain mathematically how you performed this computation. You can do this by
giving mathematical difference equations that show how the computation was performed together
with appropriate explanatory text. Your mark will be based in part on the quality of the formatting of
the mathematical formulae.
Solution: Insert your mathematical explanation here. Your mark will be based in part upon the
quality of the formatting of the mathematical formulae.
In [3]: assert mu.shape==(2,)
assert Sigma.shape==(2,2)
In [0]:
In [0]:
(δZ)
t
μ Σ
t = 0
S
0
10
6
t = 1
10
6
In [46]: # YOUR CODE HERE
import pandas as pd
from pandas import DataFrame
import numpy as np
import math as m
from math import *
import matplotlib.pyplot as plt
import sympy as sp
from scipy.stats import norm

def simulate_gbm( S0, mu, Sigma, T, n_steps):
Z = np.zeros([2,2])
dt = T/n_steps
Z[0,0] = sqrt(Sigma[0,0])
Z[1,0] = Sigma[1,0]/sqrt(Sigma[0,0])
11/9/2020 Coursework-1-2020
file:///home/user/Assignments/Topic5/Coursework-1-2020.tmp.html 4/8
[[0. 0.]
[0. 0.]
[0. 0.]
...
[0. 0.]
[0. 0.]
[0. 0.]]
Computing option prices
At time , a trader purchases assets as described below and holds the assets for 52 weeks. To
purchases these assets they must borrow money at the interest rate specified below.
2 units of stock 1.
3 European put options on stock 1 with strike 2408 and maturity 52 weeks.
6 European call options on stock 2 with strike 2368 and maturity 52 weeks.
2 European call options on stock 2 with strike 2606 and maturity 52 weeks.
The continuously compounded interest rate is r=0.07.
A European call option with strike and maturity on a stock is a derivative which gives a payout
Z[1,1] = sqrt(Sigma[1,1]-(Sigma[1,0]**2)/Sigma[0,0])
S = np.zeros([n_steps+1,2])
S[0,:] = S0
P = np.random.randn(52,2)

for i in range(0,n_steps+1):
S[i,0] = S[i-1,0]*e**(mu[0]*dt+np.sqrt(dt)*Z[0,0]*P[i-1,0])
S[i,1] = S[i-1,0]*e**(mu[1]*dt+np.sqrt(dt)*Z[1,0]*P[i-1,0]+Z[1,1]*P[i-1,1])
return S

n_scenarios=1000000
n_step=52
S0=stock[0,:]
T=1
simulated_S=np.zeros([n_scenarios,2])
for i in range(0,n_scenarios):
simulated_S[i,:]=simulate_gbm(S0,mu,Sigma,T,n_steps)[n_steps,:]
print(simulated_S)
In [41]: n_scenarios = 1000000
n_steps = 52
assert simulated_S.shape==(n_scenarios,2)
In [0]:
In [0]:
0
In [6]: question.describe_portfolio()
Out[6]:
K T
11/9/2020 Coursework-1-2020
file:///home/user/Assignments/Topic5/Coursework-1-2020.tmp.html 5/8
of at the maturity, where is the price of the stock time . A European put
option with strike and maturity gives a payout of at maturity.
You should assume that the options are purchased at the Black-Scholes price. For a call option with
strike and maturity , on a stock with price at time , this is computed using the formula
where
and
Here is the cumulative distribution function of the standard normal distribution, and is a
parameter called the volatility. For stock , you should assume where is the -
week covariance matrix of the changes in the log stock price.
This formula will be explained later in the course. For now you simply need to write a Python
function which can compute it. Since you do not yet know the theory used to derived this formula, I
have provided some tests that you can use to check your have implemented this formula correctly.
File "", line 3
d_2 = (log(S0/K)+(r-(sigma**2/2)*T/(sigma*sqrt(T))
^
SyntaxError: invalid syntax
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in
----> 1 np.testing.assert_almost_equal( black_scholes_call_price( 100, 110, 0.5,
0.1, 0.2), 3.743, decimal=3)
NameError: name 'black_scholes_call_price' is not defined
The Black-Scholes price formula for a European put option with strike and maturity is
max{S
T
−K, 0} S
T
T
K T max{K − S
T
, 0}
K T S
0
0
Call option price = N(d
1
)S
0
−Ke
−rT
N(d
2
)
d
1
= (log(S
0
/K) + (r + )T)
1
σ

T
σ
2
2
d
2
= (log(S
0
/K) + (r − )T) .
1
σ

T
σ
2
2
N σ
i σ =

52Σ
i,i
Σ 1
In [45]: import sympy as sp
from scipy.stats import norm
def black_scholes_call_price(S0,K,T,r,sigma):
d1 = (log(S0/K)+(r+(sigma**2/2)*T/(sigma*sqrt(T))
d2 = (log(S0/K)+(r-(sigma**2/2)*T/(sigma*sqrt(T))
call_price=
return

In [8]: np.testing.assert_almost_equal( black_scholes_call_price( 100, 110, 0.5, 0.1, 0.
K T
e
−rT
KN(−d
2
) −N(−d
1
)S
0
11/9/2020 Coursework-1-2020
file:///home/user/Assignments/Topic5/Coursework-1-2020.tmp.html 6/8
Write a function to compute this.
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
in
----> 1 np.testing.assert_almost_equal( black_scholes_put_price( 100, 110, 0.5,
0.1, 0.2), 8.378, decimal=3)
in black_scholes_put_price(S0, K, T, r, sigma)
1 def black_scholes_put_price(S0,K,T,r,sigma):
2 # YOUR CODE HERE
----> 3 raise NotImplementedError()
NotImplementedError:
Compute the total cost of the portfolio and store the answer in a variable called cost
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
in
1 # YOUR CODE HERE
----> 2 raise NotImplementedError()
NotImplementedError:
Historic volatility
The value is called the historic volatility of stock . The factor of in the forumla for the
historic volatility is a scaling factor to take account of the fact that one usually uses units of a year in
financial calculations. The square root in the formula comes from the fact that is the one-week
variance of stock , and so its square root is the one-week standard deviation.
There are many assumptions required to derive the Black-Scholes price formula including
assumptions on the future volatility of the stock. The parameter in the Black-Scholes formulae
represents this future volatility. In your calculation you have been told to assume that the future
volatility will be equal to the historic volatility, but this is a very unrealistic assumption.
There are often very good reasons to think that future volatility will be different from past volatility.
For example, as I write this question there is an election looming in the United States, so one might
believe that volatility of the US stock market will be high as the election approaches and will drop
after the election when the outcome is known and so there is less political uncertainty. In fact,
In [9]: def black_scholes_put_price(S0,K,T,r,sigma):
e**(r*T)*K*N(-d2)-
In [10]: np.testing.assert_almost_equal( black_scholes_put_price( 100, 110, 0.5, 0.1, 0.2
In [11]: # YOUR CODE HERE
raise NotImplementedError()
In [0]:
√52Σ
i,i
i 52
Σ
i,i
i
σ
11/9/2020 Coursework-1-2020
file:///home/user/Assignments/Topic5/Coursework-1-2020.tmp.html 7/8
volatility is much easier to predict than whether a stock will go up or down. This is one important
reason why real option prices will often be very different from those obtained using the Black-
Scholes formula and historic volatility.
Compute the Value at Risk and Expected Shortfall
After year, the trader liquidates their portfolio and pays of their debt with interest. Compute the -th
percentile of the loss distribution. This gives an estimate of a risk-figure which is called the 52 week,
Value at Risk of the portfolio. Store your answer in a variable called var .
Compute the average value of the loss in all the scenarios where the loss was greater than the
Value at Risk. This gives an estimate of another risk-figure which called the 52 week, %5$ Expected
Shortfall of the portfolio. Store your answer in a variable called es .
Value at Risk and Expected Shortfall figures are often used in the industry and can be computed
over a variety of time-horizons and at different percentage levels.
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
in
1 # YOUR CODE HERE
----> 2 raise NotImplementedError()
NotImplementedError:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in
----> 1 assert es>=var
NameError: name 'es' is not defined
Testing your code
Your code will be tested automatically as part of the marking process. However, you should write
your own tests and explain how they work. The better your tests, the higher your mark will be. For
each test that you write, provide a mathematical description of the test as well as the code that
performs the test.
YOUR ANSWER HERE
1 5
5%
In [12]: # YOUR CODE HERE
raise NotImplementedError()
In [13]: assert es>=var
In [0]:
In [0]:
11/9/2020 Coursework-1-2020
file:///home/user/Assignments/Topic5/Coursework-1-2020.tmp.html 8/8
Discussion
Write a short essay on the topic of risk measurement. For example you could discuss: the history
and purpose of different risk measures including Value at Risk and Expected Shortfall; the relative
merits of different risk alternative approaches to risk-measurement; any limitations of the
calculations you have performed for this exercise. Your essay should take up at most one page
when the notebook is formatted as a pdf.
Be sure to do the following:
Reference scholarly works to justify any claims that you make.
Reference any sources you have used (for example if you have read an article on the internet,
you should reference it)
Use your own words
It is vital to always reference your sources properly and to use your own words otherwise you may
be accused of plagiarism. This is a serious academic offence. In exams it is acceptable to use the
lecturer's own words when answering a question but in your dissertation and in this coursework you
must use your own words.
I am asking you to write a short essay because you will eventually have to write a long dissertation
so it is good to start practicing writing about mathematics. I would give the following general advice:
Try to write something you would enjoy reading.
Don't try to impress the reader with fancy words, impress them with facts and mathematics.
Don't say anything you don't understand yourself.
Say things as clearly and briefly as you can.
If you find it easier to say things with mathematical formulae than in English, then focus on the
mathematical content.
Don't pad what you have to say with waffle just to reach the word limit or to try to look more
impressive.
YOUR ANSWER HERE

欢迎咨询51作业君
51作业君

Email:51zuoyejun

@gmail.com

添加客服微信: abby12468