2018 Edition

Albane Bonnaud & Kim-Anh-Nhi Nguyen

# Estimating Financial Risk through Monte Carlo Simulation
Risk analysis is part of every decision we make when faced with uncertainty, ambiguity, and variability. Indeed, even though we have unprecedented access to information, we can't accurately predict the future. In finance, there is a fair amount of uncertainty and risk involved with estimating the future value of financial products, due to the wide variety of potential outcomes. Monte Carlo simulation (also known as the Monte Carlo Method) allows inspecting many possible outcomes of the decision making process, and can be used to assess the impact of risk: this, in turns, allows for better decision-making under uncertainty.

## Goals
The main objectives we set for this Notebook are as follows:
1. Develop fundamental knowledge about Risk analysis
2. Understand Monte Carlo Simulation (MCS)
3. Apply Monte Carlo Simulation for predicting risk


## Steps
1. First, in section 1, we introduce the basics of MCS
2. In section 2, we work on a simple example to where we apply the MCS method
3. In section 3, we briefly summarize the main characteristics of the Monte Carlo Simulation (MCS) technique
4. In section 4, we overview the common distributions which are often used in MCS
5. In section 5, we work on a real use case, that focuses on estimating financial risk. We will use techniques such as featurization  (that is, generating additional features to improve model accuracy), linear regression, kernel density estimation, sampling distributions and so on ...

