1
+ # import needed modules
2
+ import quandl
3
+ import pandas as pd
4
+ import numpy as np
5
+ import matplotlib .pyplot as plt
6
+
7
+ # get adjusted closing prices of 5 selected companies with Quandl
8
+ quandl .ApiConfig .api_key = 'zcfJ6696mcZScjzsyeta'
9
+ selected = ['CNP' , 'F' , 'WMT' , 'GE' , 'TSLA' ]
10
+ data = quandl .get_table ('WIKI/PRICES' , ticker = selected ,
11
+ qopts = { 'columns' : ['date' , 'ticker' , 'adj_close' ] },
12
+ date = { 'gte' : '2014-1-1' , 'lte' : '2016-12-31' }, paginate = True )
13
+
14
+ # reorganise data pulled by setting date as index with
15
+ # columns of tickers and their corresponding adjusted prices
16
+ clean = data .set_index ('date' )
17
+ table = clean .pivot (columns = 'ticker' )
18
+
19
+ # calculate daily and annual returns of the stocks
20
+ returns_daily = table .pct_change ()
21
+ returns_annual = returns_daily .mean () * 250
22
+
23
+ # get daily and covariance of returns of the stock
24
+ cov_daily = returns_daily .cov ()
25
+ cov_annual = cov_daily * 250
26
+
27
+ # empty lists to store returns, volatility and weights of imiginary portfolios
28
+ port_returns = []
29
+ port_volatility = []
30
+ stock_weights = []
31
+
32
+ # set the number of combinations for imaginary portfolios
33
+ num_assets = len (selected )
34
+ num_portfolios = 50000
35
+
36
+ # populate the empty lists with each portfolios returns,risk and weights
37
+ for single_portfolio in range (num_portfolios ):
38
+ weights = np .random .random (num_assets )
39
+ weights /= np .sum (weights )
40
+ returns = np .dot (weights , returns_annual )
41
+ volatility = np .sqrt (np .dot (weights .T , np .dot (cov_annual , weights )))
42
+ port_returns .append (returns )
43
+ port_volatility .append (volatility )
44
+ stock_weights .append (weights )
45
+
46
+ # a dictionary for Returns and Risk values of each portfolio
47
+ portfolio = {'Returns' : port_returns ,
48
+ 'Volatility' : port_volatility }
49
+
50
+ # extend original dictionary to accomodate each ticker and weight in the portfolio
51
+ for counter ,symbol in enumerate (selected ):
52
+ portfolio [symbol + ' Weight' ] = [Weight [counter ] for Weight in stock_weights ]
53
+
54
+ # make a nice dataframe of the extended dictionary
55
+ df = pd .DataFrame (portfolio )
56
+
57
+ # get better labels for desired arrangement of columns
58
+ column_order = ['Returns' , 'Volatility' ] + [stock + ' Weight' for stock in selected ]
59
+
60
+ # reorder dataframe columns
61
+ df = df [column_order ]
62
+
63
+ # plot the efficient frontier with a scatter plot
64
+ plt .style .use ('seaborn' )
65
+ df .plot .scatter (x = 'Volatility' , y = 'Returns' , figsize = (10 , 8 ), grid = True )
66
+ plt .xlabel ('Volatility (Std. Deviation)' )
67
+ plt .ylabel ('Expected Returns' )
68
+ plt .title ('Efficient Frontier' )
69
+ plt .show ()
0 commit comments