Using Python and streamlit, code a web app that can conduct peer analysis for hedge funds.
- User
Using Python and streamlit, code a web app that can conduct peer analysis for hedge funds.
Assistant
Using Python and streamlit, code a web app that can conduct peer analysis for hedge funds.
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
import yfinance as yf
import plotly.express as px
import plotly.graph_objects as go
# App title and description
st.title("Hedge Fund Peer Analysis Tool")
st.markdown("Compare performance, risk metrics, and characteristics across peer hedge funds")
# Sidebar for inputs
st.sidebar.header("Analysis Parameters")
# Sample hedge funds for demo purposes
sample_hedge_funds = [
"Renaissance Technologies", "Bridgewater Associates", "Man Group",
"AQR Capital", "Two Sigma", "Citadel", "Elliott Management",
"DE Shaw", "Millennium Management", "Point72"
]
# Data input method
data_input = st.sidebar.radio("Select Data Source",
["Sample Data", "Upload Custom Data"])
selected_funds = []
if data_input == "Sample Data":
selected_funds = st.sidebar.multiselect("Select Hedge Funds to Compare",
sample_hedge_funds,
default=sample_hedge_funds[:4])
else:
uploaded_file = st.sidebar.file_uploader("Upload hedge fund data (CSV)", type="csv")
if uploaded_file is not None:
fund_data = pd.read_csv(uploaded_file)
st.sidebar.success("Data uploaded successfully!")
if 'Fund Name' in fund_data.columns:
selected_funds = st.sidebar.multiselect("Select Funds to Compare",
fund_data['Fund Name'].unique())
# Date range selector
date_range = st.sidebar.selectbox(
"Select Time Period",
["1 Year", "3 Years", "5 Years", "10 Years", "YTD", "Custom"]
)
if date_range == "Custom":
col1, col2 = st.sidebar.columns(2)
start_date = col1.date_input("Start Date", datetime.now() - timedelta(days=365))
end_date = col2.date_input("End Date", datetime.now())
else:
end_date = datetime.now()
if date_range == "1 Year":
start_date = end_date - timedelta(days=365)
elif date_range == "3 Years":
start_date = end_date - timedelta(days=365*3)
elif date_range == "5 Years":
start_date = end_date - timedelta(days=365*5)
elif date_range == "10 Years":
start_date = end_date - timedelta(days=365*10)
elif date_range == "YTD":
start_date = datetime(end_date.year, 1, 1)
# Filter criteria
st.sidebar.header("Filtering Criteria")
aum_range = st.sidebar.slider("AUM Range (billions $)", 0, 100, (5, 50))
strategy_types = st.sidebar.multiselect(
"Strategy Types",
["Quantitative", "Global Macro", "Long/Short Equity", "Event Driven",
"Multi-Strategy", "Relative Value", "Activist", "Credit"],
default=["Quantitative", "Global Macro", "Long/Short Equity"]
)
# Main app content
if not selected_funds:
st.warning("Please select funds to analyze")
else:
# Generate mock data for the selected funds
def generate_mock_data(funds, start_date, end_date):
# Create date range
date_rng = pd.date_range(start=start_date, end=end_date, freq='M')
data = pd.DataFrame(date_rng, columns=['Date'])
# Create benchmark (S&P 500-like returns)
np.random.seed(42)
benchmark = np.random.normal(0.008, 0.04, len(date_rng))
data['Benchmark'] = benchmark.cumsum()
# Create fund returns with some correlation to benchmark
for fund in funds:
# Random characteristics
correlation = np.random.uniform(0.3, 0.9)
alpha = np.random.uniform(-0.002, 0.006)
vol = np.random.uniform(0.03, 0.08)
# Generate returns
fund_returns = alpha + correlation * benchmark + np.random.normal(0, vol, len(date_rng))
data[fund] = fund_returns.cumsum()
return data
# Mock fund characteristics
def generate_fund_characteristics(funds):
data = []
np.random.seed(42)
strategies = ["Quantitative", "Global Macro", "Long/Short Equity", "Event Driven",
"Multi-Strategy", "Relative Value", "Activist", "Credit"]
for fund in funds:
aum = np.random.uniform(1, 100)
mgmt_fee = np.random.uniform(1.0, 2.5)
perf_fee = np.random.choice([15, 20, 25, 30])
sharpe = np.random.uniform(0.5, 2.5)
volatility = np.random.uniform(3, 25)
max_dd = np.random.uniform(5, 40)
strategy = np.random.choice(strategies)
data.append({
'Fund': fund,
'AUM ($B)': round(aum, 1),
'Mgmt Fee (%)': round(mgmt_fee, 2),
'Perf Fee (%)': perf_fee,
'Sharpe Ratio': round(sharpe, 2),
'Volatility (%)': round(volatility, 1),
'Max Drawdown (%)': round(max_dd, 1),
'Strategy': strategy
})
return pd.DataFrame(data)
# Generate mock return data
returns_data = generate_mock_data(selected_funds, start_date, end_date)
# Generate fund characteristics
fund_chars = generate_fund_characteristics(selected_funds)
# Filter funds based on criteria
filtered_chars = fund_chars[
(fund_chars['AUM ($B)'] >= aum_range[0]) &
(fund_chars['AUM ($B)'] <= aum_range[1]) &
(fund_chars['Strategy'].isin(strategy_types))
]
filtered_funds = filtered_chars['Fund'].tolist()
# Analysis tabs
tab1, tab2, tab3, tab4 = st.tabs(["Performance", "Risk Metrics", "Characteristics", "Correlation"])
with tab1:
st.header("Performance Comparison")
# Cumulative returns chart
cum_returns = returns_data.copy()
cum_returns = cum_returns.set_index('Date')
# Convert to percentage for display
for col in cum_returns.columns:
cum_returns[col] = (1 + cum_returns[col]).cumprod() - 1
# Plot using Plotly
fig = px.line(cum_returns, x=cum_returns.index, y=cum_returns.columns,
title="Cumulative Returns", labels={"value": "Return (%)", "variable": "Fund"})
fig.update_layout(yaxis_tickformat='.0%')
st.plotly_chart(fig)
# Annual returns table
st.subheader("Annual Returns (%)")
annual_returns = pd.DataFrame({
'Fund': filtered_funds,
'2019': np.random.uniform(-10, 30, len(filtered_funds)),
'2020': np.random.uniform(-10, 30, len(filtered_funds)),
'2021': np.random.uniform(-10, 30, len(filtered_funds)),
'2022': np.random.uniform(-10, 30, len(filtered_funds)),
'2023': np.random.uniform(-10, 30, len(filtered_funds)),
'2024 YTD': np.random.uniform(-10, 30, len(filtered_funds)),
}).set_index('Fund')
st.dataframe(annual_returns.style.format("{:.2f}%"))
with tab2:
st.header("Risk Metrics")
# Risk-return scatter plot
fig = px.scatter(filtered_chars, x='Volatility (%)', y='Sharpe Ratio',
size='AUM ($B)', color='Strategy', hover_name='Fund',
title="Risk-Return Profile")
st.plotly_chart(fig)
# Drawdown chart
drawdown_data = pd.DataFrame({
'Fund': filtered_funds,
'Max Drawdown (%)': filtered_chars['Max Drawdown (%)'],
'Recovery Time (Months)': np.random.randint(3, 24, len(filtered_funds))
})
fig = px.bar(drawdown_data, x='Fund', y='Max Drawdown (%)',
color='Recovery Time (Months)',
title="Maximum Drawdown and Recovery Time",
labels={"Max Drawdown (%)": "Max Drawdown (%)"})
fig.update_layout(yaxis_tickformat='.1f')
st.plotly_chart(fig)
with tab3:
st.header("Fund Characteristics")
# Show the characteristics table
st.dataframe(filtered_chars.set_index('Fund'))
# Fee comparison
fee_data = filtered_chars[['Fund', 'Mgmt Fee (%)', 'Perf Fee (%)']]
fee_data_melted = pd.melt(fee_data, id_vars=['Fund'],
value_vars=['Mgmt Fee (%)', 'Perf Fee (%)'],
var_name='Fee Type', value_name='Fee')
fig = px.bar(fee_data_melted, x='Fund', y='Fee', color='Fee Type',
barmode='group', title="Fee Structure Comparison")
st.plotly_chart(fig)
# AUM comparison
fig = px.pie(filtered_chars, values='AUM ($B)', names='Fund',
title="AUM Breakdown")
st.plotly_chart(fig)
with tab4:
st.header("Correlation Analysis")
# Generate correlation matrix from returns
returns_only = returns_data.drop('Date', axis=1)
corr_matrix = returns_only.corr()
# Plot correlation heatmap
fig = px.imshow(corr_matrix,
labels=dict(x="Fund", y="Fund", color="Correlation"),
x=corr_matrix.columns, y=corr_matrix.columns,
title="Return Correlation Matrix")
fig.update_layout(height=500, width=700)
st.plotly_chart(fig)
# Factor exposure
st.subheader("Factor Exposures")
factors = ['Market', 'Size', 'Value', 'Momentum', 'Volatility']
# Generate random factor exposures
factor_data = pd.DataFrame({
'Fund': filtered_funds,
})
for factor in factors:
factor_data[factor] = np.random.uniform(-0.5, 1.2, len(filtered_funds))
factor_melted = pd.melt(factor_data, id_vars=['Fund'],
value_vars=factors,
var_name='Factor', value_name='Exposure')
fig = px.bar(factor_melted, x='Fund', y='Exposure', color='Factor',
barmode='group', title="Factor Exposures")
st.plotly_chart(fig)
# Footer with disclaimer
st.markdown("---")
st.caption("Disclaimer: This tool uses simulated data for demonstration purposes. Real hedge fund analysis would require proprietary data sources.")
Would you like me to explain or break down this code?