## Reference
This Notebook is inspired by Chapter 9 of the book [Advanced Analytics with Spark](http://shop.oreilly.com/product/0636920035091.do) by Josh Wills, Sandy Ryza, Sean Owen, and Uri Laserson. It is strongly suggested to read this Chapter to get a general idea of the topic of this Notebook.

# 1. Introduction

## 1.1. Monte Carlo Simulation (MCS)
Monte Carlo simulation is a computerized mathematical technique that can be applied such that it is possible to account for risk in quantitative analysis and decision making. This technique is used in many different fields, such as R&D, risk management, portfolio management, pricing derivatives, strategic planning, project planning, cost modeling and many more.

In general, MCS is a technique that "converts" uncertainty on input variables of a model into **probability distributions**. By combining the distributions and randomly selecting values from them, it recalculates the simulated model many times, to determine the probability of the output.

Historically, this technique was first used by scientists working on the atomic bomb: it was named after Monte Carlo, the Monaco resort town renowned for its casinos.  Since its introduction in World War II, Monte Carlo simulation has been used to model a variety of physical and conceptual systems.

## 1.2. How does it work?
Monte Carlo simulation performs risk analysis by building models of possible results by *substituting a range of possible input values, that constitute uncertainty, into a statistical distribution*. It then computes possible outcomes repeatedly, each time using a different set of random values from the probability functions that "model" the input. Depending upon the number of random input variables and their distribution, a Monte Carlo simulation could involve thousands or tens of thousands of "rounds" before it is complete. When complete, *Monte Carlo simulation produces distributions of possible outcome values*.

By using probability distributions instead of actual input samples, it is possible to model more accurately uncertainty: different choices of distributions will yield different outputs.

# 2. Illustrative example

Imagine you are the marketing manager for a firm that is planning to introduce a new product. You need to estimate the first-year net profit from this product, which might depend on:

- Sales volume in units
- Price per unit (also called "Selling price")
- Unit cost
- Fixed costs

Net profit will be calculated as $Net Profit = Sales Volume* (Selling Price - Unit cost) - Fixed costs$.  Fixed costs (accounting for various overheads, advertising budget, etc.) are known to be \$ 120,000, which we assume to be deterministic. All other factors, instead, involve some uncertainty: *sales volume* (in units) can cover quite a large range, the *selling price* per unit will depend on competitor actions, which are hard to predict, and *unit costs* will also vary depending on vendor prices and production experience, for example.

Now, to build a risk analysis model, we must first identify the uncertain variables -- which are essentially random variables.  While there's some uncertainty in almost all variables in a business model, we want to focus on variables where the range of values is significant.

## 2.1. Unit sales and unit price

Based on a hypothetical market research you have done, you have beliefs that there are equal chances for the market to be `slow`, `normal`, or `hot`:

- In a "slow" market, you expect to sell 50,000 units at an average selling price of \$11.00 per unit
- In a "normal" market, you expect to sell 75,000 units, but you'll likely realize a lower average selling price of \$10.00 per unit
- In a "hot" market, you expect to sell 100,000 units, but this will bring in competitors, who will drive down the average selling price to \$8.00 per unit

### Question 1
<div class="alert alert-info">
Calculate the average units and the unit price that you expect to sell, which depend on the market state. Use the assumptions above to compute the expected quantity of products and their expected unit price. 
</div>



```python
markets = [{'unit' : 50000, 'price' : 11}, {'unit' : 75000, 'price' : 10}, {'unit' : 100000, 'price' : 8}]

average_unit = sum([x['unit'] for x in markets])/len(markets)
average_price = sum([x['price'] for x in markets])/len(markets)
print("average unit:", average_unit)
print("average_price:", average_price)
```

    average unit: 75000.0
    average_price: 9.666666666666666


<div class="alert alert-warning">

COMMENT :
<li>These results are simple means, computed with the three market scenarios given above. It's a very basic approach. We'll see further if it's enough to model a financial market, which requires precision.</li>

</div>

## 2.2. Unit Cost

Another uncertain variable is Unit Cost. In our illustrative example, we assume that your firm's production manager advises you that unit costs may be anywhere from \$5.50 to \$7.50, with a most likely expected cost of \$6.50. In this case, the most likely cost can be considered as the average cost.

## 2.3. A Flawed Model: using averages to represent our random variables
Our next step is to identify uncertain functions -- also called functions of a random variable.  Recall that Net Profit is calculated as $Net Profit = Sales Volume * (Selling Price - Unit cost) - Fixed costs$.  However, Sales Volume, Selling Price and Unit Cost are all uncertain variables, so Net Profit is an uncertain function.

The simplest model to predict the Net Profit is using average of sales volume, average of selling price and average of unit cost for calculating. So, if only consider averages, we can say that the $Net Profit = 75,000*(9.66666666 - 6.5) - 120,000 \sim 117,500$.

However, as [Dr. Sam Savage](http://web.stanford.edu/~savage/faculty/savage/) warns, "Plans based on average assumptions will be wrong on average." The calculated result is far from the actual value: indeed, the **true average Net Profit** is roughly  \$93,000, as we will see later in the example.

### Question 2
#### Question 2.1
<div class="alert alert-info">
Write a function named `calNetProfit` to calculate the Net Profit using the average of sales volume, the average of selling price and the average of unit cost.
</div>


```python

def calNetProfit(average_unit, average_price, average_unitcost, fixed_cost):
    return ( average_unit * (average_price - average_unitcost) - fixed_cost )

average_unitcost = 6.5
fixed_cost = 120000
NetProfit = calNetProfit(average_unit, average_price, average_unitcost, fixed_cost)
print("Net profit:", NetProfit)

```

    Net profit: 117499.99999999994


<div class="alert alert-warning">

COMMENT :
<li>This result is the profit which is expected when using the primary average approach. Is it reliable ?</li>

</div>


#### Question 2.2
<div class="alert alert-info">
Verify the warning message of Dr. Sam Savage by calculating the error of our estimated Net Profit using averages only. Recall that the true value is roughly \$93,000, so we are interested in:
<ul></ul>

$$ error = \frac{your\_value - true\_value}{true\_value}$$

<ul></ul>
Note also we are interested in displaying the error as a percentage.
<ul></ul>
Looking at the error we make, do you think that we can use the current model that only relies on averages?
</div>


```python
trueNetProfit = 93000
error = (NetProfit - trueNetProfit) / (trueNetProfit)
print("Error in percentage:", error * 100)
```

    Error in percentage: 26.344086021505316


<div class="alert alert-warning">

COMMENT :
<li>An error of more than 26% on the true value is high !</li>
<li>A good prediction should be much below 10%.</li>
<li>Therefore, we can confirm what has been told by Dr. Same Savage : this model using averages is not accurate enough to predict the net profit.</li>
<li>One additional comment: it is not logical to do non linear operations on averages, such as multiplication.</li>

</div>

## 2.4. Using the Monte Carlo Simulation method to improve our model
As discussed before, the selling price and selling volume both depend on the state of the market scenario (slow/normal/hot). So, the net profit is the result of two random variables: `market scenario` (which in turn determines `sales volumes` and `selling price`) and `unit cost`.

Now, let's assume (this is an *a-priori* assumption we make) that `market scenario` follows a discrete, uniform distribution and that `unit cost` also follows a uniform distribution. Then, we can compute directly the values for selling price and selling volumes based on the outcome of the random variable `market scenario`, as shown in Section 2.1.

From these a-priori distributions, in each run (or trial) of our Monte Carlo simulation, we can generate the sample value for each random variable and use it to calculate the Net Profit. The more simulation runs, the more accurate our results will be. For example, if we run the simulation 100,000 times, the average net profit will amount to roughly \$92,600. Every time we run the simulation, a different prediction will be output: the average of such predictions will consistently be less than \$117,500, which we predicted using averages only.

Note also that in this simple example, we generate values for the `market scenario` and `unit cost` independently: we consider them to be **independent random variables**. This means that the eventual (and realistic!) correlation between the `market scenario` and `unit cost` variables is ignored. Later, we will learn how to be more precise and account for dependency between random variables.


### Question 3
#### Question 3.1
<div class="alert alert-info">
Write a function named `get_sales_volume_price` that returns the sales volume and price based on the market scenario. In particular, the scenario can get one of three values:
<ul>
  <li>0: Slow market</li>
  <li>1: Normal market</li>
  <li>2: Hot market</li>
</ul>  

The return value is a tuple in the form: `(sales_volume, price)`
</div>


```python
# Get sales volume and  price based on market scenario
# the function returns a tuple of (sales_volume, price)
def get_sales_volume_price(scenario):
    # Slow market
    if scenario == 0:
        return (50000,11.0)
    # Normal market
    if scenario == 1:
        return (75000,10.0)
    # Hot market
    if scenario == 2:
        return (100000,8.0)
#we used the values given above
```

#### Question 3.2
<div class="alert alert-info">
Run 100,000 Monte Carlo simulations and calculate the average net profit they produce. Then, compare the result to the "average model" we used in the previous questions (the one we called "flawed" model). Put your comments about the discrepancies between a simplistic model, and the more accurate MCS approach.  
<ul></ul>
Note that in each iteration, the `unit_cost` and `market_scenario` are generated according to their distributions. Also, recall what we have seen in Section 2.2: your firm account manager helped you with some research, to determine the variability of your random variables.  
</div>


<div class="label label-success">HINT</div>  

Function `uniform(a,b)` in module `random` generates a number $a<=c<=b$, which is drawn from a uniform distribution.  

Function `randint(a,b)` helps you generating an integer number $a<=c<=b$


```python
import random

total = 0.0
num_simulation = 100000
for i in range(0,num_simulation):
    unit_cost = random.uniform(5.5, 7.5)
    market_scenario = random.randint(0,2)
    sales_volume, price = get_sales_volume_price(market_scenario)
    netProfit = calNetProfit(sales_volume, price, unit_cost, fixed_cost)
    total += netProfit
    
print("average net profit:", total/num_simulation)
```

    average net profit: 92515.68203816004


<div class="alert alert-warning">

COMMENT :
<li>This result is very different from the one obtained with the first basic approach, which was 117499.99999999994 !</li>
<li>The net profit estimated here is much lower, which means that someone using the first approach would run the risk of overestimating one's gains.</li>
<li>Let's compare properly the two models.</li>
</div>


```python
trueNetProfit = 93000
NetProfit=total/num_simulation
error = abs((NetProfit - trueNetProfit) / (trueNetProfit))
print("Error in percentage:", error * 100)

avgProfit = 117499.99999999994
NetProfit=total/num_simulation
error = abs((NetProfit - avgProfit) / (avgProfit))
print("Error in percentage:", error * 100)
```

    Error in percentage: 0.5207720019784505
    Error in percentage: 21.26324932922546


<div class="alert alert-warning">

COMMENT :
<li>Those results mathematically support our previous observations. The true net profit being 93000, our new model brings an error of only 0.45%, when the previous model was leading to a 26% error.</li>
<li>Our new model shows a 21% difference with the first one. </li> 

</div> 


# 3. A brief summary of the Monte Carlo Simulation (MCS) technique

- A MCS allows several inputs to be used at the same time to compute the probability distribution of one or more outputs
- Different types of probability distributions can be assigned to the inputs of the model, depending on any *a-priori* information that is available. When the distribution is completely unknown, a common technique is to use a distribution computed by finding the best fit to the data you have
- The MCS method is also called a **stochastic method** because it uses random variables. Note also that the general assumption is for input random variables to be independent from each other. When this is not the case, there are techniques to account for correlation between random variables.
- A MCS generates the output as a range instead of a fixed value and shows how likely the output value is to occur in that range. In other words, the model outputs a probability distribution.

# 4. Common distributions used in MCS
In what follows, we summarize the most common probability distributions that are used as *a-priori* distributions for input random variables:

- *Normal/Gaussian Distribution*: this is a continuous distribution applied in situations where the mean and the standard deviation of a given input variable are given, and the mean represents the most probable value of the variable. In other words, values "near" the mean are most likely to occur.  This is symmetric distribution, and it is not bounded in its co-domain. It is very often used to  describe natural phenomena, such as people’s heights, inflation rates, energy prices, and so on and so forth. An illustration of a normal distribution is given below:


- *Lognormal Distribution*: this is a distribution which is appropriate for variables taking values in the range $[0, \infty]$. Values are positively skewed, not symmetric like a normal distribution.  Examples of variables described by some lognormal distributions include, for example, real estate property values, stock prices, and oil reserves. An illustration of a lognormal distribution is given below:
 

- *Triangular Distribution*: this is a continuous distribution with fixed minimum and maximum values. It is bounded by the minimum and maximum values and can be either symmetrical (the most probable value = mean = median) or asymmetrical. Values around the most likely value (e.g. the mean) are more likely to occur.  Variables that could be described by a triangular distribution include, for example, past sales history per unit of time and inventory levels. An illustration of a triangular distribution is given below:


- *Uniform Distribution*: this is a continuous distribution bounded by known minimum and maximum values. In contrast to the triangular distribution, the likelihood of occurrence of the values between the minimum and maximum is the same. In other words, all values have an equal chance of occurring, and the distribution is simply characterized by the minimum and maximum values. Examples of variables that can be described by a uniform distribution include manufacturing costs or future sales revenues for a new product. An illustration of the uniform distribution is given below:


- *Exponential Distribution*: this is a continuous distribution used to model the time that pass between independent occurrences, provided that the rate of occurrences is known. An example of the exponential distribution is given below:


- *Discrete Distribution* : for this kind of distribution, the "user" defines specific values that may occur and the likelihood of each of them.  An example might be the results of a lawsuit: 20% chance of positive verdict, 30% change of negative verdict, 40% chance of settlement, and 10% chance of mistrial.


# 5. A real use case: estimating the financial risk of a portfolio of stocks
We hope that by now you have a good understanding about Monte Carlo simulation. Next, we apply this method to a real use case: *financial risk estimation*.

Imagine that you are an investor on the stock market. You plan to buy some stocks and you want to estimate the maximum loss you could incur after two weeks of investing. This is the quantity that the financial statistic "Value at Risk" (VaR) seeks to measure. [VaR](https://en.wikipedia.org/wiki/Value_at_risk) is defined as a measure of investment risk that can be used as a reasonable estimate of the maximum probable loss for a value of an investment portfolio, over a particular time period. A VaR statistic depends on three parameters: a portfolio, a time period, and a confidence level. A VaR of 1 million dollars with a 95% confidence level over two weeks, indicates the belief that the portfolio stands only a 5% chance of losing more than 1 million dollars over two weeks. VaR has seen widespread use across financial services organizations. This statistic plays a vital role in determining how much cash investors must hold to meet the credit ratings that they seek. In addition, it is also used to understand the risk characteristics of large portfolios: it is a good idea to compute the VaR before executing trades, such that it can help take informed decisions about investments. 

Our goal is calculating VaR of two weeks interval with 95% confidence level and the associated [VaR confidence interval](http://www.investopedia.com/ask/answers/041615/whats-difference-between-confidence-level-and-confidence-interval-value-risk-var.asp).


## 5.1. Terminology
In this use case, we will use some terms that might require a proper definition, given the domain. This is what we call the *Domain Knowledge*.

- **Instrument**: A tradable asset, such as a bond, loan, option, or stock investment. At any particular time, an instrument is considered to have a value, which is the price for which it can be sold. In the use case of this notebook, instruments are stock investments.
- **Portfolio**: A collection of instruments owned by a financial institution. 
- **Return**: The change in an instrument or portfolio’s value over a time period. 
- **Loss**: A negative return. 
- **Index**: An imaginary portfolio of instruments. For example, the NASDAQ Composite index includes about 3,000 stocks and similar instruments for major US and international companies. 
- **Market factor**: A value that can be used as an indicator of macro aspects of the financial climate at a particular time. For example, the value of an index, the Gross Domestic Product of the United States, or the exchange rate between the dollar and the euro. We will often refer to market factors as just factors.

## 5.2. The context of our use case
We have a list of instruments that we plan to invest in. The historical data of each instrument has been collected for you. For simplicity, assume that the returns of instruments at a given time, depend on 4 market factors only: 

- GSPC value
- IXIC value 
- The return of crude oil
- The return of treasury bonds

Our goal is building a model to predict the loss after two weeks' time interval with confidence level set to 95%.

As a side note, it is important to realize that the approach presented in this Notebook is a simplified version of what would happen in a real Financial firm. For example, the returns of instruments at a given time often depend on more than 4 market factors only! Moreover, the choice of what constitute an appropriate market factor is an art!



## 5.3. The Data
The stock data can be downloaded (or scraped) from Yahoo! by making a series of REST calls. The data includes multiple files. Each file contains the historical information of each instrument that we want to invest in. The data is in the following format (with some samples):
```
Date, Open, High, Low, Close, Volume, Adj Close
2016-01-22,66.239998,68.07,65.449997,67.860001,137400,67.860001
2016-01-21,65.410004,66.18,64.459999,65.050003,148000,65.050003
2016-01-20,64.279999,66.32,62.77,65.389999,141300,65.389999
2016-01-19,67.720001,67.989998,64.720001,65.379997,178400,65.379997
```

The data of GSPC and IXIC values (our two first market factors) are also available on Yahoo! and use the very same format. 

The crude oil and treasure bonds data is collected from investing.com, and has a different format, as shown below (with some samples):
```
Date    Price   Open    High    Low     Vol.    Change %
Jan 25, 2016    32.17   32.36   32.44   32.10   -       -0.59%
Jan 24, 2016    32.37   32.10   32.62   31.99   -       0.54%
Jan 22, 2016    32.19   29.84   32.35   29.53   -       9.01%
Jan 21, 2016    29.53   28.35   30.25   27.87   694.04K 11.22%
Jan 20, 2016    26.55   28.33   28.58   26.19   32.11K  -6.71%
Jan 19, 2016    28.46   29.20   30.21   28.21   188.03K -5.21%
```

In our use case, the factors' data will be used jointly to build a statistical model: as a consequence, we first need to preprocess the data to proceed.

## 5.4. Data preprocessing
In this Notebook, all data files have been downloaded for you, such that you can focus on pre-processing. Next, we will:

  - Read the factor data files which are in two different formats, process and merge them together
  - Read the stock data and pre-process it
  - Trim all data into a specific time region
  - Fill in the missing values
  - Generate the data of returns in each two weeks' time interval window
  
### Factor data pre-processing

We need two functions to read and parse data from Yahoo! and Investing.com respectively. We are interested only in information about the time and the corresponding returns of a factor or an instrument: as a consequence, we will project away many columns of our RAW data, and keep only the information we are interested in.

The 3000-instrument and the 4-factor history are small enough to be read and processed locally: we do not need to use the power of parallel computing to proceed. Note that this is true also for larger cases with hundreds of thousands of instruments and thousands of factors. The need for a distributed system like Spark comes in when actually **running** the Monte Carlo simulations, which can require massive amounts of computation on each instrument. 

### Question 4
#### Question 4.1
<div class="alert alert-info">
Write a function named `readInvestingDotComHistory` to parse data from investing.com based on the format specified above (see Section 5.3). Recall that we use two factors here: one that is related to the price of crude oil, one that is related to some specific US bonds. 

<ul></ul>

Print the first 5 entries of the first factor (crude oil price) in the parsed data.

<ul></ul>

Note that we are only interested in the date and price of stocks.

</div>

<div class="label label-success">HINT</div>  
You can parse a string to `datetime` object by using the function `strptime(<string>, <dtime_format>)`. In this case, the datetime format is `"%b %d, %Y"`. For more information, please follow this [link](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior).

In the next cell, we simply copy data from our HDFS cluster (that contains everything we need for this Notebook) to the instance (a Docker container) running your Notebook. This means that you will have "local" data that you can process without using Spark. Note the folder location: find and verify that you have correctly downloaded the files!


```python
! [ -d monte-carlo-risk ] || (echo "Downloading prepared data from HDFS. Please wait..." ; hdfs dfs -copyToLocal /datasets/monte-carlo-risk . ; echo "Done!";)
```

    Downloading prepared data from HDFS. Please wait...
    Done!



```python
from datetime import datetime
from datetime import timedelta
from itertools import islice
%matplotlib inline
import numpy as np
import statsmodels.api as sm

base_folder = "monte-carlo-risk/"

factors_folder= base_folder + "factors/"

# read data from local disk
def readInvestingDotComHistory(fname):
    def process_line(line):
        cols = line.split('\t') #each column is separated by a tabulation (tab)
        date = datetime.strptime(cols[0], '%b %d, %Y') #we return a parsed datetime (first column) corresponding to the format: month day, year.
        value = float(cols[1]) #the price of stock is the second column
        return (date, value)
    
    with open(fname) as f:
        content_w_header = f.readlines()
        # remove the first line 
        # and reverse lines to sort the data by date, in ascending order
        content = content_w_header[1:]
        return (sorted(list(map(process_line , content)), key=lambda x: x[0]))

factor1_files = ['crudeoil.tsv', 'us30yeartreasurybonds.tsv']
factor1_files = map(lambda fn: factors_folder + fn, factor1_files)
factors1 = [readInvestingDotComHistory(f) for f in factor1_files]

print(factors1[0][:5]) #Print the first 5 entries of the first factor (crude oil price) in the parsed data

```

    [(datetime.datetime(2006, 1, 26, 0, 0), 66.26), (datetime.datetime(2006, 1, 27, 0, 0), 67.76), (datetime.datetime(2006, 1, 30, 0, 0), 68.35), (datetime.datetime(2006, 1, 31, 0, 0), 67.92), (datetime.datetime(2006, 2, 1, 0, 0), 66.56)]


Now, the data structure `factors1` is a list, containing data that pertains to two (out of a total of four) factors that influence the market, as obtained by investing.com. Each element in the list is a tuple, containing some sort of timestamp, and the value of one of the two factors discussed above. From now on, we call these elements "**records**" or "**entries**". Visually, `factors1` looks like this:

| 0 (crude oil) | 1 (US bonds)|
| --- | --- |
| time_stamp, value | time_stamp, value |
| ... | ... |
| time_stamp, value | time_stamp, value |
| ... | ... |


#### Question 4.2
<div class="alert alert-info">
Write a function named `readYahooHistory` to parse data from yahoo.com based on its format, as described in Section 5.3.  
<ul></ul>
Print the first 5 entries of the first factor (namely GSPC). Comment the time range of the second batch of data we use in our Notebook.  
<ul></ul>

Note that we are only interested in the date and price of stocks.
</div>

<div class="label label-danger">NOTE</div> The datetime format now is in a different format than the previous one.

<div class="label label-success">HINT</div> Use a terminal (or put the bash commands inline in your Notebook) to list filenames in your local working directory to find and have a look at your local files.


```python
# read data from local disk
def readYahooHistory(fname):
    def process_line(line):
        cols = line[:-1].split(',')
        date = datetime.strptime(cols[0], '%Y-%m-%d') #datetime is the first column in the format Year-month-day
        value = float(cols[6]) #the price is the "close" price
        return (date, value)
    
    with open(fname) as f:
        content_w_header = f.readlines()
        # remove the first line 
        # and reverse lines to sort the data by date, in ascending order
        content = content_w_header[1:]
        return (sorted(list(map(process_line , content)), key=lambda x: x[0]))
    

factor2_files = ['GSPC.csv', 'IXIC.csv']
factor2_files = map(lambda fn: factors_folder + fn, factor2_files)

factors2 = [readYahooHistory(f) for f in factor2_files]

print(factors2[0][:5], '\n')
```

    [(datetime.datetime(1950, 1, 3, 0, 0), 16.66), (datetime.datetime(1950, 1, 4, 0, 0), 16.85), (datetime.datetime(1950, 1, 5, 0, 0), 16.93), (datetime.datetime(1950, 1, 6, 0, 0), 16.98), (datetime.datetime(1950, 1, 9, 0, 0), 17.08)] 
    


<div class="alert alert-warning">

COMMENT :
<ul><li>We just processed our stock data, in order to get a list format, only containing the date and the corresponding adjusted close price (which is often used when examining historical returns or performing a detailed analysis on historical returns)</li>
</ul>

</div> 

Now, the data structure `factors2` is again list, containing data that pertains to the next two (out of a total of four) factors that influence the market, as obtained by Yahoo!. Each element in the list is a tuple, containing some sort of timestamp, and the value of one of the two factors discussed above. Visually, `factors2` looks like this:

| 0 (GSPC) | 1 (IXIC)|
| --- | --- |
| time_stamp, value | time_stamp, value |
| ... | ... |
| time_stamp, value | time_stamp, value |
| ... | ... |


### Stock data pre-processing

Next, we prepare the data for the instruments we consider in this Notebook (i.e., the stocks we want to invest in). 

#### Question 4.3

<div class="alert alert-info">
In this Notebook, we assume that we want to invest on the first 35 stocks out of the total 3000 stocks present in our datasets.

<ul></ul>

Load and prepare all the data for the considered instruments (the first 35 stocks) which have historical information for more than 5 years. This means that all instruments with less than 5 years of history should be removed.

</div>

<div class="label label-success">HINT</div> we suggest to open a terminal window (not on your local machine, but the Notebook terminal that you can find on the Jupyter dashboard) and visually check the contents of the directories holding our dataset, if you didn't do this before! Have a look at how stock data is organized!


```python
from os import listdir
from os.path import isfile, join

stock_folder = base_folder + 'stocks'

def process_stock_file(fname):
    try:
        #we have seen thanks to the terminal that the stocks are stored in the Yahoo History format
        donnees=readYahooHistory(fname)
        return (donnees)
    except Exception as e:
        raise e
        return None


# select path of all stock data files in "stock_folder"
files = [join(stock_folder, f) for f in listdir(stock_folder) if isfile(join(stock_folder, f))]

# assume that we invest only the first 35 stocks (for faster computation)
files = files[:35]

# read each line in each file, convert it into the format: (date, value)
rawStocks = [process_stock_file(f) for f in files]

# select only instruments which have more than 5 years of history
# Note: the number of business days in a year is 260
number_of_years = 5
rawStocks = list(filter(lambda instrument: len(instrument)>number_of_years*260, rawStocks))

# For testing, print the first 5 entry of the first stock
print(rawStocks[0][:5])

print("\nInstruments with more that 5 years of history:", len(rawStocks))
```

    [(datetime.datetime(1997, 8, 14, 0, 0), 6.011436), (datetime.datetime(1997, 8, 15, 0, 0), 6.473854), (datetime.datetime(1997, 8, 18, 0, 0), 7.47576), (datetime.datetime(1997, 8, 19, 0, 0), 7.39869), (datetime.datetime(1997, 8, 20, 0, 0), 7.39869)]
    
    Instruments with more that 5 years of history: 29


<div class="alert alert-warning">

COMMENT :
<li>We have filtered 29 stocks out of 35 that had more than 5 years of history.</li>

</div>

### Time alignment for our data
Different types of instruments may trade on different days, or the data may have missing values for other reasons, so it is important to make sure that our different histories align. First, we need to trim all of our time series to the same region in time. Then, we need to fill in missing values. To deal with time series that have missing values at the start and end dates in the time region, we simply fill in those dates with nearby values in the time region.

#### Question 4.4
<div class="alert alert-info">
Assume that we only focus on the data from 23/01/2009 to 23/01/2014. Write a function named `trimToRegion` to select only the records in that time interval. 

<ul></ul>

**Requirements**: after processing, each instrument $i$ has a list of records: $[r_0, r_2,...,r_{m_i}]$ such that $r_0$ and $r_{m_i}$ are assigned, respectively, the first and the last values corresponding to the extremes of the given time interval. For example: $r_0$ should contain the value at date 23/01/2009.
</div>


```python
# note that the data of crude oil and treasury is only available starting from 26/01/2006 
start = datetime(year=2009, month=1, day=23)
end = datetime(year=2014, month=1, day=23)

def trimToRegion(history, start, end):
    def isInTimeRegion(entry):
        (date, value) = entry
        return date >= start and date <= end

    # only select entries which are in the time region
    trimmed = list(filter( isInTimeRegion, history))
    
    # if the data has incorrect time boundaries, add time boundaries
    if trimmed[0][0] != start:
        trimmed.insert(0, (start, trimmed[0][1]))
    if trimmed[-1][0] != end:
        trimmed.append((end, trimmed[-1][1]))
    return trimmed
    
# test our function
trimmedStock0  = trimToRegion(rawStocks[0], start, end)
# the first 5 records of stock 0
print(trimmedStock0[:5])
# the last 5 records of stock 0
print(trimmedStock0[-5:])

assert(trimmedStock0[0][0] == start), "the first record must contain the price in the first day of time interval"
assert(trimmedStock0[-1][0] == end), "the last record must contain the price in the last day of time interval"
```

    [(datetime.datetime(2009, 1, 23, 0, 0), 16.254108), (datetime.datetime(2009, 1, 26, 0, 0), 16.470275), (datetime.datetime(2009, 1, 27, 0, 0), 16.703071), (datetime.datetime(2009, 1, 28, 0, 0), 17.975132), (datetime.datetime(2009, 1, 29, 0, 0), 16.478589)]
    [(datetime.datetime(2014, 1, 16, 0, 0), 35.571935), (datetime.datetime(2014, 1, 17, 0, 0), 35.552912), (datetime.datetime(2014, 1, 21, 0, 0), 35.971404), (datetime.datetime(2014, 1, 22, 0, 0), 36.019202), (datetime.datetime(2014, 1, 23, 0, 0), 35.149312)]


<div class="alert alert-warning">

COMMENT :
<li>We can indeed notice that our data has been trimmed to the time region that we wanted, by looking at the extremes of stocks dates.</li>

</div>

### Dealing with missing values
We expect that we have the price of instruments and factors **in each business day**. Unfortunately, there are many missing values in our data: this means that we miss data for some days, e.g. we have data for the Monday of a certain week, but not for the subsequent Tuesday. So, we need a function that helps filling these missing values.

Next, we provide to you the function to fill missing value: read it carefully!


```python
def fillInHistory(history, start, end):
    curr = history
    filled = []
    idx = 0
    curDate = start
    numEntries = len(history)
    while curDate < end:
        
        # if the next entry is in the same day
        # or the next entry is at the weekend
        # but the curDate has already skipped it and moved to the next monday
        # (only in that case, curr[idx + 1][0] < curDate )
        # then move to the next entry
        while idx + 1 < numEntries and curr[idx + 1][0] <= curDate:
            idx +=1

        # only add the last value of instrument in a single day
        # check curDate is weekday or not
        # 0: Monday -> 5: Saturday, 6: Sunday
        if curDate.weekday() < 5:
            
            filled.append((curDate, curr[idx][1]))
            # move to the next business day
            curDate += timedelta(days=1)
        
        # skip the weekends
        elif curDate.weekday() >= 5:
            # if curDate is Sat, skip 2 days, otherwise, skip 1 day
            curDate += timedelta(days=(7-curDate.weekday()))

    return filled
```

<div class="alert alert-warning">

COMMENT :
<li>After having "trimmed" the data to select only the records in the time interval [23/01/2009, 23/01/2014], the purpose is to fill the blanks in our data. Indeed we don't want to face missing values.</li>
<li>For this, when a value is missing, we give it the last value we had for the instrument.</li>

</div>

#### Question 4.5
<div class="alert alert-info">
Trim data of stocks and factors into the given time interval.
</div>


```python
#print (rawStocks[0])

# trim into a specific time region
# and fill up the missing values
stocks = list(map(lambda stock: \
            fillInHistory(
                trimToRegion(stock, start, end), 
            start, end), 
        rawStocks))



# merge two factors, trim each factor into a time region
# and fill up the missing values
allfactors = factors1 + factors2
factors = list(map( lambda factor : \
            fillInHistory(
                trimToRegion(factor, start, end), 
            start, end),
            allfactors
            ))
            
# test our code
print("the first 5 records of stock 0:\n", stocks[0][:5], "\n")
print("the last 5 records of stock 0:\n", stocks[0][-5:], "\n")
print("the first 5 records of factor 0:\n", factors[0][:5], "\n")
print("the first 5 records of factor 0:\n", factors[0][-5:], "\n")

```

    the first 5 records of stock 0:
     [(datetime.datetime(2009, 1, 23, 0, 0), 16.254108), (datetime.datetime(2009, 1, 26, 0, 0), 16.470275), (datetime.datetime(2009, 1, 27, 0, 0), 16.703071), (datetime.datetime(2009, 1, 28, 0, 0), 17.975132), (datetime.datetime(2009, 1, 29, 0, 0), 16.478589)] 
    
    the last 5 records of stock 0:
     [(datetime.datetime(2014, 1, 16, 0, 0), 35.571935), (datetime.datetime(2014, 1, 17, 0, 0), 35.552912), (datetime.datetime(2014, 1, 20, 0, 0), 35.552912), (datetime.datetime(2014, 1, 21, 0, 0), 35.971404), (datetime.datetime(2014, 1, 22, 0, 0), 36.019202)] 
    
    the first 5 records of factor 0:
     [(datetime.datetime(2009, 1, 23, 0, 0), 46.47), (datetime.datetime(2009, 1, 26, 0, 0), 45.73), (datetime.datetime(2009, 1, 27, 0, 0), 41.58), (datetime.datetime(2009, 1, 28, 0, 0), 42.16), (datetime.datetime(2009, 1, 29, 0, 0), 41.44)] 
    
    the first 5 records of factor 0:
     [(datetime.datetime(2014, 1, 16, 0, 0), 93.96), (datetime.datetime(2014, 1, 17, 0, 0), 94.37), (datetime.datetime(2014, 1, 20, 0, 0), 93.93), (datetime.datetime(2014, 1, 21, 0, 0), 94.99), (datetime.datetime(2014, 1, 22, 0, 0), 96.73)] 
    


<div class="alert alert-warning">

COMMENT :
<li>These tests only enable us to check that the data (stocks and factors) have truly been trimmed in the goal time region, <b>but</b>, we don't check that missing values have been filled up or not.</li>
</div>

Recall that Value at Risk (VaR) deals with **losses over a particular time horizon**. We are not concerned with the absolute prices of instruments, but how those prices **change over** a given period of time. In our project, we will set that length to two weeks: we use the sliding window method to transform time series of prices into an overlapping sequence of price change over two-week intervals.

The figure below illustrates this process. The returns of market factors after each two-week interval is calculated in the very same way.




```python
def buildWindow(seq, k=2):
    "Returns a sliding window (of width k) over data from iterable data structures"
    "   s -> (s0,s1,...s[k-1]), (s1,s2,...,sk), ...                   "
    it = iter(seq)
    result = tuple(islice(it, k))
    if len(result) == k:
        yield result  
    for elem in it:
        result = result[1:] + (elem,)
        yield result
```

#### Question 4.6
<div class="alert alert-info">
Compute the returns of the stocks after each two-week time window.
</div>


```python
def calculateReturn(window):
    # return the change of value after two weeks
    return (window[-1][1] - window[0][1])

def twoWeekReturns(history):
    # we use 10 instead of 14 to define the window
    # because financial data does not include weekends
    return [calculateReturn (entry) for entry in buildWindow(history, 11)]
    #we need to take a window of size 11 in order to compute the difference between the next value after the 2-weeks interval and the first day !
stocksReturns = list(map(twoWeekReturns, stocks))
factorsReturns = list(map(twoWeekReturns, factors))

# test our functions
print("the first 5 returns of stock 0:", stocksReturns[0][:5])
print("the last 5 returns of stock 0:", stocksReturns[0][-5:])
```

    the first 5 returns of stock 0: [0.9394960000000019, 0.4822190000000006, -0.6485020000000006, -1.3801449999999988, -0.08314100000000124]
    the last 5 returns of stock 0: [-1.008185999999995, -1.264989, -0.6562720000000013, -0.34240400000000193, 0.3141109999999969]


Alright! Now we have data that is properly aligned to start the training process: stocks' returns and factors' returns, per time windows of two weeks. Next, we will apply the MCS method.

## 5.5. Summary guidelines to apply the MCS method on the data we prepared
Next, we overview the steps that you have to follow to build a model of your data, and then use Monte Carlo simulations to produce output distributions:

- **Step 1**: Defining the relationship between the market factors and the instrument's returns. This relationship takes the form of a model fitted to historical data.
- **Step 2**: Defining the distributions for the market conditions (particularly, the returns of factors) that are straightforward to sample from. These distributions are fitted to historical data. 
- **Step 3**: Generate the data for each trial of a Monte Carlo run: this amount to generating the random values for market conditions along with these distributions.
- **Step 4**: For each trial, from the above values of market conditions, and using the relationship built in step 1, we calculate the return for each instrument and the total return. We use the returns to define an empirical distribution over losses. This means that, if we run 100 trials and want to estimate the 5% VaR, we would choose it as the loss from the trial with the fifth greatest loss.
- **Step 5**: Evaluating the result

## 5.6. Applying MCS

### Step 1: Defining relationship between market factors and instrument's returns

In our simulation, we will use a simple linear model. By our definition of return, a factor return is a **change** in the value of a market factor **over a particular time period**, e.g. if the value of the S&P 500 moves from 2000 to 2100 over a time interval, its return would be 100.

A vector that contains the return of 4 market factors is called a *market factor vector*. Generally, instead of using this vector as features, we derive a set of features from simple transformation of it. In particular, a vector of 4 values is transformed into a vector of length $m$ by function $F$. In the simplest case $F(v) = v$.

Denote $v_t$ the market factor vector, and $f_t$ the transformed features of $v_t$ at time $t$.

$f_{tj}$ is the value of feature $j$ in $f_t$.

Denote $r_{it}$ the return of instrument $i$ at time $t$ and $c_i$ the [intercept term](http://blog.minitab.com/blog/adventures-in-statistics/regression-analysis-how-to-interpret-the-constant-y-intercept) of instrument $i$.

We will use a simple linear function to calculate $r_{it}$ from $f_t$:

$$
r_{it} = c_i + \sum_{j=1}^{m}{w_{ij}*f_{tj}}
$$

where $w_{ij}$ is the weight of feature $j$ for instrument $i$.

All that above means that given a market factor vector, we have to apply featurization and then use the result as a surrogate for calculating the return of the instruments, using the above linear function.

There are two questions that we should consider: **how we apply featurization to a factor vector?** and **how to pick values for $w_{ij}$?**

**How we apply featurization to a factor vector?**
In fact, the instruments' returns may be non-linear functions of the factor returns. So, we should not use factor returns as features in the above linear function. Instead, we transform them into a set of features with different size. In this Notebook, we can include some additional features in our model that we derive from non-linear transformations of the factor returns. We will try adding two more features for each factor return: its square and its square root values. So, we can still assume that our model is a linear model in the sense that the response variable is a linear function of the new features. *Note that the particular feature transformation described here is meant to be an illustrative example of some of the options that are available: it shouldn't be considered as the state of the art in predictive financial modeling!!*.

**How to pick values for $w_{ij}$?**

For all the market factor vectors in our historical data, we transform them to feature vectors. Now, we have feature vectors in many two-week intervals and the corresponding instrument's returns in these intervals. We can use Ordinary Least Square (OLS) regression model to estimate the weights for each instrument such that our linear function can fit to the data. The parameters for OLS function are:

- `x`: The collection of columns where **each column** is the value of **a feature** in many two-week interval
- `y`: The return of an instrument in the corresponding time interval of x.

The figure below shows the basic idea of the process to build a statistical model for predicting the returns of stock X.




### Question 5
#### Question 5.1

<div class="alert alert-info">
Currently, our data is in form of:  

$$
factorsReturns=
\begin{bmatrix}
 r_{00} & r_{01} & r_{02} & ... & r_{0k} \\
 r_{10} & r_{11} & r_{12} & ... & r_{1k} \\
 ... & ... & ... & ... & ... \\
 r_{n0} & r_{n1} & r_{n2} & ... & r_{nk}\\
\end{bmatrix}
$$

<ul></ul>

$$
stocksReturns=
\begin{bmatrix}
 s_{00} & s_{01} & s_{02} & ... & s_{0k} \\
 s_{10} & s_{11} & s_{12} & ... & s_{1k} \\
 ... & ... & ... & ... & ... \\
 s_{n0} & s_{n1} & s_{n2} & ... & s_{nk}\\
\end{bmatrix}
$$

<ul></ul>

Where, $r_{ij}$ is the return of factor $i^{th}$ in time window $j^{th}$, $k$ is the number of time windows, and $n$ is the number of factors. A similar definition goes for $s_{ij}$.

<ul></ul>

In order to use OLS, the parameter must be in form of:

<ul></ul>

$$
x=factorsReturns^T =
\begin{bmatrix}
 r_{00} & r_{10} & ... & r_{n0} \\
 r_{01} & r_{11} & ... & r_{n1} \\
 r_{02} & r_{12} & ... & r_{n2}\\
 ... & ... & ... & ... \\
 r_{0k} & r_{1k} & ... & r_{nk}\\
\end{bmatrix}
$$

<ul></ul>

Whereas, $y$ can be any row in `stocksReturns`.

<ul></ul>

So, we need a function to transpose a matrix. Write a function named `transpose` to do just that.
</div>


```python
def transpose(matrix):
    tmatrix=[[matrix[j][i] for j in range(len(matrix))] for i in range (len(matrix[0]))]
    return (tmatrix)
    
# test function
assert (transpose([[1,2,3], [4,5,6], [7,8,9]]) == [[1, 4, 7], [2, 5, 8], [3, 6, 9]]), "Function transpose runs incorrectly"
```

#### Question 5.2
<div class="alert alert-info">
Write a function named `featurize` that takes a list factor's returns $[x_1, x_2,...,x_k]$ and transform it into a new list of features $[u_1,u_2,..,u_k, v_1, v_2,..,v_k, x_1,x_2,...,x_k]$.

<ul></ul>

Where,  


$u_i$ = $\left\{
	\begin{array}{ll}
		x_i^2 & \mbox{if } x_i \geq 0 \\
		-x_i^2 & \mbox{if } x_i < 0
	\end{array}
\right.
$

<ul></ul>

and  

$v_i$ = $\left\{
	\begin{array}{ll}
		\sqrt{x_i} & \mbox{if } x_i \geq 0 \\
		-\sqrt{x_i} & \mbox{if } x_i < 0
	\end{array}
\right.
$  

</div>


```python
def featurize(factorReturns):
    squaredReturns = [x*x*np.sign(x) for x in factorReturns]
    squareRootedReturns = [np.sqrt(np.sign(x)*x)*np.sign(x) for x in factorReturns]
    # concat new features
    return (squaredReturns + squareRootedReturns + factorReturns)#concatenate the new features and the "old" ones

# test our function
assert (featurize([4, -9, 25]) == [16, -81, 625, 2, -3, 5, 4, -9, 25]), "Function runs incorrectly"
```

#### Question 5.3
<div class="alert alert-info">
Using OLS, estimate the weights for each feature on each stock. What is the shape of `weights` (size of each dimension)?  

Explain it.
</div>


```python

def estimateParams(y, x):
    return sm.OLS(y, x).fit().params

# transpose factorsReturns
factorMat = transpose(factorsReturns)

# featurize each row of factorMat
factorFeatures = list(map(featurize,factorMat))

# OLS require parameter is a numpy array
factor_columns = np.array(factorFeatures)

#add a constant - the intercept term for each instrument i.
factor_columns = sm.add_constant(factor_columns, prepend=True)

# estimate weights
weights = [estimateParams(stockReturns, factor_columns) for stockReturns in stocksReturns]

print("weights:", weights)
print("Weights shape: ", np.shape(weights))
```

    weights: [array([ 3.60997004e-02, -2.61016467e-04, -7.42952854e+00,  1.62632031e-04,
           -3.35030984e-05,  9.32244522e-02, -1.08966171e+00,  1.44753704e-02,
           -4.98229529e-02, -3.90863252e-02,  4.35073842e+00,  3.53559150e-03,
            9.17397141e-03]), array([-1.17274963e-01,  4.35436886e-04, -4.38450415e+00,  2.17498928e-04,
           -3.81957995e-05,  1.38761779e-01, -5.16124861e-02,  8.26230905e-02,
           -1.71129497e-02, -6.28930535e-02,  2.73672265e+00, -2.97390673e-02,
            2.65115741e-02]), array([-1.66277278e-02,  2.82808726e-03, -1.91981642e+00,  6.18216700e-05,
           -1.84178884e-05,  5.24269096e-02, -2.38013145e-01,  2.54504075e-03,
           -1.24624189e-02, -5.85955453e-02,  1.06686384e+00, -1.76635800e-03,
            4.20340529e-03]), array([-1.59872476e+00, -6.71360038e-02, -2.53188310e+01,  3.08600858e-04,
           -5.15843001e-05, -3.48439716e+00, -2.75927084e+00, -4.61473966e-01,
            3.97052500e-01,  1.98535813e+00,  1.17067547e+01,  4.54737827e-02,
            1.19745954e-02]), array([-1.32808692e-01,  6.31856867e-03,  4.35060157e+00, -7.96590338e-05,
            4.01712839e-05,  2.72619731e-01,  6.11063225e-01,  9.44206407e-02,
           -1.53595273e-02, -1.56168247e-01, -1.52037487e+00, -2.45979012e-02,
            9.81419011e-03]), array([-2.61865027e-01, -2.32491203e-02,  1.24232375e+01,  1.00912081e-03,
           -2.18378056e-04,  1.58457171e-02,  8.79357183e-01,  5.47578341e-01,
           -4.95137531e-01,  3.80329801e-01, -7.02366203e+00, -1.83529771e-01,
            8.82865354e-02]), array([ 5.13669450e-02,  2.37196753e-03,  1.09721077e+00, -1.45692552e-04,
            1.99410801e-05,  1.57629141e-01, -2.66626994e-01, -2.84971950e-02,
            1.83967390e-02, -8.95190105e-02, -5.18293413e-01,  1.77294364e-02,
           -1.55859292e-03]), array([ 1.76334093e-03,  3.94672760e-03,  1.21289676e+00,  9.83574840e-06,
           -1.91644462e-05,  5.11308872e-02, -3.48946388e-01,  2.01312714e-02,
           -1.62697626e-03, -5.62331271e-02,  4.93612193e-01, -1.54767276e-03,
            4.39554475e-03]), array([-5.33866499e-01,  2.89234886e-02,  3.12268154e+01,  1.27405270e-03,
           -2.80563691e-04,  4.77830958e-01,  1.96226585e+00,  1.18135407e-01,
           -1.50954474e-01, -4.02860253e-01, -1.24588856e+01, -7.93524646e-02,
            6.62650558e-02]), array([ 1.44423898e-03,  9.73500419e-03,  1.39114841e+01,  2.26674205e-04,
           -2.53439147e-05,  4.75435862e-01,  2.69531543e+00, -7.25611680e-02,
            8.06642591e-02, -2.74421507e-01, -1.15196530e+01,  2.40409350e-02,
           -7.74271818e-04]), array([ 2.77129467e-02, -6.30607765e-03,  1.65517753e+00, -2.11458225e-04,
            4.33140844e-05, -2.36657301e-01,  7.06564901e-01, -7.30961259e-02,
            3.98076383e-02,  1.44845596e-01, -1.44032550e+00,  3.23112486e-02,
           -3.02924714e-03]), array([-1.89251241e-01,  8.67290103e-04,  8.59508062e+00, -4.33365130e-05,
           -2.61752136e-05,  1.53682112e-03,  2.82639690e-01,  4.32340576e-03,
           -5.43826462e-02, -9.99488880e-03, -1.73103738e+00, -6.58616209e-03,
            1.74630874e-02]), array([-7.71850083e-03,  6.66053909e-04, -2.18131146e+00,  7.77677119e-05,
           -1.48177530e-05,  6.34416203e-02, -1.41609773e-01,  1.58704540e-02,
           -2.34586601e-02, -1.75361213e-02,  1.15434317e+00, -4.78773921e-03,
            3.60910156e-03]), array([-1.19946479e-01, -6.76369582e-04,  5.04451151e+00,  2.49429092e-04,
           -5.55766883e-05, -3.59313243e-02,  5.54877167e-02,  4.91895282e-03,
           -1.30222909e-03,  1.13435717e-02, -2.34252648e+00,  2.45477912e-03,
            1.17665635e-02]), array([-3.78907997e-02,  5.29157169e-04, -5.52107085e-01,  1.08359040e-04,
           -2.45477769e-05,  1.60785704e-02, -2.56183479e-01,  3.27019194e-02,
           -2.05852835e-02, -1.54554701e-02,  7.73168281e-01, -7.11735839e-03,
            5.46670932e-03]), array([-4.65358105e-03, -1.86695376e-03, -2.15538530e+00,  2.39494809e-05,
            7.14234341e-06,  5.55913941e-03, -5.10201107e-01, -3.74834903e-03,
            1.91690304e-02,  2.57461096e-02,  1.61193550e+00, -7.34384005e-03,
            9.91673591e-04]), array([-4.69845237e-02, -4.24236934e-04,  2.55643379e+00, -1.10718777e-04,
            2.25143158e-05,  2.64248738e-02,  9.41103530e-02, -1.33752502e-02,
            1.95276069e-02, -9.15734582e-03, -6.98264341e-01,  1.05041497e-02,
           -3.85592188e-03]), array([-1.64896076e-02, -7.32384964e-04,  1.41822066e+00, -1.07211574e-05,
            3.92052526e-06, -2.88971559e-02,  2.66498471e-01, -5.09675895e-03,
            1.99480124e-02,  2.33611614e-02, -8.25986901e-01,  2.06004024e-03,
           -5.75538584e-04]), array([ 1.02440626e-02, -1.37350373e-03, -8.27342890e-01,  6.07512617e-05,
           -9.46179170e-06, -5.41445876e-02, -1.09871866e-01,  1.69171912e-02,
           -1.12370836e-02,  4.75092551e-02,  1.57878937e-01, -8.13171564e-03,
            4.51793028e-03]), array([-8.76582148e-03,  1.35237494e-04, -1.32007377e+00,  1.09885222e-04,
           -3.12382697e-05,  1.75845161e-02, -3.65593586e-01, -1.05106518e-02,
           -1.43236443e-02, -1.65198290e-02,  1.12895956e+00,  6.94418779e-03,
            6.91732909e-03]), array([-4.04113349e-02,  8.96115441e-04, -2.35181270e-01,  4.74931364e-05,
           -8.54823155e-06,  2.05482342e-02, -2.30342166e-01,  1.12648044e-02,
           -1.12836901e-02, -1.68236930e-02,  2.95588855e-01,  1.25031133e-03,
            2.09851079e-03]), array([-1.21099367e-02, -2.38047621e-04, -4.66663963e-01,  3.99784909e-05,
           -4.09692859e-06,  3.50814476e-03, -8.46875861e-02,  2.52074726e-02,
           -5.80440005e-03, -9.82291810e-04,  3.19171169e-01, -5.44424736e-03,
            9.26914552e-04]), array([-5.57273462e-02,  4.34863920e-03,  7.95763244e-01,  9.96826168e-05,
           -3.03065025e-05,  1.25330642e-01, -7.75337697e-01,  2.72072150e-02,
           -3.17344905e-02, -7.53303987e-02,  2.18401495e+00, -9.28971927e-03,
            8.84628555e-03]), array([-1.20402212e-02, -9.58323033e-04,  1.63309020e-01,  1.47110219e-04,
           -2.85348037e-05, -4.13680012e-02,  4.92354120e-02,  6.19303243e-02,
           -3.32647265e-02,  3.93248485e-03, -2.89696117e-01, -1.52626163e-02,
            8.29276312e-03]), array([ 1.72423814e-02, -1.00442926e-03,  2.91389168e+00,  5.96388711e-05,
           -2.40891233e-06, -1.93909968e-02,  6.11075989e-01,  2.99651989e-02,
            8.65080487e-03,  2.85031313e-02, -2.22283448e+00, -8.79758793e-03,
           -2.31308903e-04]), array([ 4.15028844e-02,  8.72662461e-04,  3.78604973e-01, -1.91705471e-05,
           -7.32682716e-07, -3.89891990e-02, -1.80942416e-01, -1.41138213e-02,
            1.05857156e-02,  8.98846247e-03,  4.10199817e-02,  3.60501353e-03,
            1.52738191e-03]), array([ 1.38367233e-02, -4.75670218e-04,  1.45793960e+01, -4.39201325e-04,
            1.73424045e-05,  1.62589772e-01,  1.17400925e+00, -2.23592579e-01,
            9.70491138e-03, -4.20190964e-02, -6.60755813e+00,  9.32740525e-02,
           -4.98640519e-03]), array([ 4.76605836e-01,  2.36831265e-02,  1.31979752e+01, -6.71325552e-04,
            1.92455687e-04,  1.68529539e-01,  2.26858046e+00, -9.64472155e-02,
            1.10134379e-01, -3.35779632e-01, -7.87536794e+00,  1.25643575e-01,
           -3.40539287e-02]), array([-1.22086411e-01, -2.98098666e-03, -9.09202424e+00,  3.53021807e-04,
           -6.04864935e-05, -4.74067313e-02, -3.96886454e-01,  6.43219429e-02,
           -5.24579751e-02,  6.22497855e-02,  2.75626790e+00, -9.81177554e-03,
            9.22500222e-03])]
    Weights shape:  (29, 13)


<div class="alert alert-warning">

COMMENT :
<li>For each stock, we evaluate the weights to build a model,which will predict the returns of this stock.</li>
<li>Each array of weights corresponds to one stock, and contains 13 values. Indeed, we have 4 market factors, and for each factor's return we take also the square and the square root, which leads to 4*3=12 terms. And with the intercept term we reach 13 terms.</li>
<li>When counting the number of lines in this matrix, we find 29. Where does it come from ? Actually, at question 4.3, we wanted to invest in the first 35 stocks. Then we filtered those with more than 5 years of history. So we ended up with a final total of 29 stocks (cf.output of question 4.3: "Instruments with more that 5 years of history: 29").
Therefore, the weight matrix has 29 rows.</li>
</div>

### Step 2: Defining the distributions for the market conditions
Since we cannot define the distributions for the market factors directly, we can only approximate their distribution.
The best way to do that, is plotting their value. However, these values may fluctuate quite a lot. 

Next, we show how to use the Kernel density estimation (KDE) technique to approximate such distributions. In brief, kernel density estimation is a way of smoothing out a histogram: this is achieved by assigning (or centering) a probability distribution (usually a normal distribution) to each data point, and then summing. So, a set of two-week-return samples would result in a large number of "super-imposed" normal distributions, each with a different mean. 

To estimate the probability density at a given point, KDE evaluates the PDFs of all the normal distributions at that point and takes their average. The smoothness of a kernel density plot depends on its *bandwidth*, and the standard deviation of each of the normal distributions. For a brief introduction on KDE, please refer to this [link](https://en.wikipedia.org/wiki/Kernel_density_estimation).


```python
from statsmodels.nonparametric.kernel_density import KDEMultivariate
from statsmodels.nonparametric.kde import KDEUnivariate
import matplotlib.pyplot as plt
import scipy

#we want to look at percentiles in the different factors' distributions
lows = [np.percentile(factorsReturn,5) for factorsReturn in factorsReturns]
highs = [np.percentile(factorsReturn,95) for factorsReturn in factorsReturns]

def plotDistribution(samples, title, samplesList=None, samplesTitles=None, plot=True):
    vmin = min(samples)
    vmax = max(samples)
    stddev = np.std(samples)
    
    domain = np.arange(vmin, vmax, (vmax-vmin)/100)
    
    # a simple heuristic to select bandwidth
    bandwidth = 1.06 * stddev * pow(len(samples), -.2)
    
    # estimate density
    kde = KDEUnivariate(samples)
    kde.fit(bw=bandwidth)
    density = kde.evaluate(domain)
    
    #plot 5th and 95th percentiles
    low = np.percentile(samples, 1)
    high = np.percentile(samples, 99)
    mean = sum(samples)/len(samples)
    plt.axvline(low, color = 'r')
    plt.axvline(high, color = 'r')
    plt.axvline(mean, color = 'b')
    
    # plot
    plt.plot(domain, density)
    plt.title(title)
    
    if samplesList!=None:
        for i in range(len(samplesList)):
            plt.plot(samplesList[i])
            if samplesTitles != None:
                plt.title(samplesTitles[i])
    
    if plot:
        plt.show()

plotDistribution(factorsReturns[0], "Distribution of GSPC values")
plotDistribution(factorsReturns[1], "Distribution of IXIC values")
plotDistribution(factorsReturns[2], "Distribution of returns of crude oil")
plotDistribution(factorsReturns[3], "Distribution of returns of treasury bonds")
```

<div class="alert alert-warning">

COMMENT :
<li>We can notice that the 3 plotted distributions share  pretty much the same shape : one that is almost symmetrical around a mean, with few values that go up to the maximum and a lot of values on each other side of the maximum that are similarly low.  </li>
<li>The mean is however slightly different for each sample</li>
<li>So, we can model their distribution by a gaussian (normal) distribution that takes into account the different factors' means and covariances.</li>
<li>And the lower and upper limits are obviously different from one factor to another. They might be to take into account in modeling them with other distributions.</li>
</div>

For the sake of simplicity, we can say that our smoothed versions of the returns of each factor can be represented quite well by a normal distribution. Of course, more exotic distributions, perhaps with fatter tails, could fit more closely the data, but it is outside the scope of this Notebook to proceed in this way.

Now, the simplest way to sample factors returns is to use a normal distribution for each of the factors, and sample from these distributions independently. However, this approach ignores the fact that market factors are often correlated. For example, when the price of crude oil is down, the price of treasury bonds is down too. We can check our data to verify about the correlation.

### Question 6

#### Question 6.1
<div class="alert alert-info">

Calculate the correlation between market factors and explain the result.

</div>

<div class="label label-success">HINT</div> function `np.corrcoef` might be useful.


```python
correlation = np.corrcoef(factorsReturns)
correlation

```




    array([[1.        , 0.39463374, 0.46575411, 0.45102902],
           [0.39463374, 1.        , 0.5518134 , 0.55175718],
           [0.46575411, 0.5518134 , 1.        , 0.95180887],
           [0.45102902, 0.55175718, 0.95180887, 1.        ]])



<div class="alert alert-warning">

COMMENT :
<li>First, the correlation maxtrix is symmetrical which is logical, as the correlation between factor i and factor j doesn't change with the order : $Cor(i,j) = Cor(j,i) $.</li>
<li>All the terms are positive and between 0
-1 and 1, which is normal for correlation values. The more the correlation between 2 factors is close to 1, the more they "behave" the same.</li>
<li>All diagonal values are equal to one, since $Cor(i,i) = 1$ for any factor i.</li>
<ul><b>Interpretation</b> :
        <li>We would like to recall what our factors represent: the 1st factor is the GSPC value, the 2nd is the IXIC value, the 3rd is the return of crude oil, the 4th is the return of treasury bonds.</li>
        <li>Correlation between factor 1 and 2 is the lowest (0.38788549) of all correlations. Factor 1 correlates the best with factor 4 , still, the correlation is still below 0.5 (0.45841194). So, <b>the GSPC value doesn't have a lot to do with the IXIC value.</b> </li>
        <li>Factor 2 correlates the best with factor 3 , though is also correlates pretty well with factor 4 with a very close correlation value (0.58306416, compared to 0.58447669). So, <b>the return of crude oil depends almost equally on the GSPC value and the IXIC value.</b> </li>
        <li>Correlation between factor 3 and 4 is the greatest (0.95227596) of all correlation values. We can say that they are also similar, as this correlation is extremely close to 1 (it is equal to one if it's rounded to the closest hundredth). So, <b>the return of crude oil depends almost totally on the return of treasury bonds, and vice-versa.</b> </li>
    
</ul>
</div>

The multivariate normal distribution can help here by taking the correlation information between the factors into account. Each sample from a multivariate normal distribution can be thought of as a vector. Given values for all of the dimensions but one, the distribution of values along that dimension is normal. But, in their joint distribution, the variables are not independent.

For this use case, we can write:

$$
\left(\begin{array}{c}f_{1}\\f_{2}\\f_{3}\\f_{4} \end{array}\right)
\sim N 
\left[
  \left(
    \begin{array}{c}
      \mu_1\\ \mu_2 \\ \mu_3 \\ \mu_4 
    \end{array}
  \right), 
  \left(
    \begin{array}{cccc}
      \sigma^2_1 & \rho_{12} \sigma_1\sigma_2 & \rho_{13} \sigma_1\sigma_3 & \rho_{14} \sigma_1\sigma_4 \\ 
      \rho_{12}\sigma_2\sigma_1 & \sigma^2_2 & \rho_{23} \sigma_2\sigma_3 & \rho_{24} \sigma_2\sigma_4\\
      \rho_{13} \sigma_3\sigma_1 & \rho_{23} \sigma_3\sigma_2 & \sigma^2_3 & \rho_{34} \sigma_3\sigma_4 \\ 
      \rho_{14} \sigma_4\sigma_1 & \rho_{24} \sigma_4\sigma_2 & \rho_{34} \sigma_3\sigma_4 & \sigma_4^2 \\ 
    \end{array}
  \right)
\right]
$$

Or,

$$
f_t \sim N(\mu, \sum)
$$

Where $f_1$, $f_2$, $f_3$ and $f_4$ are the market factors, $\sigma_i$ is the standard deviation of factor $i$, $\mu$ is a vector of the empirical means of the returns of the factors and $\sum$ is the empirical covariance matrix of the returns of the factors.

The multivariate normal is parameterized with a mean along each dimension and a matrix describing the covariance between each pair of dimensions. When the covariance matrix is diagonal, the multivariate normal reduces to sampling along each dimension independently, but placing non-zero values in the off-diagonals helps capture the relationships between variables. Whenever having the mean of this multivariate normal distribution and its covariance matrix, we can generate the sample values for market factors.

Next, we will calculate the mean and the covariance matrix of this multivariate normal distribution from the historical data.


#### Question 6.2
<div class="alert alert-info">

Calculate the covariance matrix $\sum$ and the means $\mu$ of factors' returns then generate a random vector of factors return that follows a multivariate normal distribution $\sim N(\mu, \sum)$

</div>

<div class="label label-success">HINT</div>
Function `np.cov` can help calculating covariance matrix. Function `np.random.multivariate_normal(<mean>, <cov>)` is often used for generating samples.


```python
factorCov = np.cov(factorsReturns)
factorMeans = [sum(x)/len(x) for x in factorsReturns]
sample = np.random.multivariate_normal(factorMeans, factorCov)
print("\nThe Covariance Matrix is: \n", factorCov)
print("\nThe mean vector of factors is: \n", factorMeans)
print("\nRandom vector of factors return that follows a multivariate normal distribution: \n", sample)
```

    
    The Covariance Matrix is: 
     [[2.25254567e+01 3.02486401e-01 8.37992320e+01 1.86354063e+02]
     [3.02486401e-01 2.60825277e-02 3.37841984e+00 7.75747540e+00]
     [8.37992320e+01 3.37841984e+00 1.43712013e+03 3.14118747e+03]
     [1.86354063e+02 7.75747540e+00 3.14118747e+03 7.57870747e+03]]
    
    The mean vector of factors is: 
     [0.3983848531684707, 0.0021514683153013984, 7.726074077279752, 20.740648602782073]
    
    Random vector of factors return that follows a multivariate normal distribution: 
     [-3.30231152e+00 -5.82397705e-02 -2.47827395e-03 -1.51754548e+01]


<div class="alert alert-warning">

COMMENT :
<li>The Covariance Matrix has a shape of 4*4 as there are 4 factors. It is symmetrical as $cov(i,j) = cov(j,i)$ for factor i and factor j</li>
<li>The mean vector indicates that :
<ul>
    <li>Mean value of GSPC value is 0.3983848531684707.</li>
    <li>Mean value of IXIC value is  0.0021514683153013984.</li>
    <li>Mean value of the return of crude oil is 7.726074077279752.</li>
    <li>Mean value of the return of treasury bonds is 20.740648602782073.</li>
    <li>All those mean values are coherent with the distributions that were plotted in question 5.3 (step 2).</li>
</ul>
</li>
</div>

### Step 3&4: Generating samples, running simulation and calculating the VaR

We define some functions that helps us calculating VaR 5%. You will see that the functions below are pretty complicated! This is why we provide a solution for you: however, study them well!!

The basic idea of calculating VaR 5% is that we need to find a value such that only 5% of the losses are bigger than it. That means the 5th percentile of the losses should be VaR 5%.

VaR can sometimes be problematic though, since it does give any information on the extent of the losses which can exceed the VaR estimate. CVar is an extension of VaR that is introduced to deal with this problem. Indeed, CVaR measures the expected value of the loss in those cases where VaR estimate has been exceeded.


```python
def fivePercentVaR(trials):
    numTrials = trials.count()
    topLosses = trials.takeOrdered(max(round(numTrials/20.0), 1))
    return topLosses[-1]

# an extension of VaR
def fivePercentCVaR(trials):
    numTrials = trials.count()
    topLosses = trials.takeOrdered(max(round(numTrials/20.0), 1))
    return sum(topLosses)/len(topLosses)

def bootstrappedConfidenceInterval(
      trials, computeStatisticFunction,
      numResamples, pValue):
    stats = []
    for i in range(0, numResamples):
        resample = trials.sample(True, 1.0)
        stats.append(computeStatisticFunction(resample))
    sorted(stats)
    lowerIndex = int(numResamples * pValue / 2 - 1)
    upperIndex = int(np.ceil(numResamples * (1 - pValue / 2)))
    return (stats[lowerIndex], stats[upperIndex])
```

Next, we will run the Monte Carlo simulation 10,000 times, in parallel using Spark. Since your cluster has 12 cores (two Spark worker nodes, each with 6 cores), we can set `parallelism = 12` to dispatch simulation on these cores, across the two machines (remember, those are not really "physical machines", they are Docker containers running in our infrastructure).

### Question 7
<div class="alert alert-info">
Complete the code below to define the simulation process and calculate VaR 5%.
</div>


```python
def simulateTrialReturns(numTrials, factorMeans, factorCov, weights):
    trialReturns = []
    for i in range(0, numTrials):
        # generate sample of factors' returns
        trialFactorReturns = np.random.multivariate_normal(factorMeans,factorCov) 
        
        # featurize the factors' returns
        trialFeatures = featurize(trialFactorReturns.tolist())
        
        # insert weight for intercept term
        trialFeatures.insert(0,1)
        
        trialTotalReturn = 0
        
        # calculate the return of each instrument
        # then calulate the total of return for this trial features
        trialTotalReturn = sum(np.dot(weights, trialFeatures).tolist())
        
        trialReturns.append(trialTotalReturn)
    
    return trialReturns

        
parallelism = 12
numTrials = 10000
trial_indexes = list(range(0, parallelism))
seedRDD = sc.parallelize(trial_indexes, parallelism)
bFactorWeights = sc.broadcast(weights)

trials = seedRDD.flatMap(lambda idx: \
                simulateTrialReturns(
                    max(int(numTrials/parallelism), 1), 
                    factorMeans, factorCov,
                    bFactorWeights.value
                ))
trials.cache()

valueAtRisk = fivePercentVaR(trials)
conditionalValueAtRisk = fivePercentCVaR(trials)

print ( "Value at Risk(VaR) 5%:", valueAtRisk)
print ( "Conditional Value at Risk(CVaR) 5%:", conditionalValueAtRisk )

```

    Value at Risk(VaR) 5%: -29.50361213928892
    Conditional Value at Risk(CVaR) 5%: -37.76034975795191





<div class="alert alert-warning">

COMMENT :
<li>So, there is a 0.05 probability that our portfolio of stock investments will fall in value by more than 29.50 dollars over a two weeks period. </li>
<li>The Conditional Value at Risk tells us that this loss is expected to go up to 37.76 dollars when this expected VaR estimate has been exceeded.</li>
<ul> <b>Interpretation</b>:
    <li>For now, we can't conclude about the VaR obtained. Indeed, we need to compare the values obtained here with the real values. That's what comes next.</li>
</ul>    
</div>

The value of VaR depends on how many invested stocks and the chosen distribution of random variables. Assume that we get VaR 5% = -2.66,  that means that there is a 0.05 probability that the portfolio will fall in value by more than \$2.66 over a two weeks' period if there is no trading. In other words, the loses are less than \$2.66 over two weeks' period with 95% confidence level. When a loss over two weeks is more than \$2.66, we call it <b>failure</b> (or <b>exception</b>). Informally, because of 5% probability, we expect that there are only $0.05*W$ failures out of total $W$ windows.

### Step 5: Evaluating the results using backtesting method
In general, the error in a Monte Carlo simulation should be proportional to 1/sqrt(n), where n is the number of trials. This means, for example, that quadrupling the number of trials should approximately cut the error in half. A good way to check the quality of a result is backtesting on historical data. Backtesting is a statistical procedure where actual losses are compared to the estimated VaR. For instance, if the confidence level used to calculate VaR is 95% (or VaR 5%), we expect only 5 failures over 100 two-week time windows.

The most common test of a VaR model is counting the number of VaR failures, i.e., in how many windows, the losses exceed VaR estimate. If the number of exceptions is less than selected confidence level would indicate, the VaR model overestimates the risk. On the contrary, if there are too many exceptions, the risk is underestimated. However, it's very hard to observe the amount of failures suggested by the confidence level exactly. Therefore, people try to study whether the number of failures is reasonable or not, or will the model be accepted or rejected.

One common test is Kupiec's proportion-of-failures (POF) test. This test considers how the portfolio performed at many historical time intervals and counts the number of times that the losses exceeded the VaR. The null hypothesis is that the VaR is reasonable, and a sufficiently extreme test statistic means that the VaR estimate does not accurately describe the data. The test statistic is computed as:

$$
-2ln\Bigg(\frac{(1-p)^{T-x}p^x}{(1-\frac{x}{T})^{T-x}(\frac{x}{T})^x}\Bigg)
$$

where:

$p$ is the quantile-of-loss of the VaR calculation (e.g., in VaR 5%, p=0.05),

$x$ (the number of failures) is the number of historical intervals over which the losses exceeded the VaR 

$T$ is  the total number of historical intervals considered

Or we can expand out the log for better numerical stability:

$$
\begin{equation}
-2\Big((T-x)ln(1-p)+x*ln(p)-(T-x)ln(1-\frac{x}{T})-x*ln(\frac{x}{T})\Big)
\end{equation}
$$

If we assume the null hypothesis that the VaR is reasonable, then this test statistic is drawn from a chi-squared distribution with a single degree of freedom. By using Chi-squared distribution, we can find the `p-value` accompanying our test statistic value.  If `p-value` exceeds the critical value of the Chi-squared distribution, we do have sufficient evidence to reject the null hypothesis that the model is reasonable. Or we can say, in that case, the model is considered as inaccurate.

For example, assume that we calculate VaR 5% (the confidence level of the VaR model is 95%) and get value VaR = 2.26. We also observed 50 exceptions over 500 time windows. Using the formula above, the test statistic `p-value` is calculated and equal to `8.08`. Compared to `3.84`, the critical value of Chi-squared distribution with one degree of freedom at probability 5%, the test statistic is larger. So, the model is rejected. The critical values of Chi-squared can be found by following [this link](https://people.richland.edu/james/lecture/m170/tbl-chi.html).
However, in this Notebook, it's not a good idea to find the corresponding critical value by looking in a "messy" table, especially when we need to change the confidence level. Instead, from `p-value`, we will calculate the probability of the test statistic in Chi-square thanks to some functions in package `scipy`. If the calculated probability is smaller than the quantile of loss (e.g, 0.05), the model is rejected and vice versa.


### Question 8

#### Question 8.1
<div class="alert alert-info">

Write a function to calculate the number of failures, that is when the losses (in the original data) exceed the VaR.

</div>

<div class="label label-success">HINT</div>
<ul>
  <li>First, we need to calculate the total loss in each 2-week time interval</li>
  <li>If the total loss of a time interval exceeds VaR, then we say that our VaR fails to estimate the risk in that time interval</li>
  <li>Return the number of failures</li>
</ul>  

<div class="label label-danger">NOTE</div> The loss is often having negative value, so, be careful when compare it to VaR.


```python
from scipy import stats
import math

def countFailures(stocksReturns, valueAtRisk):
    failures,loss= 0, 0
    # iterate over time intervals
    for i in range(0,len(stocksReturns[0])):
        # calculate the losses in each time interval
        loss = -sum(map(lambda stockReturns: stockReturns[i], stocksReturns))
        
        # if the loss exceeds VaR
        if loss > -valueAtRisk:
            failures += 1
    return failures
```

#### Question 8.2
<div class="alert alert-info">

Write a function named `kupiecTestStatistic` to calculate the test statistic which was described in the above equation.

</div>


```python
import numpy as np
def kupiecTestStatistic(total, failures, confidenceLevel):
    failureRatio = failures/total
    logNumer = (total - failures) * np.log(1 - confidenceLevel) + failures * np.log(confidenceLevel)
    logDenom = (total - failures) * np.log(1 - failureRatio) + failures * np.log(failureRatio)
    return -2 * (logNumer - logDenom)
    
# test the function
assert (round(kupiecTestStatistic(250, 36, 0.1), 2) == 4.80), "function kupiecTestStatistic runs incorrectly"
```

Now we can find the p-value accompanying our test statistic value.


```python
def kupiecTestPValue(stocksReturns, valueAtRisk, confidenceLevel):
    failures = countFailures(stocksReturns, valueAtRisk)
    N = len(stocksReturns)
    print("num failures:", failures)
    total = len(stocksReturns[0])
    print("Number of stocks: ", total)
    testStatistic = kupiecTestStatistic(total, failures, confidenceLevel)
    #return 1 - stats.chi2.cdf(testStatistic, 1.0)
    return (stats.distributions.chi2.sf(testStatistic, 1.0), testStatistic)

varConfidenceInterval = bootstrappedConfidenceInterval(trials, fivePercentVaR, 100, 0.05)
cvarConfidenceInterval = bootstrappedConfidenceInterval(trials, fivePercentCVaR, 100, .05)
stat_found = kupiecTestPValue(stocksReturns, valueAtRisk, 0.05)
print("VaR confidence interval: " , varConfidenceInterval)
print("CVaR confidence interval: " , cvarConfidenceInterval)
print("Statistical value from Kupiec test: " , stat_found[1])
print("Kupiec test p-value: " , stat_found[0])
```

    num failures: 131
    Number of stocks:  1294
    VaR confidence interval:  (-29.20324949869589, -29.50361213928892)
    CVaR confidence interval:  (-37.82929114395939, -37.417263261846166)
    Statistical value from Kupiec test:  55.86610639623416
    Kupiec test p-value:  7.757855674512068e-14



```python
#before commenting on the results above, 
#we want to understand how we can interpret statistical values and p-value derived from Kupiec test
stat_list = []
kupiec_list = [] 
for i in range(1,1000):
    stat_result = kupiecTestStatistic(1000,i,0.05)
    stat_list.append(stat_result)
    kupiec_list.append(stats.distributions.chi2.sf(stat_result, 1.0))
f, axarr = plt.subplots(2, sharex=True)
axarr[0].plot(range(1,1000), stat_list)
axarr[0].axvline(50, color = 'r') #50 is the perfect number of failures that fits the model (5% of errors)
axarr[0].set_title("Kupiec Statistical value (from Kupiec test)")
axarr[0].set_ylabel("Kupiec Stat values")
axarr[0].set_xlabel("Number of failures out of 1000")

axarr[1].plot(range(1,1000), kupiec_list)
axarr[1].axvline(50, color = 'r') #5 is the perfect number of failures that fits the model (5% of errors)
axarr[1].set_ylabel("p-value (Chi-distribution)")
axarr[1].set_xlabel("Number of failures out of 1000")
plt.show()
```

<div class="alert alert-warning">

COMMENT :
<li>So, it seems that an optimal model has a number of failures that corresponds exactly to the model, i.e., to its predicted failure rate (here, it is 0.05).</li>

<ul> <b>According to the graphs above, it seems that :</b>
    <li>An optimal model has a Kupiec statistical value as clos as 0 as possible. Bad models have statistical values very far from 0 (more than 100 here).</li>
    <li>An optimal model has a p-value (derived from the chi-distribution value found from the Kupiec test) of 1.0 and bad models have a p-value close to 0</li>
    <li>Therefore, we need to find distributions that estimates our data such that <b>the statistical value from Kupiec test is as close as 0 as possible</b> and <b>such that the p-value is as close as 1.0 as possible.</b></li>
    
</ul>    
</div>

#### Question 8.3
<div class="alert alert-info">

Discuss the results you have obtained

</div>

<div class="alert alert-warning">

ANSWER
<ul> <u>About the intervals</u>:
    <li>The VaR estimate (approximately -29.50) that we found in question 7 is inside the interval found here, which is reassuring because the confidence interval is an interval that has a probability of including the VaR estimate</li>
    <li>As for the CVaR estimate (-37.76) that we found in question 7, it is also in the confidence interval found here.</li>
    
</ul>
<ul> <u>About the statistical values found</u>:
    <li>The statistical value found directly from the Kupiec test is <b>above 50</b>, which is much more than 0 ! </li>
    <li>The p-value found is 7.8e-14 approximately, which is much below 0.05 and much below 1.0 !</li>
    <li>Moreover, the number of failures is 131 out of 1294 stocks, so we have a rate of more than 10%, which is higher than 5%. So, the distribution of probability is not appropriate.</li>
    <li>Therefore, <b>the null hypothesis that the VaR is reasonable here is an very bad estimate</b>. We should maybe try other distributions than the normal distribution.</li>
</ul>

</div>

### Question 9
<div class="alert alert-info">
Assume that we invest in more than 100 stocks. Use the same market factors as for the previous questions to estimate VaR by running MCS, then validate your result.  

What is the main observation you have, once you answer this question? When you plan to invest in more instruments, how is your ability to predict the risk going to be affected?
</div>



```python
#Let's get the first 150 stocks
#then, filter the stock with less than 5 years of history
stock_files = [join(stock_folder, f) for f in listdir(stock_folder) if isfile(join(stock_folder, f))]
stock_files = stock_files[:150]
rawStocks1 = [process_stock_file(f) for f in stock_files]
number_of_years = 5
rawStocks1 = list(filter(lambda instrument: len(instrument)>number_of_years*260, rawStocks1))
print("\nNumber of instruments with more that 5 years of history:", len(rawStocks1))
```

    
    Number of instruments with more that 5 years of history: 115



```python
#Now that we have selected and filtered more than 100 stocks
#Let's evaluate stocks returns in a time intervall of two weeks
stocks1 = list(map(lambda stock: \
            fillInHistory(
                trimToRegion(stock, start, end), 
            start, end), 
        rawStocks1))


stocksReturns1 = list(map(twoWeekReturns, stocks1))

```


```python
#Let's estimate the weights
weights1 = [estimateParams(stockReturns, factor_columns) for stockReturns in stocksReturns1]


print(weights1)
print("Shape of the weights matrix: ", len(weights1), len(weights1[0]))
```

    [array([ 3.60997004e-02, -2.61016467e-04, -7.42952854e+00,  1.62632031e-04,
           -3.35030984e-05,  9.32244522e-02, -1.08966171e+00,  1.44753704e-02,
           -4.98229529e-02, -3.90863252e-02,  4.35073842e+00,  3.53559150e-03,
            9.17397141e-03]), array([-1.17274963e-01,  4.35436886e-04, -4.38450415e+00,  2.17498928e-04,
           -3.81957995e-05,  1.38761779e-01, -5.16124861e-02,  8.26230905e-02,
           -1.71129497e-02, -6.28930535e-02,  2.73672265e+00, -2.97390673e-02,
            2.65115741e-02]), array([-1.66277278e-02,  2.82808726e-03, -1.91981642e+00,  6.18216700e-05,
           -1.84178884e-05,  5.24269096e-02, -2.38013145e-01,  2.54504075e-03,
           -1.24624189e-02, -5.85955453e-02,  1.06686384e+00, -1.76635800e-03,
            4.20340529e-03]), array([-1.59872476e+00, -6.71360038e-02, -2.53188310e+01,  3.08600858e-04,
           -5.15843001e-05, -3.48439716e+00, -2.75927084e+00, -4.61473966e-01,
            3.97052500e-01,  1.98535813e+00,  1.17067547e+01,  4.54737827e-02,
            1.19745954e-02]), array([-1.32808692e-01,  6.31856867e-03,  4.35060157e+00, -7.96590338e-05,
            4.01712839e-05,  2.72619731e-01,  6.11063225e-01,  9.44206407e-02,
           -1.53595273e-02, -1.56168247e-01, -1.52037487e+00, -2.45979012e-02,
            9.81419011e-03]), array([-2.61865027e-01, -2.32491203e-02,  1.24232375e+01,  1.00912081e-03,
           -2.18378056e-04,  1.58457171e-02,  8.79357183e-01,  5.47578341e-01,
           -4.95137531e-01,  3.80329801e-01, -7.02366203e+00, -1.83529771e-01,
            8.82865354e-02]), array([ 5.13669450e-02,  2.37196753e-03,  1.09721077e+00, -1.45692552e-04,
            1.99410801e-05,  1.57629141e-01, -2.66626994e-01, -2.84971950e-02,
            1.83967390e-02, -8.95190105e-02, -5.18293413e-01,  1.77294364e-02,
           -1.55859292e-03]), array([ 1.76334093e-03,  3.94672760e-03,  1.21289676e+00,  9.83574840e-06,
           -1.91644462e-05,  5.11308872e-02, -3.48946388e-01,  2.01312714e-02,
           -1.62697626e-03, -5.62331271e-02,  4.93612193e-01, -1.54767276e-03,
            4.39554475e-03]), array([-5.33866499e-01,  2.89234886e-02,  3.12268154e+01,  1.27405270e-03,
           -2.80563691e-04,  4.77830958e-01,  1.96226585e+00,  1.18135407e-01,
           -1.50954474e-01, -4.02860253e-01, -1.24588856e+01, -7.93524646e-02,
            6.62650558e-02]), array([ 1.44423898e-03,  9.73500419e-03,  1.39114841e+01,  2.26674205e-04,
           -2.53439147e-05,  4.75435862e-01,  2.69531543e+00, -7.25611680e-02,
            8.06642591e-02, -2.74421507e-01, -1.15196530e+01,  2.40409350e-02,
           -7.74271818e-04]), array([ 2.77129467e-02, -6.30607765e-03,  1.65517753e+00, -2.11458225e-04,
            4.33140844e-05, -2.36657301e-01,  7.06564901e-01, -7.30961259e-02,
            3.98076383e-02,  1.44845596e-01, -1.44032550e+00,  3.23112486e-02,
           -3.02924714e-03]), array([-1.89251241e-01,  8.67290103e-04,  8.59508062e+00, -4.33365130e-05,
           -2.61752136e-05,  1.53682112e-03,  2.82639690e-01,  4.32340576e-03,
           -5.43826462e-02, -9.99488880e-03, -1.73103738e+00, -6.58616209e-03,
            1.74630874e-02]), array([-7.71850083e-03,  6.66053909e-04, -2.18131146e+00,  7.77677119e-05,
           -1.48177530e-05,  6.34416203e-02, -1.41609773e-01,  1.58704540e-02,
           -2.34586601e-02, -1.75361213e-02,  1.15434317e+00, -4.78773921e-03,
            3.60910156e-03]), array([-1.19946479e-01, -6.76369582e-04,  5.04451151e+00,  2.49429092e-04,
           -5.55766883e-05, -3.59313243e-02,  5.54877167e-02,  4.91895282e-03,
           -1.30222909e-03,  1.13435717e-02, -2.34252648e+00,  2.45477912e-03,
            1.17665635e-02]), array([-3.78907997e-02,  5.29157169e-04, -5.52107085e-01,  1.08359040e-04,
           -2.45477769e-05,  1.60785704e-02, -2.56183479e-01,  3.27019194e-02,
           -2.05852835e-02, -1.54554701e-02,  7.73168281e-01, -7.11735839e-03,
            5.46670932e-03]), array([-4.65358105e-03, -1.86695376e-03, -2.15538530e+00,  2.39494809e-05,
            7.14234341e-06,  5.55913941e-03, -5.10201107e-01, -3.74834903e-03,
            1.91690304e-02,  2.57461096e-02,  1.61193550e+00, -7.34384005e-03,
            9.91673591e-04]), array([-4.69845237e-02, -4.24236934e-04,  2.55643379e+00, -1.10718777e-04,
            2.25143158e-05,  2.64248738e-02,  9.41103530e-02, -1.33752502e-02,
            1.95276069e-02, -9.15734582e-03, -6.98264341e-01,  1.05041497e-02,
           -3.85592188e-03]), array([-1.64896076e-02, -7.32384964e-04,  1.41822066e+00, -1.07211574e-05,
            3.92052526e-06, -2.88971559e-02,  2.66498471e-01, -5.09675895e-03,
            1.99480124e-02,  2.33611614e-02, -8.25986901e-01,  2.06004024e-03,
           -5.75538584e-04]), array([ 1.02440626e-02, -1.37350373e-03, -8.27342890e-01,  6.07512617e-05,
           -9.46179170e-06, -5.41445876e-02, -1.09871866e-01,  1.69171912e-02,
           -1.12370836e-02,  4.75092551e-02,  1.57878937e-01, -8.13171564e-03,
            4.51793028e-03]), array([-8.76582148e-03,  1.35237494e-04, -1.32007377e+00,  1.09885222e-04,
           -3.12382697e-05,  1.75845161e-02, -3.65593586e-01, -1.05106518e-02,
           -1.43236443e-02, -1.65198290e-02,  1.12895956e+00,  6.94418779e-03,
            6.91732909e-03]), array([-4.04113349e-02,  8.96115441e-04, -2.35181270e-01,  4.74931364e-05,
           -8.54823155e-06,  2.05482342e-02, -2.30342166e-01,  1.12648044e-02,
           -1.12836901e-02, -1.68236930e-02,  2.95588855e-01,  1.25031133e-03,
            2.09851079e-03]), array([-1.21099367e-02, -2.38047621e-04, -4.66663963e-01,  3.99784909e-05,
           -4.09692859e-06,  3.50814476e-03, -8.46875861e-02,  2.52074726e-02,
           -5.80440005e-03, -9.82291810e-04,  3.19171169e-01, -5.44424736e-03,
            9.26914552e-04]), array([-5.57273462e-02,  4.34863920e-03,  7.95763244e-01,  9.96826168e-05,
           -3.03065025e-05,  1.25330642e-01, -7.75337697e-01,  2.72072150e-02,
           -3.17344905e-02, -7.53303987e-02,  2.18401495e+00, -9.28971927e-03,
            8.84628555e-03]), array([-1.20402212e-02, -9.58323033e-04,  1.63309020e-01,  1.47110219e-04,
           -2.85348037e-05, -4.13680012e-02,  4.92354120e-02,  6.19303243e-02,
           -3.32647265e-02,  3.93248485e-03, -2.89696117e-01, -1.52626163e-02,
            8.29276312e-03]), array([ 1.72423814e-02, -1.00442926e-03,  2.91389168e+00,  5.96388711e-05,
           -2.40891233e-06, -1.93909968e-02,  6.11075989e-01,  2.99651989e-02,
            8.65080487e-03,  2.85031313e-02, -2.22283448e+00, -8.79758793e-03,
           -2.31308903e-04]), array([ 4.15028844e-02,  8.72662461e-04,  3.78604973e-01, -1.91705471e-05,
           -7.32682716e-07, -3.89891990e-02, -1.80942416e-01, -1.41138213e-02,
            1.05857156e-02,  8.98846247e-03,  4.10199817e-02,  3.60501353e-03,
            1.52738191e-03]), array([ 1.38367233e-02, -4.75670218e-04,  1.45793960e+01, -4.39201325e-04,
            1.73424045e-05,  1.62589772e-01,  1.17400925e+00, -2.23592579e-01,
            9.70491138e-03, -4.20190964e-02, -6.60755813e+00,  9.32740525e-02,
           -4.98640519e-03]), array([ 4.76605836e-01,  2.36831265e-02,  1.31979752e+01, -6.71325552e-04,
            1.92455687e-04,  1.68529539e-01,  2.26858046e+00, -9.64472155e-02,
            1.10134379e-01, -3.35779632e-01, -7.87536794e+00,  1.25643575e-01,
           -3.40539287e-02]), array([-1.22086411e-01, -2.98098666e-03, -9.09202424e+00,  3.53021807e-04,
           -6.04864935e-05, -4.74067313e-02, -3.96886454e-01,  6.43219429e-02,
           -5.24579751e-02,  6.22497855e-02,  2.75626790e+00, -9.81177554e-03,
            9.22500222e-03]), array([ 2.42865034e-01,  3.08413070e-03,  3.69450813e+00, -1.05362324e-04,
            3.35121486e-05, -2.17691903e-01,  1.61475607e-01,  4.79901219e-02,
            5.10188267e-02,  4.25249926e-02, -1.73012163e+00,  3.83944066e-02,
           -6.03665152e-03]), array([-2.91596724e-02, -1.72316544e-03, -1.70308285e-01,  2.78772540e-05,
           -5.78475347e-06, -6.08298454e-02, -2.05123817e-02, -7.15255719e-04,
           -2.08599209e-03,  4.29201439e-02,  9.11263067e-02, -3.13556060e-03,
            4.83138032e-03]), array([ 5.73499268e-02,  6.48564156e-03,  3.10146521e+00, -4.29498495e-05,
           -8.22432380e-06,  1.72788957e-01,  2.17684043e-01, -1.62606841e-02,
           -1.48757612e-02, -1.42456615e-01, -9.32544417e-01,  1.36378839e-02,
            2.00309187e-03]), array([ 2.20121899e-02,  2.50365120e-04, -1.68264197e+00,  1.31029553e-06,
            5.43564898e-06, -1.60987502e-03, -7.94856643e-02, -1.75916278e-02,
            2.89310594e-03, -8.38283240e-03,  2.10224761e-01,  2.50327452e-03,
           -8.24552696e-04]), array([ 8.14824571e-03,  1.19625230e-04,  4.48214608e+00, -5.75005197e-05,
            2.68714935e-05,  8.26854347e-02,  1.22961403e+00,  6.06307787e-02,
           -2.82988343e-02, -2.05760293e-02, -3.93055204e+00,  1.80151116e-02,
           -4.40416978e-03]), array([ 1.24727717e-01,  3.56815890e-03,  4.47984415e-01,  1.11290004e-04,
           -2.13079672e-05,  1.60896403e-01,  2.76107894e-01,  8.78048785e-02,
           -1.65446258e-02, -9.50843064e-02, -7.27878492e-01, -1.82809831e-02,
            7.82673132e-03]), array([-1.34242208e-01, -7.01493773e-04,  1.09947760e+01,  3.36709471e-04,
           -8.01359067e-05, -3.62812071e-02,  1.54854376e+00,  2.07110733e-01,
           -1.62451846e-01, -9.42013330e-03, -5.01979768e+00, -2.73150117e-02,
            1.86673925e-02]), array([ 2.87567784e-02,  1.03807500e-02,  1.37402318e+00, -1.33341144e-04,
            1.39610889e-05,  5.36088659e-02,  1.33428517e-01, -6.81190877e-02,
            9.48133972e-03, -8.26775483e-02, -7.33876548e-01,  2.07405696e-02,
           -1.18960828e-03]), array([ 1.08296624e-01,  9.67146899e-05, -5.59839163e+00, -3.46463610e-05,
            2.56572253e-05,  1.81086995e-02, -2.45223851e+00, -1.62437196e-02,
            4.28600871e-02,  2.95840971e-02,  6.75099881e+00,  1.24345843e-02,
           -6.31231346e-03]), array([ 3.90266745e-03,  1.99182691e-03, -4.46987160e-01, -2.27949503e-05,
           -4.73478456e-06,  4.97655384e-02, -6.20731260e-01, -1.10982908e-02,
           -2.62228453e-02, -4.32588066e-02,  1.11977292e+00,  3.84384928e-03,
            4.13807190e-03]), array([ 5.22596707e-02,  2.52629690e-04, -6.85023281e-01,  1.94454553e-06,
           -1.57990548e-05,  3.89394365e-02, -7.49575222e-02, -1.98966167e-02,
           -2.85337477e-02, -1.62999622e-02,  1.12677669e-01, -6.33747309e-03,
            1.12600690e-02]), array([ 1.94392306e-02, -6.54776685e-04,  1.75409437e+00,  1.34266496e-04,
           -3.24032989e-05,  3.70426522e-02,  1.78948247e-01,  1.52328019e-02,
           -2.01472507e-02, -1.30494151e-02, -7.46034751e-01, -5.77747967e-03,
            5.73549829e-03]), array([ 1.58825963e+02, -1.62840377e+01,  7.10242964e+03,  1.11233232e-01,
           -3.67538928e-02, -4.12249053e+02, -6.92361185e+02,  6.97808274e+01,
           -7.70041035e+01,  2.54753314e+02, -5.72517104e+02, -2.17667218e+01,
            1.61020757e+01]), array([-3.21273050e-02,  1.26502535e-03,  2.09573333e+00, -2.20151375e-05,
           -2.73610791e-05,  3.54176519e-02,  2.82286418e-01, -1.84575120e-02,
           -3.15878824e-02, -8.42729735e-03, -1.46952117e+00,  1.68625931e-03,
            1.20170510e-02]), array([ 7.92241584e-02,  3.57814595e-03, -2.85520394e+00, -5.97309771e-05,
            2.12118096e-05,  3.58918280e-02, -5.48494795e-01,  1.55701584e-02,
            1.23119762e-02, -5.62426677e-02,  1.48541697e+00,  5.28838583e-03,
           -3.72515035e-03]), array([ 5.14707415e-02,  1.27786068e-03, -5.34141223e-01, -7.04990480e-05,
            5.83404228e-06, -6.60604957e-02, -4.14757484e-01, -2.74376442e-02,
           -7.82373975e-03,  1.92440784e-04,  1.04132096e+00,  9.97210920e-03,
           -3.58669755e-05]), array([-9.29862933e-01, -1.51722904e-02,  1.56852712e+01,  6.37304364e-04,
           -1.24360878e-04,  1.88575719e-01,  1.22158255e+00,  1.91048713e-01,
           -1.31523906e-01,  7.50818211e-02, -1.52725738e+01, -3.16579129e-02,
            3.71549279e-02]), array([ 2.60239783e-02,  1.18294610e-02,  2.41457241e+00, -1.63977720e-04,
            7.86955815e-05,  2.42369986e-01,  2.29626174e+00, -8.24170214e-02,
            1.53254688e-01, -1.31980496e-01, -5.82656420e+00,  2.60326517e-02,
           -7.35809749e-03]), array([-1.63565243e-01, -4.94520714e-03,  1.19694785e+00,  1.28200002e-04,
           -2.63143388e-05, -1.16037191e-01,  1.35569211e+00, -1.38497650e-01,
            5.65605078e-02,  1.29147454e-01, -1.99129570e+00,  2.36439788e-02,
            6.92330506e-03]), array([-1.31621868e+00, -4.09751944e-02, -4.64159640e+01,  9.04586588e-03,
           -1.88838221e-03, -8.47306909e+00,  8.72058868e+00,  6.44889190e-01,
           -3.11198687e-01,  3.12715491e+00, -2.07149330e+01, -4.21875698e-01,
           -1.34848257e-01]), array([ 5.20650066e-03,  5.02214029e-04,  2.29773141e-01, -1.52357176e-05,
            3.75148926e-06, -3.79516088e-02, -1.24347900e-01,  2.35953748e-02,
           -3.01536034e-04,  6.44692111e-03, -3.33321810e-02,  2.64012535e-04,
            1.68750161e-04]), array([-1.18299404e-02,  2.28391449e-03, -5.38859203e-01,  2.72394902e-05,
           -9.34939233e-06,  4.38512960e-03, -2.64775829e-01,  1.91597970e-02,
           -1.25836260e-02, -2.69417241e-02,  7.10354976e-01, -4.49983658e-03,
            3.91492462e-03]), array([-4.69149085e-02,  1.48723492e-02, -5.43967018e+00,  3.20127082e-04,
           -1.00943714e-04,  3.20678056e-01, -1.39280270e+00, -1.25558262e-01,
            1.21311397e-02, -2.94941843e-01,  5.10658201e+00,  2.43038891e-02,
            1.83462643e-02]), array([ 4.02239381e-02,  1.90310071e-03, -7.63794013e-01,  3.24728020e-05,
           -8.68615007e-06,  3.22029503e-02,  3.99685337e-01, -1.57072630e-02,
           -4.04525177e-03, -2.14588837e-02, -6.67901331e-01, -2.28479757e-03,
            4.89255770e-03]), array([-1.50856291e-01, -1.96536726e-03,  1.14804330e+01,  2.65754323e-06,
            2.36651243e-05,  5.50622261e-02,  1.41507090e+00,  4.92894209e-02,
            2.85318971e-02,  1.79439202e-02, -5.85504881e+00, -1.60587772e-02,
            7.02748011e-03]), array([ 4.21867144e-02, -9.13322101e-04, -2.41503293e-01,  1.60764432e-05,
           -5.45828365e-06, -7.36683167e-03,  2.64104960e-01,  1.82607284e-03,
            5.05359031e-03,  2.30843513e-02, -3.41016722e-01, -4.00262442e-03,
            2.49302105e-03]), array([-5.02981951e-02, -1.53106856e-03,  1.75345658e+00, -3.12801255e-05,
           -1.54268461e-06, -3.59493348e-02, -1.00242330e-01, -2.43703838e-02,
            2.35988909e-02,  2.23437381e-02,  8.94653664e-02,  1.02773515e-02,
           -8.03314281e-04]), array([-5.30527522e-02, -1.07283963e-03, -3.35112807e+00,  1.78075303e-04,
           -4.17852393e-05,  1.45496928e-02, -3.88170401e-01, -1.18958345e-02,
           -1.01850808e-02, -1.68983637e-04,  1.26819784e+00,  1.29677462e-02,
            5.43540667e-03]), array([-1.13877748e-01, -6.01007433e-03,  9.47977290e+00,  1.61275443e-04,
           -2.79772198e-05, -4.45351783e-02, -3.81660983e-01, -1.34329450e-01,
            8.56497893e-02,  2.47146571e-01, -8.12048534e-01,  1.82034882e-02,
            7.19922191e-03]), array([-1.89861288e+00,  6.46137464e-02, -1.69587644e+01,  5.06505807e-03,
           -1.13552524e-03,  2.97170329e+00, -6.98500564e-01,  4.42253716e-01,
           -5.92459060e-01, -2.04503352e+00,  9.69212117e+00, -2.42982738e-01,
            1.96092183e-01]), array([-2.88299868e-02,  2.59206614e-04, -3.91394172e+00,  3.46413649e-05,
           -1.18954228e-05, -1.12382200e-01, -1.03965972e+00, -4.36373002e-02,
            3.29471937e-03,  2.63404316e-02,  2.86778390e+00,  1.19323765e-02,
            1.74135255e-03]), array([-2.10938804e-02, -4.51457267e-04,  1.89366901e+00,  5.50136600e-05,
           -2.74394464e-05,  1.33848420e-04,  7.19665369e-01,  3.68386867e-03,
           -1.97317303e-02, -4.87493532e-03, -1.98006845e+00, -1.40471185e-03,
            9.95920877e-03]), array([ 9.51125773e-04,  1.86974575e-03,  8.64972477e+00,  1.37734225e-04,
           -3.40857266e-05, -3.97288048e-02,  9.75149452e-01,  1.08204393e-01,
           -3.83412022e-02, -2.89292887e-02, -5.21962782e+00, -3.99941074e-02,
            2.66211592e-02]), array([-8.96961787e-03, -1.96296496e-03, -2.67102299e+00,  5.03631314e-05,
           -7.32137085e-06, -6.14624538e-02, -6.16784044e-01, -1.12276119e-02,
            1.60520098e-02,  2.93498739e-02,  1.85853336e+00,  8.00969915e-03,
            4.68941567e-04]), array([ 9.66151170e-02,  6.44260163e-03,  7.05752906e+00,  1.11551025e-04,
           -1.10381528e-05,  3.32813060e-01,  1.25853985e+00,  2.80712592e-02,
            5.47313828e-03, -1.84561093e-01, -4.74194354e+00, -7.74657019e-03,
            6.68898586e-03]), array([-4.23207490e-01,  1.41442443e-02,  2.27284526e+01, -2.71149752e-05,
           -4.87830763e-05,  2.82684819e-01,  1.56309281e+00, -1.83444911e-01,
           -5.59416767e-02, -1.28666331e-01, -7.09367051e+00,  1.22234160e-02,
            3.13507452e-02]), array([ 6.20524992e-02,  3.01202362e-03,  8.32533285e+00, -4.37672696e-04,
            1.14371313e-04,  4.43659084e-02,  1.50131567e+00, -1.23059455e-02,
            8.50759456e-02, -5.73747344e-02, -4.97747723e+00,  5.11531882e-02,
           -2.28104160e-02]), array([ 4.19798543e-02,  2.48563998e-03,  1.45852113e+00,  1.56538182e-05,
            3.45146461e-06,  4.48140225e-02,  5.59464181e-01,  1.51439039e-02,
            3.60320541e-05, -3.57693137e-02, -1.37022780e+00, -3.32401504e-03,
            8.95492964e-04]), array([-1.28467953e-01, -1.77678859e-02,  8.28059020e+00,  3.71500851e-05,
            4.13346615e-05, -1.65850231e-01,  9.24314883e-01,  1.39233656e-01,
            5.03422066e-02,  1.58805171e-01, -2.72914621e+00, -3.66871615e-02,
            4.48081894e-04]), array([-2.62503395e-01, -6.04907369e-03,  2.23675018e+01, -3.49282490e-04,
            7.70579468e-05,  5.90513666e-01, -4.80684517e-02,  7.99775071e-02,
           -5.62997474e-02, -2.77089720e-01, -6.79824424e+00, -4.49516962e-03,
            1.40762554e-02]), array([-5.32731449e-02,  2.99606386e-03, -8.22474938e-01, -5.25806211e-05,
            1.63369194e-07, -1.47490189e-02, -4.90432326e-01, -6.81230039e-02,
            3.75445070e-02, -1.46260625e-02,  2.29000390e+00,  1.06112206e-02,
            1.77671083e-03]), array([-2.76864973e-02,  5.95466633e-03,  2.38341752e+00, -3.90772564e-05,
            7.19824336e-06,  1.21443141e-01,  6.80441545e-01,  2.16854487e-02,
           -1.22957525e-03, -9.32404689e-02, -1.60896169e+00,  3.66574677e-03,
           -4.67221138e-04]), array([ 4.94088199e-02,  1.08807147e-03, -7.71280315e-01,  8.95752461e-05,
           -1.96952942e-05,  3.84944602e-02, -8.69196051e-02,  1.29123193e-02,
           -1.06013263e-02, -2.39623136e-02,  7.65705837e-01, -4.21675862e-03,
            2.90520129e-03]), array([ 1.35246502e-02, -9.03472548e-04,  1.26274701e-01, -2.53301459e-05,
            7.11333543e-06, -2.45506482e-02, -1.77249082e-02, -4.66657213e-03,
            6.58543969e-03,  1.80552975e-02, -4.03141128e-02,  2.11532756e-03,
           -8.66834694e-04]), array([ 3.10676128e-02, -2.56423022e-03, -1.24990863e-01,  4.32368573e-06,
           -2.20683266e-07, -3.73410099e-02, -4.61870296e-02,  1.89421235e-02,
           -3.93744152e-03,  4.10789583e-02,  1.85157614e-01,  9.22187333e-04,
            8.64732771e-04]), array([ 8.58253374e-03,  2.31589753e-03,  6.11273618e-01, -4.22187421e-05,
            3.04021308e-06,  1.16526743e-01,  4.61582991e-01, -7.19759011e-03,
           -2.66599119e-02, -5.66023222e-02, -1.03567189e+00,  3.60240135e-03,
            2.30408517e-03]), array([-9.17439782e-01, -8.42766698e-04, -4.50729780e+01,  1.21462529e-03,
           -2.35413627e-04, -9.93998973e-01, -1.01589687e+01,  7.42075177e-01,
           -2.15531359e-01,  8.55129101e-01,  2.83870965e+01, -2.09245498e-01,
            8.98743343e-02]), array([ 1.18464147e-02, -1.66944444e-04, -6.49013011e+00, -3.78622533e-05,
            2.82143032e-07,  2.16440433e-02, -1.36424454e+00, -3.44926470e-03,
           -8.36320771e-03, -2.49211968e-02,  5.43734125e+00,  2.98690681e-02,
           -1.36485943e-03]), array([ 2.22918405e-01, -3.40315177e-02,  2.10801976e+01, -1.68153332e-03,
            3.30823135e-04, -1.25941589e+00,  4.01220351e+00, -2.76570100e-01,
           -6.54665230e-03,  8.15067454e-01, -1.12990143e+01,  3.66261490e-02,
            4.44902384e-02]), array([-1.25428147e-01,  3.18602768e-03, -2.81939516e+00, -8.53938480e-05,
            3.23652765e-05,  2.80681552e-02,  2.56661504e-01, -8.80741608e-02,
            5.84094846e-02, -3.99893541e-02,  7.49418078e-01,  1.15953826e-02,
           -5.36065635e-04]), array([-6.62013770e-02,  1.55441785e-02,  7.94071204e+00, -4.42535483e-05,
            7.97990034e-08,  3.62357871e-01,  1.62426363e-01, -1.09241063e-02,
            4.12624441e-02, -1.85599069e-01, -1.63544495e+00, -3.30444314e-03,
            1.59917574e-03]), array([-6.58110208e-02, -9.89914578e-03,  5.03480454e+00, -5.88337152e-05,
            5.94494145e-06, -1.71385278e-01,  1.25751641e-01, -4.36384398e-02,
            4.15337034e-02,  1.57112836e-01, -1.76045811e+00,  1.22570010e-02,
            8.63060996e-04]), array([-7.33562637e-03,  2.52359444e-03,  3.87834809e+00, -4.54275062e-06,
           -1.55995168e-05,  5.16969122e-02,  2.39334461e-01,  1.20545091e-02,
           -2.53808247e-02, -4.47986266e-02, -1.26317674e+00,  3.06084128e-03,
            5.44307273e-03]), array([-2.33183565e-02, -3.23524637e-03,  1.61289728e-01,  3.74112125e-05,
           -1.91804867e-06, -6.46701646e-02, -6.03439123e-02,  1.41843488e-02,
            4.27231481e-03,  4.38708002e-02,  7.67035774e-02,  7.18245145e-05,
           -5.40924520e-04]), array([-1.35268391e-02, -1.21003218e-03,  1.92127071e-01, -3.76103339e-06,
           -5.60278490e-07, -4.08080319e-02, -1.43617494e-01, -7.31906816e-03,
            9.33051824e-03,  2.71547607e-02,  2.61098180e-01,  1.30534919e-03,
           -5.77655988e-05]), array([-1.12434950e-01, -4.53158252e-03, -7.39593630e+00,  3.11820236e-04,
           -4.01643270e-05, -1.47946243e-01,  6.84980142e-02,  2.93759627e-02,
           -5.79416967e-03,  7.02817996e-02,  1.55777184e+00, -1.08730346e-02,
            1.18993331e-02]), array([-2.53102611e-02, -7.45789889e-03,  6.00028536e+00, -5.15291628e-04,
            1.15557776e-04,  1.05086310e-01,  1.17989096e+00, -2.37461826e-01,
            1.17149352e-01,  1.20676658e-02, -4.13242352e+00,  7.47856422e-02,
           -2.63139585e-02]), array([-1.32143162e-02, -1.36718067e-03,  3.98598157e+00, -2.00362450e-04,
            3.66142748e-05, -2.13620594e-02,  1.97870250e-01, -9.52476601e-03,
            2.56167209e-02,  2.53223213e-02, -9.10636253e-01,  2.03798773e-02,
           -4.06902820e-03]), array([-3.05959093e-02, -9.50147282e-04, -1.25619277e+00,  2.06646817e-05,
           -1.24271256e-05, -2.80860510e-02,  1.05066195e-02, -3.04638141e-03,
           -1.29509936e-02,  2.77959418e-02,  3.97262907e-01,  5.16259240e-03,
            2.73058412e-03]), array([-1.14438279e-04, -1.09797837e-03, -1.04966160e-01,  2.13458568e-05,
           -2.84504863e-06, -2.21395632e-02, -3.23191978e-02,  2.23267113e-02,
           -1.20279404e-02,  1.55471007e-02,  1.61231951e-01, -4.90596883e-03,
            1.61733666e-03]), array([ 2.85067160e-02,  1.57761756e-03,  9.70743831e-01, -3.79030118e-06,
           -2.59830195e-06,  1.71851518e-02,  2.34111024e-01,  9.14661001e-04,
           -3.59107439e-03, -2.60055955e-02, -5.89658601e-01,  1.98657277e-03,
            5.87755444e-04]), array([-1.23083118e-01, -1.32903195e-02,  2.10827913e+00, -6.89308816e-06,
            8.38427862e-06,  1.08074956e-01,  1.80304674e+00, -1.06233759e-01,
            2.26018331e-02,  9.50423311e-02, -5.13952274e+00, -1.50775150e-02,
            1.83303194e-02]), array([ 4.93790863e-02,  1.36633575e-03,  7.02232453e-01, -4.10936500e-05,
            1.40609574e-05, -3.53192936e-02, -1.33200339e-01,  1.49817037e-02,
            1.38216321e-02,  1.31740094e-02,  1.43473297e-01, -4.73881040e-03,
            1.91798809e-03]), array([ 6.91835306e-03, -4.63399281e-04, -1.44244731e-01,  4.81120028e-05,
           -1.16821984e-05,  1.82430076e-02, -1.52878373e-01,  2.37124447e-02,
           -1.79269577e-02,  5.51042183e-03,  3.26364351e-01, -7.12633330e-03,
            4.45176521e-03]), array([ 1.60710402e-02, -1.37311116e-03,  3.36057826e+00,  6.67139025e-05,
           -1.36780914e-05, -8.94726396e-02,  8.10855835e-01,  5.75594613e-02,
           -1.40699684e-02,  6.93450979e-02, -2.19826258e+00, -9.18983054e-03,
            5.81828420e-03]), array([-1.31457678e-01, -5.05938662e-03, -2.96709965e+00,  2.98429797e-04,
            1.91583495e-06,  7.46273347e-02, -1.81601096e+00, -8.84633285e-02,
            1.32070106e-01,  1.88023087e-02,  3.54145822e+00,  2.90252231e-02,
           -1.03726209e-02]), array([-2.09227073e-01,  1.64540623e-03,  6.60433722e-01,  1.67470856e-05,
            4.90808998e-06, -1.48194186e-01,  1.64118153e+00,  3.51663377e-02,
           -1.47860641e-02,  5.73488212e-02, -4.51653016e+00, -1.73185035e-02,
            1.61679767e-02]), array([-1.92607374e-02,  7.43050778e-04,  1.38486893e+00, -4.06439555e-05,
            6.69292666e-06,  2.98790439e-03,  1.43248296e-01, -9.80600685e-04,
            6.99766084e-03, -2.64880864e-03, -8.17144855e-01,  9.07839190e-03,
           -1.73979691e-03]), array([ 2.14784115e-02, -1.74756981e-03, -2.20545767e+00,  9.32928817e-05,
           -1.86954443e-05, -1.03055894e-01, -6.38968025e-02,  3.93724982e-02,
           -4.60548314e-02,  6.64997808e-02,  8.62233690e-01, -1.26651990e-02,
            7.41505348e-03]), array([ 1.61556287e-01, -2.58360863e-03,  5.35824964e+00,  4.37739052e-04,
           -8.37083979e-05,  3.16747039e-01,  7.33854383e-01,  9.07642343e-02,
           -5.82948318e-02, -1.01488823e-01, -5.48345570e+00, -1.91636931e-02,
            2.09157605e-02]), array([ 9.99151323e-03, -2.64801007e-02,  2.33726261e+01,  3.37990445e-04,
           -4.65719058e-05, -3.16940279e-01,  7.44137922e+00,  5.69772706e-02,
            8.94465990e-02,  4.33736954e-01, -2.32188538e+01, -8.45128837e-02,
            3.21221023e-02]), array([-4.12188168e-03,  6.31027663e-03, -1.33386252e-01,  1.35896735e-05,
           -7.24202062e-06,  9.58540090e-02,  6.99609109e-02, -1.78099171e-02,
            5.41174480e-03, -7.25248878e-02, -9.27741989e-02,  2.43516117e-03,
            1.10176547e-03]), array([ 1.92946267e-01,  3.45228960e-03, -6.16710248e+00, -5.65668994e-04,
            1.47850338e-04, -6.71496528e-01, -2.87744485e+00,  2.86788704e-02,
            4.87586902e-02,  5.62060500e-02,  6.26209798e+00,  2.63217522e-02,
            2.98143644e-03]), array([ 1.78890697e-01,  6.70108264e-03,  3.70545100e+00,  5.63399673e-05,
            1.82950769e-05,  6.31077062e-02,  2.79105239e+00,  1.73268443e-01,
           -8.12943318e-04, -1.60568569e-01, -5.40487568e+00, -2.67839759e-02,
            2.99631085e-03]), array([-5.74668447e-02,  8.71676696e-04, -1.38440222e+00,  5.80275678e-05,
           -1.70382680e-05,  8.50432632e-03, -2.30518010e-01,  8.12543248e-03,
           -1.62297206e-02, -1.98733414e-02,  6.30779158e-01, -1.66412216e-03,
            5.39293965e-03]), array([ 1.44181932e-02,  3.71490434e-03,  3.92803619e-01,  3.77605060e-05,
           -2.48717787e-05,  2.93497719e-02, -4.54093430e-02, -3.50119575e-03,
           -2.39044196e-02, -4.83920654e-02,  7.84411356e-02,  1.78440983e-03,
            6.59850686e-03]), array([-6.16843423e-03,  2.38103891e-04, -3.13859526e+00,  3.21405951e-05,
           -1.71202744e-05,  2.34890950e-02,  2.03618319e-02, -1.54132969e-02,
           -2.87657379e-02, -2.17883709e-02,  6.47319789e-01,  1.78317637e-02,
            2.25082092e-03]), array([ 2.17712095e-04, -1.12083184e-03,  8.45961121e+00, -3.41707105e-07,
           -1.52121332e-06, -1.80824470e-01,  1.17462676e+00,  5.50519496e-02,
            1.15183743e-02,  7.59625787e-02, -3.12056420e+00, -1.18352095e-02,
            1.28732852e-02]), array([-6.75425041e-02, -1.47979407e-03,  1.93527056e+00,  3.99540960e-07,
            1.75986564e-06, -3.94850833e-02,  1.16439423e-01,  2.42205709e-02,
           -1.34510474e-02,  4.45417894e-02, -8.16680735e-01, -3.20982023e-03,
            3.67788315e-03]), array([-9.52496834e-02,  2.78376599e-03,  1.91223732e+00, -2.37525317e-04,
            2.43486002e-05, -4.82296500e-02, -2.91748464e-01, -1.05340675e-01,
            5.83008672e-02, -8.55395252e-03, -1.22979991e-01,  3.16264056e-02,
           -5.29537529e-03]), array([-2.13742951e-02, -2.13168117e-03,  2.25836956e-01,  4.62699421e-05,
           -1.20766763e-05, -2.97650300e-02, -2.34546387e-01, -2.48024100e-02,
            2.84947805e-03,  4.20577285e-02,  7.11015218e-01,  3.56722871e-03,
            1.75957115e-03]), array([-3.15799030e-01,  4.50784888e-03,  1.83147849e+01, -4.87323776e-04,
            1.06670878e-04,  1.91028103e-01,  1.71506053e+00, -8.79388652e-02,
            9.63217321e-02, -1.34868996e-01, -8.41115874e+00,  3.79633342e-02,
           -1.21987522e-02]), array([ 1.22920414e-01, -7.47182958e-05,  1.49305573e+00, -4.03243682e-05,
            7.69889252e-06, -4.07840408e-02,  8.40393099e-02, -3.72847860e-02,
            1.41658590e-02,  2.18054681e-02, -5.67773134e-01,  1.06915030e-02,
           -3.03973792e-03]), array([ 6.35486287e-02, -1.96507172e-03,  1.71190001e+00, -1.86824724e-05,
            7.13564499e-06, -5.09511246e-02,  3.27203035e-01,  1.65795943e-02,
           -4.54001846e-03,  3.21637897e-02, -1.03359450e+00,  1.09459310e-03,
           -7.34282278e-04]), array([-4.27175249e-02, -7.60863250e-03,  4.56624081e+00, -2.25577564e-05,
            1.46273200e-06, -5.71213877e-02,  9.65672593e-01,  6.20362230e-03,
           -1.85426279e-03,  6.99699992e-02, -3.49616144e+00,  5.09346991e-03,
            2.87868248e-03]), array([-1.46483124e+01, -2.45970145e+00,  2.83101492e+02,  1.93105665e-02,
            4.41955804e-03, -1.55199000e+01,  1.89031247e+02,  2.57732113e+01,
            1.46665325e+01,  3.70044726e+00, -2.07210231e+02, -3.45984975e+00,
           -1.84746372e+00])]
    Shape of the weights matrix:  115 13



```python
#Let's now run the simulation
parallelism = 12
numTrials = 10000
trial_indexes = list(range(0, parallelism))
seedRDD = sc.parallelize(trial_indexes, parallelism)
bFactorWeights = sc.broadcast(weights1)

trials1 = seedRDD.flatMap(lambda idx: \
                simulateTrialReturns(
                    max(int(numTrials/parallelism), 1), 
                    factorMeans, factorCov,
                    bFactorWeights.value
                ))
trials1.cache()

valueAtRisk1 = fivePercentVaR(trials1)
conditionalValueAtRisk1 = fivePercentCVaR(trials1)

print ( "Value at Risk(VaR) 5%:", valueAtRisk1)
print ( "Conditional Value at Risk(CVaR) 5%:", conditionalValueAtRisk1 )
```

    Value at Risk(VaR) 5%: -372.484326543507
    Conditional Value at Risk(CVaR) 5%: -636.8212183342457



```python
varConfidenceInterval = bootstrappedConfidenceInterval(trials1, fivePercentVaR, 100, 0.05)
cvarConfidenceInterval = bootstrappedConfidenceInterval(trials1, fivePercentCVaR, 100, .05)
print("VaR confidence interval: " , varConfidenceInterval)
print("CVaR confidence interval: " , cvarConfidenceInterval)

stat_found1 = kupiecTestPValue(stocksReturns1, valueAtRisk1, 0.05)
print("Statistical value from Kupiec test: " , stat_found1[1])
print("Kupiec test p-value: " , stat_found1[0])
```

    VaR confidence interval:  (-371.30756187525185, -376.31785372254535)
    CVaR confidence interval:  (-600.8099548521916, -643.493811273861)
    num failures: 227
    Number of stocks:  1294
    Statistical value from Kupiec test:  267.6942771735744
    Kupiec test p-value:  3.609435936228716e-60


<div class="alert alert-warning">

ANSWER
<ul><u>About the estimates</u>:
    <li>The VaR estimate is approximately -372.48. So, there is a 0.05 probability that our portfolio of stock investments will fall in value by more than 372.48 dollars over a two weeks period. It is this time much higher than in the previous simulation. It can be explained by the fact that the number of stocks we want to invest in is higher (we went from less than 35 to more than 100), so the total loss is greater.
      </li>
    <li>The same remarks can be applied for the CVaR estimate (of approximate value -636.82) which tells us that this loss is expected to go up to 636.82 dollars when this expected VaR estimate has been exceeded.</li>
</ul>

<ul> <u>About the intervals</u>:
    <li>The VaR estimate found is inside the interval found here, which is reassuring because the confidence interval is an interval that has a probability of including the VaR estimate</li>
    <li>As for the CVaR estimate found, it is also in the confidence interval found here.</li>
    
</ul>
<ul> <u>About the statistical values found</u>:
    <li>The statistical value found directly from the Kupiec test is <b>above 200</b>, which is much more than 0 and worse than when we had 29 stocks... </li>
    <li>The p-value found is 3.6e-60 approximately, which is much below 0.05 and much below 1.0, and worse than when we had 29 stocks.</li>
    <li>Moreover, the number of failures is 227 out of 1294 stocks, so we have a rate of more than 15%, which is higher than 5%. So, the distribution of probability is not appropriate again.</li>
    <li>Therefore, <b>the null hypothesis that the VaR is reasonable here is an very bad estimate again</b>. We should try other distributions than the normal distribution.</li>
</ul>

</div>

### Question 10
<div class="alert alert-info">

In the previous questions, we used the normal distributions to sample the factors returns.  

Try to study how results vary when selecting other probability distributions: our goal is to improve the result of our MCS.
</div>


```python
#we define a new simulation function so we can use a TRIANGULAR distribution
def simulateTrialReturnsTriang(numTrials, factorMeans, factorCov, weights, lows = None, highs = None):
    trialReturns = []
    for i in range(0, numTrials):
        # generate sample of factors' returns
        trialFactorReturns = [np.random.triangular(lows[i],factorMeans[i],highs[i]) for i in range(len(factorMeans))]

        # featurize the factors' returns
        trialFeatures = featurize(trialFactorReturns)
        
        # insert weight for intercept term
        trialFeatures.insert(0,1)
        
        trialTotalReturn = 0
        
        # calculate the return of each instrument
        # then calulate the total of return for this trial features
        
        for weight in weights:
            trialTotalReturn += sum([weight[j] * trialFeatures[j] for j in range(len(weight))])
        trialReturns.append(trialTotalReturn)
    return trialReturns

```


```python
#we run the simulation 
parallelism = 12
numTrials = 10000
trial_indexes = list(range(0, parallelism))
seedRDD = sc.parallelize(trial_indexes, parallelism)
bFactorWeights = sc.broadcast(weights)

triangularTrials = seedRDD.flatMap(lambda idx: \
                simulateTrialReturnsTriang(
                    max(int(numTrials/parallelism), 1), 
                    factorMeans, factorCov,
                    bFactorWeights.value,
                    lows = lows, highs = highs
                ))
triangularTrials.cache()

triangularValueAtRisk = fivePercentVaR(triangularTrials)
triangularConditionalValueAtRisk = fivePercentCVaR(triangularTrials)

print ("Value at Risk(VaR) 5% given by Triangular distribution: ", triangularValueAtRisk)
print ("Conditional Value at Risk(CVaR) 5% given by Triangular distribution: ", triangularConditionalValueAtRisk)
```

    Value at Risk(VaR) 5% given by Triangular distribution:  -14.049093845614106
    Conditional Value at Risk(CVaR) 5% given by Triangular distribution:  -16.38277269409191



```python
varConfidenceIntervalTriang = bootstrappedConfidenceInterval(triangularTrials, fivePercentVaR, 100, 0.05)
cvarConfidenceIntervalTriang = bootstrappedConfidenceInterval(triangularTrials, fivePercentCVaR, 100, .05)
print("VaR confidence interval given by Triangular distribution : " , varConfidenceIntervalTriang)
print("CVaR confidence interval given by Triangular distribution: " , cvarConfidenceIntervalTriang)

stat_found2 = kupiecTestPValue(stocksReturns, triangularValueAtRisk, 0.05)
print("Statistical value from Kupiec test: " , stat_found2[1])
print("Kupiec test p-value: " , stat_found2[0])
```

    VaR confidence interval given by Triangular distribution :  (-14.034518215351504, -14.481771805189796)
    CVaR confidence interval given by Triangular distribution:  (-16.386325208556975, -16.263656498918397)
    num failures: 300
    Number of stocks:  1294
    Statistical value from Kupiec test:  498.0363715443659
    Kupiec test p-value:  2.5422477860386094e-110


<div class="alert alert-warning">

COMMENT
<ul>We tried to test with a triangular distribution with the low 5% percentile as the lower limit (left), the high 95% percentile as the upper limit (right) and factorMeans vector for the mode of the distribution for each factor. We have some comments about the estimates:
    <li>The VaR estimate is approximately -14.05. So, there is a 0.05 probability that our portfolio of stock investments will fall in value by more than 14.05 dollars over a two weeks period. It is this time much higher than in the previous simulation. It can be explained by the fact that the number of stocks we want to invest in is higher (we went from less than 35 to more than 100), so the total loss is greater.
      </li>
    <li>The same remarks can be applied for the CVaR estimate (of approximate value -16.38) which tells us that this loss is expected to go up to 16.38 dollars when this expected VaR estimate has been exceeded.</li>
</ul>

<ul> About the intervals:
    <li>The VaR estimate found is inside the interval found here, which is reassuring because the confidence interval is an interval that has a probability of including the VaR estimate</li>
    <li>As for the CVaR estimate found, it is also in the confidence interval found here.</li>
    
</ul>
<ul> About the statistical values found:
    <li>The statistical value found directly from the Kupiec test is <b>almost 500</b> ! And though we came back to the case where we had 29 stocks, the result is worst than what we had obtained with the multivariate normal distribution. </li>
    <li>The p-value found is 2.5e-110 approximately, which is much below 0.05 and much below 1.0, and worse than when we had 29 stocks.</li>
    <li>Moreover, the number of failures is 300 out of 1294 stocks, so we have a rate of more than 20%, which is higher than 5%. So, the distribution of probability is not appropriate again.</li>
    <li>Therefore, <b>the null hypothesis that the VaR is reasonable here is an very bad estimate again</b>. </li>
    <li>The triangular distribution is not better than the normal one. <b>However, we can try to vary the parameters (left and right) of the triangular distribution, to see how the results evolve.</b></li>
</ul>

</div>


```python
#we try other choices for the parameters of the triangular distribution
percentiles_values = []
Var_Triang_values = []
CVar_Triang_values = []
kupiec_Triang_values = []
pValue_Triang_values = []
for i in range(5):
    lows = [np.percentile(factorsReturn,2*i) for factorsReturn in factorsReturns]
    highs = [np.percentile(factorsReturn,100-2*i) for factorsReturn in factorsReturns]
    
    triangularTrials = seedRDD.flatMap(lambda idx: \
                simulateTrialReturnsTriang(
                    max(int(numTrials/parallelism), 1), 
                    factorMeans, factorCov,
                    bFactorWeights.value,
                    lows, highs
                ))
    triangularTrials.cache()

    triangularValueAtRisk = fivePercentVaR(triangularTrials)
    triangularConditionalValueAtRisk = fivePercentCVaR(triangularTrials)
    
    print("########## New Simulation ##########\n")
    
    print("percentile: ", 2*i)
    print ("Value at Risk(VaR) 5%:", triangularValueAtRisk)
    print ("Conditional Value at Risk(CVaR) 5%:", triangularConditionalValueAtRisk)
    varConfidenceIntervalTrian = bootstrappedConfidenceInterval(triangularTrials, fivePercentVaR, 100, 0.05)
    cvarConfidenceIntervalTrian = bootstrappedConfidenceInterval(triangularTrials, fivePercentCVaR, 100, .05)
    
    stat_found3 = kupiecTestPValue(stocksReturns, triangularValueAtRisk, 0.05)
    print("VaR confidence interval: " , varConfidenceIntervalTrian)
    print("CVaR confidence interval: " , cvarConfidenceIntervalTrian)

    print("Statistical value from Kupiec test: " , stat_found3[1])
    print("Kupiec test p-value: " , stat_found3[0])
    
    percentiles_values.append(2*i)
    Var_Triang_values.append(triangularValueAtRisk)
    CVar_Triang_values.append(triangularConditionalValueAtRisk)
    kupiec_Triang_values.append(stat_found3[1])
    pValue_Triang_values.append(stat_found3[0])
    
    print("\n")
```

    ########## New Simulation ##########
    
    percentile:  0
    Value at Risk(VaR) 5%: -79.29622876953263
    Conditional Value at Risk(CVaR) 5%: -100.47024671186466
    num failures: 6
    Number of stocks:  1294
    VaR confidence interval:  (-81.07794555802609, -78.36927450481451)
    CVaR confidence interval:  (-98.76644454494354, -100.52535727794945)
    Statistical value from Kupiec test:  91.6233693654797
    Kupiec test p-value:  1.0484746529084402e-21
    
    
    ########## New Simulation ##########
    
    percentile:  2
    Value at Risk(VaR) 5%: -22.4116141420793
    Conditional Value at Risk(CVaR) 5%: -25.893129389374323
    num failures: 174
    Number of stocks:  1294
    VaR confidence interval:  (-22.597405499979367, -22.41146371801759)
    CVaR confidence interval:  (-25.78437824126428, -25.949382067157337)
    Statistical value from Kupiec test:  135.6940213017633
    Kupiec test p-value:  2.3277361510399826e-31
    
    
    ########## New Simulation ##########
    
    percentile:  4
    Value at Risk(VaR) 5%: -18.642387931973598
    Conditional Value at Risk(CVaR) 5%: -21.403121349463145
    num failures: 218
    Number of stocks:  1294
    VaR confidence interval:  (-18.714051811458766, -18.598371074061)
    CVaR confidence interval:  (-21.520892023819343, -21.60744246890812)
    Statistical value from Kupiec test:  242.98952874328484
    Kupiec test p-value:  8.767408944597074e-55
    
    
    ########## New Simulation ##########
    
    percentile:  6
    Value at Risk(VaR) 5%: -15.78412211990549
    Conditional Value at Risk(CVaR) 5%: -18.15003481650301
    num failures: 270
    Number of stocks:  1294
    VaR confidence interval:  (-15.704195653146076, -15.84488786942227)
    CVaR confidence interval:  (-18.366269609954134, -18.1214385867058)
    Statistical value from Kupiec test:  397.2490968941918
    Kupiec test p-value:  2.1866374532320223e-88
    
    
    ########## New Simulation ##########
    
    percentile:  8
    Value at Risk(VaR) 5%: -14.136199860670237
    Conditional Value at Risk(CVaR) 5%: -16.38616758629027
    num failures: 299
    Number of stocks:  1294
    VaR confidence interval:  (-13.917331087460058, -14.397114352514906)
    CVaR confidence interval:  (-16.43897793809893, -16.559332425686797)
    Statistical value from Kupiec test:  494.54774579227296
    Kupiec test p-value:  1.4597674019101995e-109
    
    



```python
#let's plot the results

f, axarr = plt.subplots(4, sharex=True)
axarr[0].plot(percentiles_values, Var_Triang_values)
axarr[0].set_ylabel("VaR")

axarr[1].plot(percentiles_values, CVar_Triang_values)
axarr[1].set_ylabel("CVaR")

axarr[2].plot(percentiles_values, kupiec_Triang_values)
axarr[2].set_ylabel("Kupiec values")

axarr[3].plot(percentiles_values, pValue_Triang_values)
axarr[3].set_ylabel("p-values")
axarr[3].set_xlabel("Percentile (lower limit)")
plt.show()
```

<div class="alert alert-warning">

COMMENT
<ul>The former results were not really satisfying. We tried to test the triangular distribution by varying the low percentile (for the lower left limit) and the high percentile (for the upper right limit) and keeping the same factorMeans vector for the mode of the distribution for each factor. 
We have some comments about the evolutin:
    <li>The VaR and CVaR estimates are still negative and both get higher in absolute value as the percentile for the lower limit increases.</li>
    <li>The statistical value found directly from the Kupiec test also increases up to almost 500 when the percentile increases. Therefore, the result gets worse.</li>
    <li>Similarly, the p-values found are decreasing towards 0 when the percentile for the lower limit increases, so the model gets worse and worse.</li>
</ul>

<ul> About the intervals:
    <li>Sometimes, the VaR or the CVaR found doesn't fit in the corresponding interval, which is not normal.</li>
    <li>we tried to find an explanation, but could not...</li>
    
</ul>
<ul> About the statistical values found:
    <li>In any cas, the p-values are too far from 0.05, even more than in the multivariate normal distribution. So, the triangular distribution is not that good to fit our data.</li>
</ul>

</div>


```python
#we define a new simulation function so we can use a UNIFORM distribution
lows = [np.percentile(factorsReturn,0) for factorsReturn in factorsReturns]
highs = [np.percentile(factorsReturn,100) for factorsReturn in factorsReturns]


def simulateTrialReturnsUniform(numTrials, factorMeans, factorCov, weights, lows = None, highs = None):
    trialReturns = []
    for i in range(0, numTrials):
        # generate sample of factors' returns
        trialFactorReturns = [np.random.uniform(lows[i], highs[i]) for i in range(len(factorMeans))]

        # featurize the factors' returns
        trialFeatures = featurize(trialFactorReturns)
        
        # insert weight for intercept term
        trialFeatures.insert(0,1)
        
        trialTotalReturn = 0
        
        # calculate the return of each instrument
        # then calulate the total of return for this trial features
        
        for weight in weights:
            trialTotalReturn += sum([weight[j] * trialFeatures[j] for j in range(len(weight))])
        trialReturns.append(trialTotalReturn)
    return trialReturns

```


```python
#we run the simulation 
parallelism = 12
numTrials = 10000
trial_indexes = list(range(0, parallelism))
seedRDD = sc.parallelize(trial_indexes, parallelism)
bFactorWeights = sc.broadcast(weights)

uniformTrials = seedRDD.flatMap(lambda idx: \
                simulateTrialReturnsUniform(
                    max(int(numTrials/parallelism), 1), 
                    factorMeans, factorCov,
                    bFactorWeights.value,
                    lows = lows, highs = highs
                ))
uniformTrials.cache()

uniformValueAtRisk = fivePercentVaR(uniformTrials)
uniformConditionalValueAtRisk = fivePercentCVaR(uniformTrials)

print ("Value at Risk(VaR) 5% given by Uniform distribution: ", uniformValueAtRisk)
print ("Conditional Value at Risk(CVaR) 5% given by Uniform distribution: ", uniformConditionalValueAtRisk)
```

    Value at Risk(VaR) 5% given by Uniform distribution:  -120.97053674924591
    Conditional Value at Risk(CVaR) 5% given by Uniform distribution:  -137.15674590164105



```python
varConfidenceIntervalUnif = bootstrappedConfidenceInterval(uniformTrials, fivePercentVaR, 100, 0.05)
cvarConfidenceIntervalUnif = bootstrappedConfidenceInterval(uniformTrials, fivePercentCVaR, 100, .05)
print("VaR confidence interval given by Uniform distribution : " , varConfidenceIntervalUnif)
print("CVaR confidence interval given by Uniform distribution: " , cvarConfidenceIntervalUnif)

stat_found4 = kupiecTestPValue(stocksReturns, uniformValueAtRisk, 0.05)
print("Statistical value from Kupiec test: " , stat_found4[1])
print("Kupiec test p-value: " , stat_found4[0])
```

    VaR confidence interval given by Uniform distribution :  (-122.3246145955257, -119.62358974714402)
    CVaR confidence interval given by Uniform distribution:  (-137.41593511995384, -137.16771113411517)
    num failures: 1
    Number of stocks:  1294
    Statistical value from Kupiec test:  122.305709879868
    Kupiec test p-value:  1.9787374035492386e-28


<div class="alert alert-warning">

COMMENT
<ul>We tried to change the distribution and test a <b>uniform distribution</b>. 
The results are not better:
    <li>The number of failures is very low compared to what had been obtained before (only 1 failure).</li>
    <li>But, the value found directly from the Kupiec test is still very high compared to 0 (more than 100). And the p-value is very low (around 2e-29) compared to 0.05.</li>
</ul>

</div>


```python
#we define a new simulation function so we can use a EXPONENTIAL distribution
lows = [np.percentile(factorsReturn,0) for factorsReturn in factorsReturns]
highs = [np.percentile(factorsReturn,100) for factorsReturn in factorsReturns]


def simulateTrialReturnsExp(numTrials, factorMeans, factorCov, weights, lows = None, highs = None):
    trialReturns = []
    for i in range(0, numTrials):
        # generate sample of factors' returns
        
        trialFactorReturns = [np.random.exponential(factorMeans[i]) for i in range(len(factorMeans))] 
        #we know that the mean of an exponential distribution of parameter lambda=1/beta is 1/lambda, i.e., beta
        #beta is the parameter considered in numpy.random.exponential

        # featurize the factors' returns
        trialFeatures = featurize(trialFactorReturns)
        
        # insert weight for intercept term
        trialFeatures.insert(0,1)
        
        trialTotalReturn = 0
        
        # calculate the return of each instrument
        # then calulate the total of return for this trial features
        
        for weight in weights:
            trialTotalReturn += sum([weight[j] * trialFeatures[j] for j in range(len(weight))])
        trialReturns.append(trialTotalReturn)
    return trialReturns

```


```python
#we run the simulation 
parallelism = 12
numTrials = 10000
trial_indexes = list(range(0, parallelism))
seedRDD = sc.parallelize(trial_indexes, parallelism)
bFactorWeights = sc.broadcast(weights)

expTrials = seedRDD.flatMap(lambda idx: \
                simulateTrialReturnsExp(
                    max(int(numTrials/parallelism), 1), 
                    factorMeans, factorCov,
                    bFactorWeights.value,
                    lows = lows, highs = highs
                ))
expTrials.cache()

expValueAtRisk = fivePercentVaR(expTrials)
expConditionalValueAtRisk = fivePercentCVaR(expTrials)

print ("Value at Risk(VaR) 5% given by Exponential distribution: ", expValueAtRisk)
print ("Conditional Value at Risk(CVaR) 5% given by Exponential distribution: ", expConditionalValueAtRisk)
```

    Value at Risk(VaR) 5% given by Exponential distribution:  -2.7583634554780727
    Conditional Value at Risk(CVaR) 5% given by Exponential distribution:  -2.920658991722667



```python
varConfidenceIntervalExp = bootstrappedConfidenceInterval(expTrials, fivePercentVaR, 100, 0.05)
cvarConfidenceIntervalExp = bootstrappedConfidenceInterval(expTrials, fivePercentCVaR, 100, .05)
print("VaR confidence interval given by Uniform distribution : " , varConfidenceIntervalExp)
print("CVaR confidence interval given by Uniform distribution: " , cvarConfidenceIntervalExp)

stat_found5 = kupiecTestPValue(stocksReturns, expValueAtRisk, 0.05)
print("Statistical value from Kupiec test: " , stat_found5[1])
print("Kupiec test p-value: " , stat_found5[0])
```

    VaR confidence interval given by Uniform distribution :  (-2.784251054524954, -2.739158309639585)
    CVaR confidence interval given by Uniform distribution:  (-2.90967957176745, -2.9230602393171687)
    num failures: 517
    Number of stocks:  1294
    Statistical value from Kupiec test:  1436.0304735886507
    Kupiec test p-value:  0.0


<div class="alert alert-warning">

COMMENT
<ul>We tried to change the distribution and test an <b>exponential distribution</b>. 
The results are even worse:
    <li>The number of failures is the highest compared to what had been obtained before (more than 500 failures so almost 40% of failure rate).</li>
    <li>Moreover, the value found directly from the Kupiec test is even higher and the p-value is even lower, equal to 0 !</li>
</ul>

</div>


```python
#lets compare the models

#Kupiec test statistical value
models_names = ["Normal","Triangular","Uniform","Exponential"]
models = range(0,4)
kupiec = [55.9, 91.6, 122.3, 1436]

plt.bar( models, kupiec, align='center')
plt.xticks(models, models_names)
plt.ylabel("Kupiec test statistical value")
plt.show()
```


```python
#lets compare the models

#Kupiec test statistical value
models_names = ["Normal","Triangular","Uniform","Exponential"]
models = range(0,4)
pvalues = [8e-14, 1e-21, 2e-28, 0]

plt.bar( models, pvalues, align='center')
plt.xticks(models, models_names)
plt.ylabel("p-values")
plt.show()
```

<div class="alert alert-warning">

COMMENT
<ul>To conclude, according to the graphs above, it looks like the <b>normal distribution</b> was the best model stock returns:
    <li>It gives the p-value closest to 0.05 and a Kupiec statistical value closest to 0.</li>
    <li>It can be explained by the fact the it is the only distribution that takes into account the inter-dependency between factors, thanks to the covariance matrix. In the other distributions, we did not introduce dependency between the factors, which was not ideal.</li>
</ul>

</div>

# 6. Summary
In this lecture, we studied the Monte Carlo Simulation method and its application to estimate financial risk. To apply it, first, we needed to define the relationship between market factors and the instruments' returns. In such step, you must define the model which maps the market factors' values to the instruments' values: in our use case, we used a linear regression function for building our model. Next, we also had to find the parameters of our model, which are the weights of the factors we considered. Then, we had to study the distribution of each market factor. A good way to do that is using Kernel density estimation to smooth the distribution and plot it. Depending on the shape of each figure, we had to guess the best fit distribution for each factor: in our use case, we used a very simple approach, and decided that our smoothed distributions all looked normal distributions. 

Then, the idea of Monte Carlo simulation was to generate many possible values for each factor and calculate the corresponding outcomes by a well-defined model in each trial. After many trials, we were able to calculate VaR from the sequences of outcome's values. When the number of trials is large enough, the VaR converges to reasonable values, that we could validate using well-known statistical hypothesis. 

# References
- The example in section 2 is inspired from [this article](http://www.solver.com/monte-carlo-simulation-example).
- [Backtesting Value-at-Risk models](https://aaltodoc.aalto.fi/bitstream/handle/123456789/181/hse_ethesis_12049.pdf?sequence=1) (Kansantaloustiede, 2009) - (A good reference to study Backtesting).



```python

```

7a301ba430490ea4c36d99c6fcd7108ca7b9b0c0
ipynb
Jupyter Notebook
lab2-Estimating-Financial-Risk-Monte-Carlo-Simulation/Lab2-MC-Bonnaud-Nguyen.ipynb
kanguyn/Algorithmic-Machine-Learning-Spring2018
2cc143cbdba5661240947feb1d79fa74c86dcf93
MIT
lab2-Estimating-Financial-Risk-Monte-Carlo-Simulation/Lab2-MC-Bonnaud-Nguyen.ipynb
kanguyn/Algorithmic-Machine-Learning-Spring2018
2cc143cbdba5661240947feb1d79fa74c86dcf93
MIT
lab2-Estimating-Financial-Risk-Monte-Carlo-Simulation/Lab2-MC-Bonnaud-Nguyen.ipynb
kanguyn/Algorithmic-Machine-Learning-Spring2018
2cc143cbdba5661240947feb1d79fa74c86dcf93
MIT
Qwen/Qwen-72B
1. YES
2. YES