File size: 8,276 Bytes
f2bfb78
 
 
 
 
 
f9c3c03
 
f2bfb78
 
fc101f7
f2bfb78
fc101f7
f2bfb78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc101f7
f2bfb78
fc101f7
f2bfb78
 
 
 
 
fc101f7
f2bfb78
 
 
 
 
 
 
 
 
 
 
 
 
9004315
5b5632a
f2bfb78
fc101f7
f2bfb78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc101f7
f2bfb78
fc101f7
f2bfb78
 
 
 
 
 
 
 
 
 
 
fc101f7
f2bfb78
 
 
 
 
 
fc101f7
5b5632a
f2bfb78
5b5632a
f2bfb78
5b5632a
f2bfb78
 
 
 
 
 
 
f2ecd11
f2bfb78
 
 
 
 
f2ecd11
f2bfb78
 
 
 
 
 
5b5632a
f2bfb78
5b5632a
f2bfb78
5b5632a
 
 
 
 
392668a
 
5b5632a
 
 
f2bfb78
 
 
 
 
 
 
 
 
208a029
f2bfb78
 
 
 
5b5632a
9004315
5b5632a
f2bfb78
5b5632a
f2bfb78
208a029
f2bfb78
 
5b5632a
f2bfb78
 
392668a
f2bfb78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b5103
fe1b531
e1b5103
 
fc101f7
e1b5103
 
fc101f7
 
 
 
 
 
e1b5103
 
 
 
 
 
fc101f7
e1b5103
 
 
 
 
 
fc101f7
e1b5103
 
 
 
 
 
 
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import pandas as pd
import seaborn as sns
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
import altair as alt
import plotly.express as px


def beta(stock_df, choices):
    symbols, weights, benchmark, investing_style, rf, A_coef  = choices.values()
    tickers = symbols
    tickers.append(benchmark)
    #print(tickers)
    quantity = weights
    selected_stocks = stock_df[tickers]
    # calculating daily return
    # loops through each stocks
    # loops through each row belonging to the stock
    # calculates the percentage change from previous day
    # sets the value of first row to zero since there is no previous value
    df_stocks = selected_stocks.copy()

    for i in selected_stocks.columns[1:]:
        for j in range(1, len(selected_stocks)):
            df_stocks[i][j] = ((selected_stocks[i][j] - selected_stocks[i][j - 1]) / selected_stocks[i][j - 1]) * 100
        df_stocks[i][0] = 0
    # calculate Beta and alpha for a single stock
    # used sp500 as a benchmark
    # used polyfit to calculate beta
    beta_list = []
    alpha_list = []
    stocks_daily_return = df_stocks
    for i in stocks_daily_return.columns:
        if i != 'Date' and i != benchmark:
            # stocks_daily_return.plot(kind = 'scatter', x = 'A', y = i)
            b, a = np.polyfit(stocks_daily_return[benchmark], stocks_daily_return[i], 1)
            # plt.plot(stocks_daily_return['sp500'], b * stocks_daily_return['sp500'] + a, '-', color = 'r')
            beta_list.append(round(b, 2))
            alpha_list.append(round(a, 2))
            # plt.show()
    # Formats the results
    symbols.remove(benchmark)
    beta = {'Assets': symbols, 'Beta': beta_list}
    alpha = {'Assets': symbols, 'Alpha': alpha_list}
    # Creates a header for streamlit
    st.subheader('Beta and Alpha of Assets Compared to S&P500 index')
    col1, col2 = st.columns(2)

    with col1:
        st.dataframe(beta)
    with col2:
        st.dataframe(alpha)


