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 def beta(stock_df, choices): symbols, weights, investment = choices.values() tickers = symbols tickers.append('sp500') #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 != 'sp500': # stocks_daily_return.plot(kind = 'scatter', x = 'A', y = i) b, a = np.polyfit(stocks_daily_return['sp500'], 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('sp500') 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, investment = choices.values() symbols_ =symbols tickers = symbols tickers.append('sp500') #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 != 'sp500': # stocks_daily_return.plot(kind = 'scatter', x = 'A', y = i) b, a = np.polyfit(stocks_daily_return['sp500'], 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['sp500'].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('sp500') 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('aaa',ER_portfolio) st.subheader('Expected Portfolio Return Based on CAPM Model') # Creates a header for streamlit st.write('Expected Portfolio Return is:', ER_portfolio) 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() # Creates the title for streamlit st.subheader('Portfolio Historical Normalized Cumulative Returns') # Graphs the cumulative returns st.line_chart(cumulative_return) def display_heat_map(stock_df): """Uses the stock dataframe to calculate the correlations between the different assets and display them as a heatmap. """ # Calcuilates the correlation of the assets in the portfolio price_correlation = stock_df.corr() # Creates the title for streamlit st.subheader('Heatmap Showing Correlation Of Assets') # Generates a figure for the heatmap fig, ax = plt.subplots() sns.heatmap(price_correlation, ax=ax) # Displays the heatmap on streamlit st.write(fig) # Creates a header for the correlation data st.subheader('Correlation Data') # Displays the correlation data on streamlit st.dataframe(price_correlation) #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): import plotly.express as px symbols, weights, investment = choices.values() beta,cash_value_weights = ER(stock_df,choices) my_list = [] for i in beta.values(): my_list.append(i) df_final =pd.DataFrame() df_final['ticker'] = symbols df_final['quantities'] = weights df_final['cash_value'] =cash_value_weights df_final['Beta'] = my_list fig = px.scatter( df_final, x="quantities", y="Beta", size="cash_value", #color="continent", 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)