cse6242-dataminers / plots.py
Lirsen Myrtaj
Del 2 write functions (#42)
208a029
raw
history blame
8.28 kB
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)