def ER(stock_df, choices):
    symbols, weights, benchmark, investing_style, rf, A_coef  = choices.values()
    symbols_ =symbols.copy()
    tickers = symbols
    tickers.append(benchmark)
    #print(tickers)
    quantity = weights
    selected_stocks = stock_df[tickers]
    # calculating daily return
    # loops through each stocks
    # loops through each row belonging to the stock
    # calculates the percentage change from previous day
    # sets the value of first row to zero since there is no previous value
    df_stocks = selected_stocks.copy()

    for i in selected_stocks.columns[1:]:
        for j in range(1, len(selected_stocks)):
            df_stocks[i][j] = ((selected_stocks[i][j] - selected_stocks[i][j - 1]) / selected_stocks[i][j - 1]) * 100
        df_stocks[i][0] = 0
    beta = {}
    alpha = {}
    stocks_daily_return = df_stocks
    # print(df_stocks)

    for i in stocks_daily_return.columns:
        if i != 'Date' and i != benchmark:
            # stocks_daily_return.plot(kind = 'scatter', x = 'A', y = i)
            b, a = np.polyfit(stocks_daily_return[benchmark], stocks_daily_return[i], 1)
            # plt.plot(stocks_daily_return['sp500'], b * stocks_daily_return['sp500'] + a, '-', color = 'r')
            beta[i] = round(b, 2)
            alpha[i] = round(a, 2)
            # plt.show()

    # calculating camp for a stock
    keys = list(beta.keys())
    ER_ = []
    # rf = 0 assuming risk-free rate of 0
    rf = 0
    # rm - annualize retun
    rm = stocks_daily_return[benchmark].mean() * 252
    for i in keys:
        ER_.append( round(rf + (beta[i] * (rm - rf)), 2))

    #for i in keys:
    #    print('Expected Return based on CAPM for {} is {}%'.format(i, ER_[i]))
    #print(ER)
    symbols.remove(benchmark)
    #st.subheader('Expected Annual Return Based on CAPM Model')

    Expected_return = {'Assets': symbols_, 'Expected Annual Return': ER_}
    # Creates a header for streamlit
    #st.dataframe(Expected_return)

    
    # calculate expected return for the portfolio
    # portfolio weights assume equal
    portfolio_weights = []
    current_cash_value = 0
    total_portfolio_value = 0
    cash_value_stocks =[]
    for i in range(len(tickers) ):
        stocks_name = tickers[i]
        current_cash_value = selected_stocks[stocks_name].iloc[-1]
        stocks_quantity = quantity[i]
        cash_value = stocks_quantity * current_cash_value
        cash_value_stocks.append(cash_value)
        total_portfolio_value += cash_value
        portfolio_weights.append(cash_value)
    #print(portfolio_weights)
    portfolio_weights = (portfolio_weights / total_portfolio_value)*100
    ER_portfolio= []
    ER_portfolio = sum(list(ER_) * portfolio_weights)/100
    #print(ER_portfolio)

    #st.subheader('Expected Portfolio Return Based on CAPM Model')
    # Creates a header for streamlit
    #st.write('Expected Portfolio Return is:', ER_portfolio)
    Bar_output = Expected_return.copy()
    Bar_output['Assets'].append('Portfolio')
    Bar_output['Expected Annual Return'].append(ER_portfolio)
    fig = px.bar(Bar_output, x='Assets', y="Expected Annual Return",color='Assets') 
    #fig.update_layout(title_text = 'Annual Expected Return of the Assets and Portfolio',title_x=0.458)
    st.subheader('Annual Expected Return of the Assets and Portfolio')
    st.plotly_chart(fig, use_container_width=True)
    
    return beta, cash_value_stocks

def basic_portfolio(stock_df):
    """Uses the stock dataframe to graph the normalized historical cumulative returns of each asset.
    """
    # Calculates the daily returns of the inputted dataframe
    daily_return = stock_df.dropna().pct_change()
    # Calculates the cumulative return of the previously calculated daily return
    cumulative_return = (1 + daily_return).cumprod()

    
    # Graphs the cumulative returns
    st.line_chart(cumulative_return)


def display_heat_map(stock_df,choices):
    symbols, weights, benchmark, investing_style, rf, A_coef  = choices.values()
    selected_stocks = stock_df[symbols]
    # Calcuilates the correlation of the assets in the portfolio
    price_correlation = selected_stocks.corr()

    
    # Generates a figure for the heatmap
    fig, ax = plt.subplots()
    fig = px.imshow(price_correlation,text_auto=True, aspect="auto")
    # Displays the heatmap on streamlit
    st.write(fig)
   

#def display_portfolio_return(stock_df, choices):
    """Uses the stock dataframe and the chosen weights from choices to calculate and graph the historical cumulative portfolio return.
    """
#    symbols, weights, investment = choices.values()

    # Calculates the daily percentage returns of the 
#    daily_returns = stock_df.pct_change().dropna()
    # Applies the weights of each asset to the portfolio
#    portfolio_returns = daily_returns.dot(weights)
    # Calculates the cumulative weighted portfolio return
#    cumulative_returns = (1 + portfolio_returns).cumprod()
    # Calculates the cumulative profit using the cumulative portfolio return
#    cumulative_profit = investment * cumulative_returns

    # Graphs the result, and displays it with a header on streamlit
#    st.subheader('Portfolio Historical Cumulative Returns Based On Inputs!')
#    st.line_chart(cumulative_profit)
def buble_interactive(stock_df,choices):
    symbols, weights, benchmark, investing_style, rf, A_coef  = choices.values()
    beta,cash_value_weights  = ER(stock_df,choices)
    my_list = []
    my_colors = []
    for i in beta.values():
        my_list.append(i)
        if i < 0.3:
            my_colors.append("Conservative")
        if i >= 0.3 and i <= 1.1:
            my_colors.append("Moderate Risk")
        if i > 1.1:
            my_colors.append("Risky")
    
    df_final =pd.DataFrame()
    df_final['ticker'] = symbols
    df_final['quantities'] = weights
    df_final['cash_value']  =cash_value_weights
    df_final['Beta'] = my_list
    df_final['Risk'] = my_colors
   
    fig = px.scatter(
    df_final,
    x="quantities",
    y="Beta",
    size="cash_value",
    color="Risk",
    hover_name="ticker",
    log_x=True,
    size_max=60,
    )
    fig.update_layout(title="Beta ----write something")
    # -- Input the Plotly chart to the Streamlit interface
    st.plotly_chart(fig, use_container_width=True)