Files changed (1) hide show
  1. ef.py +46 -6
ef.py CHANGED
@@ -6,13 +6,26 @@ import streamlit as st
6
  import plotly.graph_objects as go
7
  import plotly.express as px
8
 
 
 
 
 
9
  def ef_viz(stock_df,choices):
10
- st.write("EF Visualization KOI EDITS")
 
 
 
 
 
 
 
 
 
11
  symbols, weights, investment = choices.values()
12
  tickers = symbols
13
 
14
  #tickers.append('sp500')
15
- st.write(tickers)
16
  #st.write(stock_df)
17
 
18
  # Yearly returns for individual companies
@@ -30,12 +43,12 @@ def ef_viz(stock_df,choices):
30
  assets = pd.concat([ind_er, ann_sd], axis=1) # Creating a table for visualising returns and volatility of assets
31
  assets.columns = ['Returns', 'Volatility']
32
  assets
33
- st.write(assets)
34
  ln_pct_change = stock_df[tickers].pct_change().apply(lambda x: np.log(1+x))[1:]
35
  #Cov Matrix
36
  cov_matrix =ln_pct_change.cov()
37
 
38
-
39
  p_ret = [] # Define an empty array for portfolio returns
40
  p_vol = [] # Define an empty array for portfolio volatility
41
  p_weights = [] # Define an empty array for asset weights
@@ -62,11 +75,31 @@ def ef_viz(stock_df,choices):
62
  data[symbol] = [w[counter] for w in p_weights]
63
 
64
  port_ef_df = pd.DataFrame(data)
65
- st.write(port_ef_df[tickers].T)
 
 
66
  rf = 0.041
67
  min_vol_port = port_ef_df.iloc[port_ef_df['Volatility'].idxmin()]
68
  optimal_risky_port = port_ef_df.iloc[((port_ef_df['Returns']-rf)/port_ef_df['Volatility']).idxmax()]
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  ## Create Figure
72
 
@@ -84,6 +117,13 @@ def ef_viz(stock_df,choices):
84
 
85
  ])
86
  )
 
 
 
87
  #https://stackoverflow.com/questions/59057881/python-plotly-how-to-customize-hover-template-on-with-what-information-to-show
88
- st.plotly_chart(fig, use_container_width=True)
 
 
 
 
89
  #st.write(stock_df)
 
6
  import plotly.graph_objects as go
7
  import plotly.express as px
8
 
9
+
10
+ ### START AND RUN STREAMLIT
11
+ #https://docs.streamlit.io/library/get-started/installation
12
+
13
  def ef_viz(stock_df,choices):
14
+ #st.write("EF Visualization KOI EDITS")
15
+ # st.header('CAPM Model and the Efficient Frontier')
16
+ # """
17
+ # CAPM model measure systematic risks, however it has unrealistic assumptions and relies heavily on a linear interpretation
18
+ # of the risks vs. returns relationship. It is better to use CAPM model in conjunction with the Efficient Frontier to better
19
+ # graphically depict volatility (a measure of investment risk) for the defined rate of return. <br>
20
+ # Each circle depicted above is a variation of the portfolio with the same input assest, only different weights.
21
+ # Portfolios with higher volatilities has a yellower shade of hue, while portfolios with a higher return has a bigger radius. <br>
22
+ # As you input different porfolio assets, take note of how diversification can improve a portfolio's risk versus reward profile.
23
+ # """
24
  symbols, weights, investment = choices.values()
25
  tickers = symbols
26
 
27
  #tickers.append('sp500')
28
+ #st.write(tickers)
29
  #st.write(stock_df)
30
 
31
  # Yearly returns for individual companies
 
43
  assets = pd.concat([ind_er, ann_sd], axis=1) # Creating a table for visualising returns and volatility of assets
44
  assets.columns = ['Returns', 'Volatility']
45
  assets
46
+ #st.write(assets)
47
  ln_pct_change = stock_df[tickers].pct_change().apply(lambda x: np.log(1+x))[1:]
48
  #Cov Matrix
49
  cov_matrix =ln_pct_change.cov()
50
 
51
+ ## CREATE PORFOLIOS WEIGHTS
52
  p_ret = [] # Define an empty array for portfolio returns
53
  p_vol = [] # Define an empty array for portfolio volatility
54
  p_weights = [] # Define an empty array for asset weights
 
75
  data[symbol] = [w[counter] for w in p_weights]
76
 
77
  port_ef_df = pd.DataFrame(data)
78
+ #st.write(port_ef_df[tickers].T)
79
+ ## NEEDS INPUT INSTEAD OF HARD CODE
80
+ a = 5 #the coefficient of risk aversion is A. If an invest is less risk averse A is small. We assume 25 < A < 35.
81
  rf = 0.041
82
  min_vol_port = port_ef_df.iloc[port_ef_df['Volatility'].idxmin()]
83
  optimal_risky_port = port_ef_df.iloc[((port_ef_df['Returns']-rf)/port_ef_df['Volatility']).idxmax()]
84
 
85
+
86
+ ## CREATE CAPM LINE #https://www.youtube.com/watch?v=JWx2wcrSGkk
87
+ cal_x = []
88
+ cal_y = []
89
+ utl = []
90
+
91
+
92
+
93
+ for er in np.linspace(rf, max(data['Returns']),20):
94
+ sd = (er - rf)/ ((optimal_risky_port[0] - rf)/ optimal_risky_port[1])
95
+ u = er - 0.5*a*(sd**2)
96
+ cal_x.append(sd)
97
+ cal_y.append(er)
98
+ utl.append(u)
99
+
100
+ data2 = {'Utility':utl, 'cal_x':cal_x, 'cal_y':cal_y}
101
+
102
+ utl_df = pd.DataFrame(data2)
103
 
104
  ## Create Figure
105
 
 
117
 
118
  ])
119
  )
120
+
121
+ fig1 = px.line(utl_df, x="cal_x", y="cal_y")
122
+ fig1.update_traces(line=dict(color = 'rgba(11,156,49,1)'))
123
  #https://stackoverflow.com/questions/59057881/python-plotly-how-to-customize-hover-template-on-with-what-information-to-show
124
+ #https://stackoverflow.com/questions/65124833/plotly-how-to-combine-scatter-and-line-plots-using-plotly-express
125
+
126
+ fig3 = go.Figure(data=fig.data + fig1.data)
127
+
128
+ st.plotly_chart(fig3, use_container_width=True)
129
  #st.write(stock_df)