File size: 5,007 Bytes
9aaed9a fd36ba3 9aaed9a fd36ba3 9aaed9a fd36ba3 9aaed9a |
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 |
import pandas as pd
import numpy as np
from datetime import datetime
import streamlit as st
import matplotlib.pyplot as plt
import plotly.express as px
#import plotly.graph_objects as go
def preprocess(stocks,choices):
symbols, weights, investing_style, benchmark, rf, A_coef = choices.values()
stocks = stocks.pivot(index="Date", columns="Ticker", values="Adj. Close")
print('stocks',stocks)
logRet = np.log(stocks/stocks.shift())
log_returns = np.log(stocks/stocks.shift())
tickers_list = symbols.copy()
weights_list = weights.copy()
return logRet,tickers_list,weights_list
def cumulative_return(stocks,choices):
symbols, weights, investing_style, benchmark, rf, A_coef = choices.values()
logRet,tickers_list,weights_list = preprocess(stocks,choices)
tkers = sorted(set(stocks['Ticker'].unique()))
stocks = stocks.pivot(index="Date", columns="Ticker", values="Adj. Close")
stock_port = {}
for e in tickers_list: stock_port[e] = 0
# Convert Weights to Floats and Sum
weights = [float(x) for x in weights_list]
s = sum(weights)
# Calc Weight Proportions
new_weights = []
for i in weights: new_weights.append(i/s)
# Assign Weights to Ticker Dict
i = 0
for e in stock_port:
stock_port[e] = new_weights[i]
i += 1
port = dict.fromkeys(tkers, 0)
port.update(stock_port)
portfolio_dict = port
for e in portfolio_dict:
tmp = 0
if portfolio_dict[e] > tmp:
tmp = portfolio_dict[e]
tick = e
list_ =[]
for e in tickers_list:
if e not in list_:
list_.append(e)
df = stocks[list_]
df = df/df.iloc[0]
df.reset_index(inplace=True)
df=pd.DataFrame(df)
print(df)
fig = px.line(df, x='Date' ,y=df.columns[1:,])
#layout reference = https://linuxtut.com/en/b13e3e721519c2842cc9/
fig.update_layout(
xaxis=dict(
rangeselector=dict(
buttons=list([
dict(count=1,
label="1m",
step="month",
stepmode="backward"),
dict(count=6,
label="6m",
step="month",
stepmode="backward"),
dict(count=1,
label="YTD",
step="year",
stepmode="todate"),
dict(count=1,
label="1y",
step="year",
stepmode="backward"),
dict(step="all")
])
),
rangeslider=dict(
visible=True
),
type="date"
)
)
fig.update_layout(xaxis=dict(rangeselector = dict(font = dict( color = "black"))))
st.subheader('Portfolio Historical Normalized Cumulative Returns')
st.plotly_chart(fig, use_container_width=True)
def sharp_ratio_func(stocks,choices):
symbols, weights, investing_style, benchmark, rf, A_coef = choices.values()
logRet,tickers_list,weights_list = preprocess(stocks,choices)
tkers = sorted(set(stocks['Ticker'].unique()))
stocks = stocks.pivot(index="Date", columns="Ticker", values="Adj. Close")
stock_port = {}
for e in tickers_list: stock_port[e] = 0
# Convert Weights to Floats and Sum
weights = [float(x) for x in weights_list]
s = sum(weights)
# Calc Weight Proportions
new_weights = []
for i in weights: new_weights.append(i/s)
# Assign Weights to Ticker Dict
i = 0
for e in stock_port:
stock_port[e] = new_weights[i]
i += 1
port = dict.fromkeys(tkers, 0)
port.update(stock_port)
portfolio_dict = port
sharp_ratio_list = []
for ticker in symbols:
logRet = np.log(stocks/stocks.shift())
stk = dict.fromkeys(tkers, 0)
stkTicker = {ticker:1}
stk.update(stkTicker)
ttlStk = np.sum(logRet*stk, axis=1)
stock_sharpe_ratio = ttlStk.mean() / ttlStk.std()
sharp_ratio_list.append(stock_sharpe_ratio)
sharp_ratio = {'Assets': symbols, 'Sharpe Ratio': sharp_ratio_list}
# Portfolio sharp Ratio Calculation
logRet = np.log(stocks/stocks.shift())
portfolio = dict.fromkeys(tkers, 0)
portfolio.update(portfolio_dict)
totalPortfolio = np.sum(logRet*portfolio, axis=1)
portfolio_sharpe_ratio = totalPortfolio.mean() / totalPortfolio.std()
sharp_ratio['Assets'].append('Portfolio')
sharp_ratio['Sharpe Ratio'].append(portfolio_sharpe_ratio)
fig = px.bar(sharp_ratio, x='Assets', y="Sharpe Ratio",color='Assets')
fig.update_layout(title_text = 'Sharpe Ratio of the Assets and Portfolio',
title_x=0.458)
st.plotly_chart(fig, use_container_width=True)
|