swapnilbotu commited on
Commit
b1de1a4
·
verified ·
1 Parent(s): bd7d4be

Uploaded all required files

Browse files
Files changed (3) hide show
  1. app.py +113 -0
  2. capm_functions.py +37 -0
  3. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #importing libraries
2
+ import streamlit as st
3
+ import pandas as pd
4
+ import yfinance as yf
5
+ import pandas_datareader.data as web
6
+ import datetime
7
+
8
+ import capm_functions
9
+
10
+ #Streamlit page configuration
11
+ st.set_page_config(page_title="CAPM",
12
+ page_icon="chart_with_upwards_trend",
13
+ layout='wide')
14
+
15
+ st.title("Capital Asset Pricing Model")
16
+
17
+ # getting input from user
18
+ try:
19
+ col1, col2 =st.columns([1,1])
20
+ with col1:
21
+ stocks_list = st.multiselect("Choose 4 stocks", ('TSLA','AAPL','NFLX','MSFT','MGM','AMZN','NVDA','GOOGL'),('TSLA','AAPL','AMZN','GOOGL'))
22
+
23
+ with col2:
24
+ year=st.number_input("Numbers of years",1,10)
25
+
26
+ #downloading data for SP500
27
+
28
+ end = datetime.date.today()
29
+ start = datetime.date(datetime.date.today().year-year, datetime.date.today().month, datetime.date.today().day)
30
+
31
+ SP500 = web.DataReader(['sp500'], 'fred',start,end)
32
+
33
+ stocks_df = pd.DataFrame()
34
+
35
+ for stock in stocks_list:
36
+ data = yf.download(stock, period=f'{year}y')
37
+ stocks_df[f'{stock}'] = data['Close']
38
+
39
+
40
+ stocks_df.reset_index(inplace=True)
41
+ SP500.reset_index(inplace=True)
42
+ SP500.columns = ['Date','SP500']
43
+ stocks_df['Date'] = stocks_df['Date'].astype('datetime64[ns]')
44
+ stocks_df['Date'] = stocks_df['Date'].apply(lambda x:str(x)[:10])
45
+ stocks_df['Date'] = pd.to_datetime(stocks_df['Date'])
46
+ stocks_df = pd.merge(stocks_df, SP500, on='Date', how='inner')
47
+
48
+ col1, col2 = st.columns([1,1])
49
+ with col1:
50
+ st.markdown('### Dataframe head')
51
+ st.dataframe(stocks_df.head(), use_container_width=True)
52
+
53
+ with col2:
54
+ st.markdown('### Dataframe tail')
55
+ st.dataframe(stocks_df.tail(), use_container_width=True)
56
+
57
+
58
+ col1, col2 = st.columns([1,1])
59
+ with col1:
60
+ st.markdown('### Price of all the Stocks')
61
+ st.plotly_chart(capm_functions.interactive_plot(stocks_df))
62
+
63
+
64
+ with col2:
65
+
66
+ st.markdown('### Price of all the Stocks After Normalization')
67
+ st.plotly_chart(capm_functions.interactive_plot(capm_functions.normalize(stocks_df)))
68
+
69
+ stocks_daily_returns = capm_functions.daily_return(stocks_df)
70
+ #print(stocks_daily_returns.head())
71
+
72
+ beta = {}
73
+ alpha = {}
74
+
75
+ for i in stocks_daily_returns.columns:
76
+ if i !='Date' and i !='SP500':
77
+ b,a = capm_functions.calculate_beta(stocks_daily_returns,i)
78
+
79
+ beta[i]=b
80
+ alpha[i]=a
81
+ print(beta, alpha)
82
+
83
+ beta_df = pd.DataFrame(columns=['stock','Beta Value'])
84
+ beta_df['Stock'] = beta.keys()
85
+ beta_df['Beta value'] = [str(round(i,2)) for i in beta.values()]
86
+
87
+
88
+ with col1:
89
+ st.markdown('### Calculated Beta Value')
90
+ st.dataframe(beta_df, use_container_width=True)
91
+
92
+
93
+ rf = 0
94
+ rm = stocks_daily_returns['SP500'].mean()*252
95
+
96
+ return_df = pd.DataFrame()
97
+ return_value = []
98
+ for stock, value in beta.items():
99
+ return_value.append(str(round(rf+(value*(rf-rm)),2)))
100
+ return_df['Stock'] = stocks_list
101
+
102
+ return_df['Return value'] = return_value
103
+
104
+ with col2:
105
+ st.markdown('### Calculated Return using CAPM')
106
+
107
+ st.dataframe(return_df, use_container_width=True)
108
+ except:
109
+ st.write('Please select valid Input')
110
+
111
+
112
+
113
+
capm_functions.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import plotly.express as px
2
+ import numpy as np
3
+
4
+
5
+ #function to plot interactive plotely chart
6
+ def interactive_plot(df):
7
+ fig = px.line()
8
+ for i in df.columns[1:]:
9
+ fig.add_scatter(x = df['Date'],y=df[i], name=i)
10
+ fig.update_layout(width=450, margin=dict(l=20,r=20,t=50,b=20),legend=dict(orientation = 'h', yanchor = 'bottom',y=1.02, xanchor='right',x=1,))
11
+ return fig
12
+
13
+
14
+ #function to normalize the prices based on the initial price
15
+ def normalize(df_2):
16
+ df = df_2.copy()
17
+ for i in df.columns[1:]:
18
+ df[i] = df[i]/df[i][0]
19
+ return df
20
+
21
+
22
+ #functions to calculate daily returns
23
+ def daily_return(df):
24
+ df_daily_return = df.copy()
25
+ for i in df.columns[1:]:
26
+ for j in range(1,len(df)):
27
+ df_daily_return[i][j] = ((df[i][j]-df[i][j-1]/df[i][j-1])*100)
28
+ df_daily_return[i][0] = 0
29
+ return df_daily_return
30
+
31
+
32
+ #functions to calculate beta
33
+ def calculate_beta(stocks_daily_return, stock):
34
+ rm = stocks_daily_return['SP500'].mean()*252
35
+
36
+ b, a = np.polyfit(stocks_daily_return['SP500'], stocks_daily_return[stock],1)
37
+ return b,a
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ yfinance
4
+ pandas_datareader
5
+ datetime
6
+ plotly-express