-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
204 lines (164 loc) Β· 8.32 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import streamlit as st
import pandas as pd
import yfinance as yf
import datetime
import capm_functions
st.set_page_config(page_title="CAPM Analysis", page_icon="π", layout='wide')
# Custom CSS for styling
st.markdown(
"""
<style>
.main-header {
font-size: 32px;
font-weight: bold;
color: #4B6CB7;
text-align: center;
margin-bottom: 30px;
}
.sidebar .sidebar-content {
background-color: #f0f2f6;
}
</style>
""",
unsafe_allow_html=True
)
st.markdown('<h1 class="main-header">Capital Asset Pricing Model (CAPM)</h1>', unsafe_allow_html=True)
st.sidebar.markdown("## Navigation")
st.sidebar.markdown("Choose the page according to the feature need:")
page = st.sidebar.radio("Select Page", ["π CAPM Analysis", "π Stock Comparison"])
benchmarks = {
'Nifty 50': '^NSEI',
'NASDAQ 100': '^NDX'
}
nifty50_stocks = [
'ADANIPORTS.NS', 'ASIANPAINT.NS', 'AXISBANK.NS', 'BAJAJ-AUTO.NS', 'BAJAJFINSV.NS',
'BAJFINANCE.NS', 'BHARTIARTL.NS', 'BPCL.NS', 'BRITANNIA.NS', 'CIPLA.NS',
'COALINDIA.NS', 'DIVISLAB.NS', 'DRREDDY.NS', 'EICHERMOT.NS', 'GRASIM.NS',
'HCLTECH.NS', 'HDFC.NS', 'HDFCBANK.NS', 'HDFCLIFE.NS', 'HEROMOTOCO.NS',
'HINDALCO.NS', 'HINDUNILVR.NS', 'ICICIBANK.NS', 'INDUSINDBK.NS', 'INFY.NS',
'ITC.NS', 'JSWSTEEL.NS', 'KOTAKBANK.NS', 'LT.NS', 'M&M.NS',
'MARUTI.NS', 'NESTLEIND.NS', 'NTPC.NS', 'ONGC.NS', 'POWERGRID.NS',
'RELIANCE.NS', 'SBILIFE.NS', 'SBIN.NS', 'SUNPHARMA.NS', 'TATAMOTORS.NS',
'TATASTEEL.NS', 'TCS.NS', 'TECHM.NS', 'TITAN.NS', 'ULTRACEMCO.NS',
'UPL.NS', 'WIPRO.NS'
]
nasdaq100_stocks = [
'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'NVDA', 'META', 'TSLA', 'BRK-B', 'UNH', 'V',
'MA', 'HD', 'DIS', 'ADBE', 'CMCSA', 'NFLX', 'INTC', 'CSCO', 'PFE', 'MRK',
'PEP', 'AVGO', 'TXN', 'QCOM', 'ABT', 'TMO', 'CRM', 'ORCL', 'COST', 'NKE',
'MCD', 'AMGN', 'MDT', 'HON', 'BMY', 'C', 'BAX', 'BA', 'GILD', 'MS',
'CVX', 'WMT', 'WBA', 'MCO', 'CAT', 'DHR', 'LMT', 'IBM', 'UPS', 'COP',
'AMT', 'LRCX', 'LLY', 'CL', 'SBUX', 'T', 'MDLZ', 'EOG', 'MCK', 'SNY',
'WFC', 'FIS', 'MO', 'CME', 'GS', 'ADP', 'IACI', 'BMY', 'AON', 'KMB',
'PSA', 'ISRG', 'MCHP', 'HPE', 'MU', 'LUV', 'MSCI', 'CSX', 'XOM', 'TRV'
]
if page == "π CAPM Analysis":
col1, col2 = st.columns([1, 1])
with col1:
benchmark = st.selectbox("Select Benchmark", options=list(benchmarks.keys()))
with col2:
stocks_list = st.multiselect("Choose stocks", nifty50_stocks if benchmark == 'Nifty 50' else nasdaq100_stocks)
year = st.slider("Number of Years", 1, 15, 5)
if not stocks_list or year == 0:
st.warning("Please select at least one stock and a valid number of years.")
st.markdown(
'''
<div style="text-align: center;">
<h2> For stock comparison select the next page from sidebar! </h2>
</div>
''',
unsafe_allow_html=True
)
else:
try:
end = datetime.date.today()
start = datetime.date(end.year - year, end.month, end.day)
with st.spinner("Fetching data..."):
benchmark_symbol = benchmarks[benchmark]
benchmark_data = yf.download(benchmark_symbol, start=start, end=end)
benchmark_data = benchmark_data[['Close']].rename(columns={'Close': benchmark})
stocks_df = pd.DataFrame()
for stock in stocks_list:
data = yf.download(stock, start=start, end=end)
stocks_df[stock] = data['Close']
stocks_df.reset_index(inplace=True)
benchmark_data.reset_index(inplace=True)
stocks_df = pd.merge(stocks_df, benchmark_data[['Date', benchmark]], on='Date', how='inner')
st.markdown("### Stock Prices Overview")
col1, col2 = st.columns([1, 1])
with col1:
st.dataframe(stocks_df.head(), use_container_width=True)
with col2:
st.dataframe(stocks_df.tail(), use_container_width=True)
col1, col2 = st.columns([1, 1])
with col1:
st.markdown("### Stock Price Movements")
st.plotly_chart(capm_functions.interactive_plot(stocks_df), use_container_width=True)
with col2:
normalized_df = capm_functions.normalize(stocks_df)
st.markdown("### Normalized Stock Prices")
st.plotly_chart(capm_functions.interactive_plot(normalized_df), use_container_width=True)
# Calculating beta values for CAPM calculations
stock_daily_return = capm_functions.daily_returns(stocks_df)
beta = {}
alpha = {}
for stock in stocks_list:
b, a = capm_functions.calc(stock_daily_return, stock, benchmark)
beta[stock] = b
alpha[stock] = a
col1, col2 = st.columns([1, 1])
with col1:
st.markdown("### Beta Values")
beta_df = pd.DataFrame({'Stock': beta.keys(), 'Beta Value': [round(b, 2) for b in beta.values()]})
st.dataframe(beta_df, use_container_width=True)
with col2:
st.markdown("### Expected Return using CAPM")
rf = 0
rm = stock_daily_return[benchmark].mean() * 252
return_values = [round(rf + beta[stock] * (rm - rf), 2) for stock in stocks_list]
return_df = pd.DataFrame({'Stock': stocks_list, 'Expected Return (CAPM)': return_values})
st.dataframe(return_df, use_container_width=True)
st.markdown("""
## What is CAPM?
The Capital Asset Pricing Model (CAPM) is a financial model that calculates the expected return of an investment based on its risk in relation to the market.
It uses beta to measure an asset's volatility compared to the market, helping investors assess the potential risk and return of their investments.
Formula used to calculate CAPM is :- Ra = Rf + Ξ²(Rm - Rf)
where:
Rf = The return on a risk-free investment, such as government bonds.
Rm = The expected return of the overall market.
""")
except Exception as e:
st.error(f"An error occurred: {e}")
elif page == "π Stock Comparison":
col1, col2 = st.columns([1, 1])
with col1:
stock1 = st.selectbox("Select First Stock", options=nifty50_stocks + nasdaq100_stocks)
with col2:
stock2 = st.selectbox("Select Second Stock", options=nifty50_stocks + nasdaq100_stocks)
year = st.slider("Number of Years for Comparison", 1, 15, 5)
if stock1 and stock2 and year > 0:
try:
end = datetime.date.today()
start = datetime.date(end.year - year, end.month, end.day)
with st.spinner("Fetching stock data..."):
data1 = yf.download(stock1, start=start, end=end)
data2 = yf.download(stock2, start=start, end=end)
df1 = data1[['Close']].rename(columns={'Close': stock1})
df2 = data2[['Close']].rename(columns={'Close': stock2})
df1.reset_index(inplace=True)
df2.reset_index(inplace=True)
comparison_df = pd.merge(df1, df2, on='Date', how='inner')
comparison_df[f'{stock1} Return (%)'] = (comparison_df[stock1] / comparison_df[stock1].iloc[0] - 1) * 100
comparison_df[f'{stock2} Return (%)'] = (comparison_df[stock2] / comparison_df[stock2].iloc[0] - 1) * 100
st.markdown("### Cumulative Return Comparison (%)")
st.line_chart(comparison_df[['Date', f'{stock1} Return (%)', f'{stock2} Return (%)']].set_index('Date'))
st.markdown("### Stock Prices")
st.line_chart(comparison_df[['Date', stock1, stock2]].set_index('Date'))
final_returns = comparison_df[['Date', f'{stock1} Return (%)', f'{stock2} Return (%)']].iloc[-1]
st.markdown(f"### Final Cumulative Returns Over {year} Years")
st.write(f"{stock1} Return: {final_returns[f'{stock1} Return (%)']:.2f}%")
st.write(f"{stock2} Return: {final_returns[f'{stock2} Return (%)']:.2f}%")
except Exception as e:
st.error(f"An error occurred: {e}")
else:
st.warning("Please select two different stocks and a valid number of years.")