1 目錄
* MATLAB隨機數的產生
- Uniform,Normal & Custom distributions
* 蒙特卡洛仿真
* 產生股票價格路徑
* 期權定價
- 經典公式
- 和蒙特卡洛方法比較
- 方差減小技巧
- Exotic Options
* 多變量仿真
- Basket Option
- Portfolio Value at Risk
2 重點內容講解
2.1 蒙特卡洛仿真
- 依賴隨機數生成
- rand,randn,randi
注:rand:產生平均分布隨機數
randn:產生正太分布隨機數
randi:產生隨機整數隨機數
-支持的隨機分布
- 隨機分布擬合
2.2 在統計工具箱里面有更多的隨機數生成函數
2.3 基於MATLAB常用隨機數的舉例
舉例:生成隨機數
%% Uniform distribution % % Numbers uniformly distributed along [0 1] % 產生100個隨機分布的隨機數在[0 1]這個閉區間內 % rand的參數為n*n的矩陣 rU = rand(1,10); hist(rU,10);
圖示:
舉例:生成正太分布隨機數
%% Normal distribution % % Numbers normally distribution with mean0,std1 % 基於均值為0,標准差為1的正態分布隨機數。 % randn的參數為n*n的矩陣 rN = randn(1,1000); hist(rN,1000);
圖示:
舉例:設計隨機種子的方式生成隨機數
%% Setting the behaviour of the random numbers % % There are many implementations of pseudo-random number generator in % MATLAB,we will be working with % % mt19937ar - Mersenne Twister,which has an approximate period of % 2^19937-1 % We can set the behaviour in a number of ways % Seed the generator % 以設定種子的方式設置隨機數 rng(0) [randn(1),randn(1),randn(1),randn(1)] rng(0); [randn(1),randn(1),randn(1),randn(1)] % 由於設定的種子都是一樣的,因此生成的兩組隨機數也是一樣的 % ans = % 0.5377 1.8339 -2.2588 0.8622 % ans = % 0.5377 1.8339 -2.2588 0.8622
舉例:其他產生隨機數的方法
%% Generating random numbers from different distributions % % Lets see a list of the supported distributions docsearch Continuous Distributions % 用random產生隨機數,按照隨機規則產生,具體規則在doc,查看flag內容 %% Now,lets choose a number of draws from one of these,say the exponential % 產生指數的隨機數,[]為矩陣形狀,3為參數,exp為flag rB = random('exp',3,[1 10000]); hist(rB,100);
圖示:
2.3 對數據進行擬合fitdist
2.4 產生股票價格路徑
2.5 公開函數:隨機蒙特卡洛價格路徑:
function mat = pricePaths(S,r,T,sigma,nSims,nSteps) % S ==>> 起始價格 % r ==>> 無風險回報率 % T ==>> 時間寬度 % sigma ==>> 波動率 % nSims ==>> 做多少次蒙特卡洛放在 % nSteps ==>> 在T時間內取多大的步長 % Generate asset price paths using geometric brownian motion % Determine the timestep % 根據時間長度和步長,求出每個均勻分布點是多少長 Dt = T/(nSteps); % Generate the random numbers % 初步隨機數,多少蒙特卡羅仿真*多少步長的矩陣 mat = randn(nSteps,nSims); % Generate the returns scaled using the relevant equation % 布朗運動公式 mat = exp((r-sigma^2/2)*Dt + sigma*sqrt(Dt).*mat); % Generate price paths mat = cumprod(mat,1); % 按照列的方向累乘,從某一天累計的回報率 % Scale with the initial asset price % 初始價格*實際價格=實際價格回報率后的價格 mat = [repmat(S,1,nSims); mat.*S]; end
應用實例:
%% S = 10; % 股票起始價格 r = 0.03; % 無風險收益率 T = 1; % 時間跨度 sigma = 0.2; % 波動率 nSims = 10; % 多少條路徑(多少次蒙特卡洛實驗) nSteps = 250*10; % 步長是多少 這里是2500個步長 paths = pricePaths(S,r,T,sigma,nSims,nSteps); %% Plotting figure; plot(paths);
圖示:我們可以看到以10為起始價格,生成10條蒙特卡洛的隨機股票價格路徑。生成這些隨機的股票價格可以進行一些模型的壓力檢測。不僅在樣本內可以進行檢測,而且在可能會產生的不可知價格路徑下,模型的魯棒性效果如何(Robust)。
再比如我們可以把初始價格設置為3000個點也會生成如下路徑: