# Set the number input value to the existing allocation
alloc_input = st.number_input(
f"{ticker} Allocation (%)",
min_value=0.0,
max_value=100.0,
value=alloc, # Use existing allocation here
step=0.000001,
format="%.6f",
key=f"alloc_edit_{ticker}",
help=f"Set the allocation percentage for {ticker}. Must sum to 100% across all selected assets."
)
allocations_edit.append(alloc_input)
current_total_edit = sum(allocations_edit)
st.markdown(f"**Total Allocation:** {current_total_edit:.6f}%")
if not np.isclose(current_total_edit, 100.0, atol=1e-4):
st.warning(f"Allocations must sum to 100%. Currently sum to {current_total_edit:.6f}%. Please adjust the allocations.")
if current_total_edit > 0:
allocations_edit = [alloc / current_total_edit * 100 for alloc in allocations_edit]
else:
st.error("Total allocation is zero. Please set allocations for your assets.")
submitted_edit = st.form_submit_button("Save Changes")
if submitted_edit:
if not name_edit:
st.error("Please provide a portfolio name.")
elif name_edit != portfolio_to_edit['name'] and name_edit in [p['name'] for p in st.session_state.portfolios]:
st.error("Portfolio name already exists. Please choose a unique name.")
elif not selected_edit:
st.error("Please select at least one asset.")
elif not np.isclose(sum(allocations_edit), 100.0, atol=1e-4):
st.warning(f"Allocations must sum to 100%. Currently sum to {sum(allocations_edit):.6f}%. Adjusting allocations proportionally.")
allocations_edit = [alloc / current_total_edit * 100 for alloc in allocations_edit]
portfolio_to_edit.update({
'name': name_edit,
'start_date': pd.to_datetime(start_date_edit),
'end_date': pd.to_datetime(end_date_edit),
'rf_rate': rf_rate_edit,
'broker_fee': broker_fee_edit,
'benchmark_symbol': benchmark_symbol_edit,
'rebalance_freq': frequency_mapping.get(rebalance_freq_edit, 'M'),
'selected': selected_tickers_edit,
'allocations': allocations_edit
})
st.success(f"Portfolio '{name_edit}' updated successfully!")
st.markdown("**Updated Allocations:**")
allocations_summary = {ticker: f"{alloc:.6f}%" for ticker, alloc in zip(selected_tickers_edit, allocations_edit)}
st.json(allocations_summary)
st.session_state.edit_portfolio = None
st.markdown("---")
st.subheader("💡 Example Portfolios")
example_portfolios = [
{
'name': "Retirement Portfolio",
'start_date': pd.to_datetime(datetime.today() - timedelta(days=365*10)),
'end_date': pd.to_datetime(datetime.today()),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': '^GSPC',
'rebalance_freq': 'M',
'selected': ['AAPL', 'MSFT', 'GOOGL', 'JPM', 'XOM'],
'allocations': [20.0, 20.0, 20.0, 20.0, 20.0]
},
{
'name': "Tech-Heavy Portfolio",
'start_date': pd.to_datetime(datetime.today() - timedelta(days=365*5)),
'end_date': pd.to_datetime(datetime.today()),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': '^IXIC',
'rebalance_freq': 'M',
'selected': ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'META'],
'allocations': [25.0, 25.0, 20.0, 15.0, 15.0]
},
{
'name': "Balanced Risk-Return Portfolio",
'start_date': pd.to_datetime(datetime.today() - timedelta(days=365*7)),
'end_date': pd.to_datetime(datetime.today()),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': '^GSPC',
'rebalance_freq': 'M',
'selected': ['AAPL', 'JNJ', 'V', 'PG', 'XOM'],
'allocations': [20.0, 20.0, 20.0, 20.0, 20.0]
},
{
'name': "Income-Focused Portfolio",
'start_date': pd.to_datetime(datetime.today() - timedelta(days=365*7)),
'end_date': pd.to_datetime(datetime.today()),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': '^DJI',
'rebalance_freq': 'Q',
'selected': ['PG', 'KO', 'JNJ', 'T', 'PFE'],
'allocations': [20.0, 20.0, 20.0, 20.0, 20.0]
},
{
'name': "Growth-Oriented Portfolio",
'start_date': pd.to_datetime(datetime.today() - timedelta(days=365*3)),
'end_date': pd.to_datetime(datetime.today()),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': '^IXIC',
'rebalance_freq': 'M',
'selected': ['TSLA', 'NVDA', 'AMD', 'META', 'NFLX'],
'allocations': [30.0, 25.0, 20.0, 15.0, 10.0]
},
{
'name': "Value Portfolio",
'start_date': pd.to_datetime(datetime.today() - timedelta(days=365*10)),
'end_date': pd.to_datetime(datetime.today()),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': '^DJI',
'rebalance_freq': 'Q',
'selected': ['KO', 'PFE', 'XOM', 'WMT', 'CVX'],
'allocations': [20.0, 20.0, 20.0, 20.0, 20.0]
},
{
'name': "Conservative Portfolio",
'start_date': pd.to_datetime(datetime.today() - timedelta(days=365*5)),
'end_date': pd.to_datetime(datetime.today()),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': '^GSPC',
'rebalance_freq': 'Q',
'selected': ['JNJ', 'PG', 'KO', 'PEP', 'WMT'],
'allocations': [20.0, 20.0, 20.0, 20.0, 20.0]
},
{
'name': "Dividend-Focused Portfolio",
'start_date': pd.to_datetime(datetime.today() - timedelta(days=365*7)),
'end_date': pd.to_datetime(datetime.today()),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': 'DVY', # Dividend Index
'rebalance_freq': 'Q',
'selected': ['T', 'VZ', 'PFE', 'KO', 'IBM'],
'allocations': [20.0, 20.0, 20.0, 20.0, 20.0]
},
{
'name': "Global Diversification Portfolio",
'start_date': pd.to_datetime(datetime.today() - timedelta(days=365*5)),
'end_date': pd.to_datetime(datetime.today()),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': 'ACWI', # All Country World Index
'rebalance_freq': 'M',
'selected': ['AAPL', 'TSM', 'BABA', 'SAP', 'UL'],
'allocations': [20.0, 20.0, 20.0, 20.0, 20.0]
},
{
'name': "High-Risk Growth Portfolio",
'start_date': pd.to_datetime(datetime.today() - timedelta(days=365*3)),
'end_date': pd.to_datetime(datetime.today()),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': '^IXIC',
'rebalance_freq': 'M',
'selected': ['TSLA', 'ARKK', 'NVDA', 'SHOP', 'CRWD'],
'allocations': [30.0, 20.0, 20.0, 15.0, 15.0]
},
{
'name': "Emerging Markets Portfolio",
'start_date': pd.to_datetime(datetime.today() - timedelta(days=365*5)),
'end_date': pd.to_datetime(datetime.today()),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': 'EEM', # Emerging Markets Index
'rebalance_freq': 'M',
'selected': ['BABA', 'TSM', 'PDD', 'INFY', 'VALE'],
'allocations': [25.0, 25.0, 20.0, 15.0, 15.0]
}
]
for example in example_portfolios:
with st.expander(example['name']):
# Display portfolio details in a table
df_example = pd.DataFrame({
'Attribute': ['Start Date', 'End Date', 'Risk-Free Rate (%)', 'Broker Fee (%)', 'Benchmark Symbol', 'Rebalance Frequency', 'Selected Assets', 'Allocations (%)'],
'Value': [
example['start_date'].strftime('%Y-%m-%d'),
example['end_date'].strftime('%Y-%m-%d'),
f"{example['rf_rate']*100:.2f}",
f"{example['broker_fee']*100:.6f}",
example['benchmark_symbol'],
example['rebalance_freq'],
", ".join(example['selected']),
", ".join([f"{alloc:.2f}" for alloc in example['allocations']])
]
})
st.table(df_example)
if st.button(f"Load {example['name']}", key=f"load_{example['name']}"):
if example['name'] in [p['name'] for p in st.session_state.portfolios]:
st.warning(f"Portfolio '{example['name']}' already exists.")
else:
st.session_state.portfolios.append(example.copy())
st.success(f"Portfolio '{example['name']}' loaded successfully!")
with col2:
st.subheader("➕ Add New Portfolio")
with st.form("add_portfolio_form"):
st.markdown("### 🔧 Configure Details")
name = st.text_input("Portfolio Name", "", help="Enter a unique name for your portfolio.")
start_date = st.date_input(
"Start Date:",
datetime.today() - timedelta(days=365 * 15),
min_value=datetime(1900, 1, 1),
help="Choose the start date for backtesting."
)
end_date = st.date_input(
"End Date:",
datetime.today(),
min_value=datetime(1900, 1, 1),
help="Choose the end date for backtesting."
)
rf_rate = st.number_input(
"Risk-Free Rate (%)",
0.0,
10.0,
st.session_state.default_config['rf_rate'] * 100,
help="Enter the risk-free rate as a percentage."
) / 100
broker_fee = st.number_input(
"Broker Fee (%)",
0.0,
10.0,
st.session_state.default_config['broker_fee'] * 100,
step=0.000001,
format="%.6f",
help="Enter the broker fee as a percentage per transaction."
) / 100
benchmark_symbol = st.text_input(
"Benchmark Symbol (e.g., ^GSPC)",
st.session_state.default_config['benchmark_symbol'],
help="Enter the ticker symbol for your benchmark index."
)
rebalance_freq = st.selectbox(
"Rebalance Frequency",
["Daily", "Weekly", "Monthly", "Quarterly", "Yearly"],
index=2,
help="Choose how often to rebalance the portfolio."
)
st.markdown("### 🛠️ Set Allocations")
ticker_df = get_tickers()
asset_options = ticker_df.apply(lambda row: format_asset_option(row['Ticker'], row['Company Name']), axis=1).tolist()
selected = st.multiselect(
"Select Assets:",
options=asset_options,
help="Choose the assets you want to include in your portfolio."
)
# After selecting assets, extract tickers
selected_tickers = [option.split(' - ')[0] for option in selected]
allocations = []
if selected_tickers:
for ticker in selected_tickers:
alloc = st.number_input(
f"{ticker} Allocation (%)",
min_value=0.0,
max_value=100.0,
value=0.0,
step=0.000001,
format="%.6f",
key=f"allocations_new_{ticker}",
help=f"Set the allocation percentage for {ticker}. The sum of all allocations must equal 100%."
)
allocations.append(alloc)
current_total = sum(allocations)
st.markdown(f"**Total Allocation:** {current_total:.6f}%")
if not np.isclose(current_total, 100.0, atol=1e-4):
st.warning(f"Allocations must sum to 100%. Currently sum to {current_total:.6f}%. Please adjust the allocations.")
submitted = st.form_submit_button("Add Portfolio")
if submitted:
if not name:
st.error("Please provide a portfolio name.")
elif name in [p['name'] for p in st.session_state.portfolios]:
st.error("Portfolio name already exists. Please choose a unique name.")
elif not selected:
st.error("Please select at least one asset.")
elif not np.isclose(sum(allocations), 100.0, atol=1e-4):
st.error(f"Allocations must sum to 100%. Currently sum to {sum(allocations):.6f}%.")
else:
new_portfolio = {
'name': name,
'start_date': pd.to_datetime(start_date),
'end_date': pd.to_datetime(end_date),
'rf_rate': rf_rate,
'broker_fee': broker_fee,
'benchmark_symbol': benchmark_symbol,
'rebalance_freq': frequency_mapping.get(rebalance_freq, 'M'),
'selected': selected_tickers,
'allocations': allocations
}
st.session_state.portfolios.append(new_portfolio)
st.success(f"Portfolio '{name}' added successfully!")
st.markdown("**Allocations:**")
allocations_summary = {ticker: f"{alloc}%" for ticker, alloc in zip(selected_tickers, allocations)}
st.json(allocations_summary)
# Debugging Information
with st.expander("🔍 Debug Information"):
st.write("Current Portfolios in Session State:")
st.write(st.session_state.portfolios)
import streamlit as st
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
# ----------------------------
# Helper Functions and Constants
# ----------------------------
def get_tickers():
"""Mock function to return a DataFrame of tickers and company names."""
data = {
'Ticker': ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'META', 'JNJ', 'V', 'PG', 'XOM', 'KO',
'TSLA', 'NVDA', 'AMD', 'SHOP', 'CRWD', 'BABA', 'TSM', 'PDD', 'INFY', 'VALE'],
'Company Name': [
'Apple Inc.', 'Microsoft Corporation', 'Alphabet Inc.', 'Amazon.com, Inc.',
'Meta Platforms, Inc.', 'Johnson & Johnson', 'Visa Inc.', 'Procter & Gamble Co.',
'Exxon Mobil Corporation', 'The Coca-Cola Company', 'Tesla, Inc.',
'NVIDIA Corporation', 'Advanced Micro Devices, Inc.', 'Shopify Inc.',
'CrowdStrike Holdings, Inc.', 'Alibaba Group Holding Limited',
'Taiwan Semiconductor Manufacturing Company', 'Pinduoduo Inc.',
'Infosys Limited', 'Vale S.A.'
]
}
return pd.DataFrame(data)
def get_company_name(tickers_df, ticker):
"""Retrieve company name given a ticker."""
company = tickers_df.loc[tickers_df['Ticker'] == ticker, 'Company Name']
return company.values[0] if not company.empty else 'Unknown'
def format_asset_option(ticker, company_name):
"""Format asset option for display."""
return f"{ticker} - {company_name}"
frequency_mapping = {
"Daily": "D",
"Weekly": "W",
"Monthly": "M",
"Quarterly": "Q",
"Yearly": "Y"
}
# ----------------------------
# Initialize Session State
# ----------------------------
def initialize_session():
"""Initialize session state variables."""
default_config = {
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': '^GSPC'
}
session_defaults = {
'portfolios': [],
'backtest_results': {},
'step': "Configure Portfolio",
'edit_portfolio': None,
'default_config': default_config
}
for key, value in session_defaults.items():
if key not in st.session_state:
st.session_state[key] = value
# ----------------------------
# Portfolio Management Functions
# ----------------------------
def delete_portfolio(selected_portfolio):
"""Delete a portfolio by name."""
st.session_state.portfolios = [
p for p in st.session_state.portfolios if p['name'] != selected_portfolio
]
st.success(f"Portfolio '{selected_portfolio}' deleted successfully.")
if st.session_state.edit_portfolio == selected_portfolio:
st.session_state.edit_portfolio = None
def duplicate_portfolio(portfolio, new_name):
"""Duplicate a portfolio with a new name."""
duplicated = portfolio.copy()
duplicated['name'] = new_name
st.session_state.portfolios.append(duplicated)
st.success(f"Portfolio '{new_name}' duplicated successfully.")
def update_portfolio(portfolio, updated_data):
"""Update an existing portfolio with new data."""
portfolio.update(updated_data)
st.success(f"Portfolio '{portfolio['name']}' updated successfully!")
def add_new_portfolio(new_portfolio):
"""Add a new portfolio to the session state."""
st.session_state.portfolios.append(new_portfolio)
st.success(f"Portfolio '{new_portfolio['name']}' added successfully!")
st.json({ticker: f"{alloc}%" for ticker, alloc in zip(new_portfolio['selected'], new_portfolio['allocations'])})
def validate_allocations(allocations):
"""Validate that allocations sum to 100%."""
total = sum(allocations)
if not np.isclose(total, 100.0, atol=1e-4):
st.warning(f"Allocations must sum to 100%. Currently sum to {total:.6f}%. Please adjust the allocations.")
return False
return True
# ----------------------------
# UI Components
# ----------------------------
def display_existing_portfolios(tickers_df):
"""Display and manage existing portfolios."""
st.subheader("📁 Existing Portfolios")
if st.session_state.portfolios:
portfolio_names = [p['name'] for p in st.session_state.portfolios]
selected_portfolio = st.selectbox("Select Portfolio to Edit/Delete/Duplicate", portfolio_names)
if selected_portfolio:
portfolio = next(p for p in st.session_state.portfolios if p['name'] == selected_portfolio)
col_del, col_edit, col_dup = st.columns(3)
with col_del:
if st.button("🗑️ Delete Portfolio"):
delete_portfolio(selected_portfolio)
with col_edit:
if st.button("✏️ Edit Portfolio"):
st.session_state.edit_portfolio = selected_portfolio
with col_dup:
if st.button("📄 Duplicate Portfolio"):
new_name = st.text_input("New Portfolio Name", f"{selected_portfolio}_Copy")
if st.button("Confirm Duplicate"):
if not new_name:
st.error("Please provide a new portfolio name.")
elif new_name in portfolio_names:
st.error("Portfolio name already exists.")
else:
duplicate_portfolio(portfolio, new_name)
else:
st.write("No portfolios saved.")
def edit_portfolio_form(tickers_df):
"""Form to edit an existing portfolio."""
if st.session_state.edit_portfolio:
st.markdown("---")
st.subheader("✏️ Edit Portfolio")
try:
portfolio = next(p for p in st.session_state.portfolios if p['name'] == st.session_state.edit_portfolio)
except StopIteration:
st.error("The portfolio you are trying to edit no longer exists.")
st.session_state.edit_portfolio = None
return
with st.form("edit_portfolio_form"):
name = st.text_input("Portfolio Name", portfolio['name'], help="Enter a unique name for your portfolio.")
start_date = st.date_input(
"Start Date:",
portfolio['start_date'].date(),
min_value=datetime(1900, 1, 1),
help="Choose the start date for backtesting."
)
end_date = st.date_input(
"End Date:",
portfolio['end_date'].date(),
min_value=datetime(1900, 1, 1),
help="Choose the end date for backtesting."
)
rf_rate = st.number_input(
"Risk-Free Rate (%)",
0.0,
10.0,
portfolio['rf_rate'] * 100,
help="Enter the risk-free rate as a percentage."
) / 100
broker_fee = st.number_input(
"Broker Fee (%)",
0.0,
10.0,
portfolio['broker_fee'] * 100,
step=0.000001,
format="%.6f",
help="Enter the broker fee as a percentage per transaction."
) / 100
benchmark_symbol = st.text_input(
"Benchmark Symbol (e.g., ^GSPC)",
portfolio['benchmark_symbol'],
help="Enter the ticker symbol for your benchmark index."
)
rebalance_freq = st.selectbox(
"Rebalance Frequency",
list(frequency_mapping.keys()),
index=list(frequency_mapping.values()).index(portfolio['rebalance_freq']),
help="Choose how often to rebalance the portfolio."
)
st.markdown("### 🛠️ Set Allocations")
selected_default = [format_asset_option(ticker, get_company_name(tickers_df, ticker)) for ticker in portfolio['selected']]
asset_options = tickers_df.apply(lambda row: format_asset_option(row['Ticker'], row['Company Name']), axis=1).tolist()
selected = st.multiselect(
"Select Assets:",
options=asset_options,
default=selected_default,
help="Choose the assets you want to include in your portfolio."
)
selected_tickers = [option.split(' - ')[0] for option in selected if ' - ' in option]
allocations = []
for ticker in selected_tickers:
alloc = st.number_input(
f"{ticker} Allocation (%)",
min_value=0.0,
max_value=100.0,
value=portfolio['allocations'][portfolio['selected'].index(ticker)],
step=0.000001,
format="%.6f",
key=f"alloc_edit_{ticker}",
help=f"Set the allocation percentage for {ticker}. Must sum to 100% across all selected assets."
)
allocations.append(alloc)
total_allocation = sum(allocations)
st.markdown(f"**Total Allocation:** {total_allocation:.6f}%")
if not np.isclose(total_allocation, 100.0, atol=1e-4):
st.warning(f"Allocations must sum to 100%. Currently sum to {total_allocation:.6f}%. Please adjust the allocations.")
if total_allocation > 0:
allocations = [alloc / total_allocation * 100 for alloc in allocations]
else:
st.error("Total allocation is zero. Please set allocations for your assets.")
submitted = st.form_submit_button("Save Changes")
if submitted:
if not name:
st.error("Please provide a portfolio name.")
elif name != portfolio['name'] and name in [p['name'] for p in st.session_state.portfolios]:
st.error("Portfolio name already exists. Please choose a unique name.")
elif not selected:
st.error("Please select at least one asset.")
elif not np.isclose(sum(allocations), 100.0, atol=1e-4):
st.warning(f"Allocations must sum to 100%. Currently sum to {sum(allocations):.6f}%. Adjusting allocations proportionally.")
allocations = [alloc / total_allocation * 100 for alloc in allocations] if total_allocation else allocations
updated_data = {
'name': name,
'start_date': pd.to_datetime(start_date),
'end_date': pd.to_datetime(end_date),
'rf_rate': rf_rate,
'broker_fee': broker_fee,
'benchmark_symbol': benchmark_symbol,
'rebalance_freq': frequency_mapping.get(rebalance_freq, 'M'),
'selected': selected_tickers,
'allocations': allocations
}
update_portfolio(portfolio, updated_data)
st.session_state.edit_portfolio = None
def display_example_portfolios(tickers_df):
"""Display and load example portfolios."""
st.markdown("---")
st.subheader("💡 Example Portfolios")
example_portfolios = [
{
'name': "Retirement Portfolio",
'start_date': datetime.today() - timedelta(days=365*10),
'end_date': datetime.today(),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': '^GSPC',
'rebalance_freq': 'M',
'selected': ['AAPL', 'MSFT', 'GOOGL', 'JPM', 'XOM'],
'allocations': [20.0, 20.0, 20.0, 20.0, 20.0]
},
{
'name': "Tech-Heavy Portfolio",
'start_date': datetime.today() - timedelta(days=365*5),
'end_date': datetime.today(),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': '^IXIC',
'rebalance_freq': 'M',
'selected': ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'META'],
'allocations': [25.0, 25.0, 20.0, 15.0, 15.0]
},
# Add other example portfolios here...
{
'name': "Growth-Oriented Portfolio",
'start_date': datetime.today() - timedelta(days=365*3),
'end_date': datetime.today(),
'rf_rate': 0.02,
'broker_fee': 0.0,
'benchmark_symbol': '^IXIC',
'rebalance_freq': 'M',
'selected': ['TSLA', 'NVDA', 'AMD', 'META', 'NFLX'],
'allocations': [30.0, 25.0, 20.0, 15.0, 10.0]
},
# ... Add more examples as needed
]
for example in example_portfolios:
with st.expander(example['name']):
df_example = pd.DataFrame({
'Attribute': ['Start Date', 'End Date', 'Risk-Free Rate (%)', 'Broker Fee (%)',
'Benchmark Symbol', 'Rebalance Frequency', 'Selected Assets', 'Allocations (%)'],
'Value': [
example['start_date'].strftime('%Y-%m-%d'),
example['end_date'].strftime('%Y-%m-%d'),
f"{example['rf_rate']*100:.2f}",
f"{example['broker_fee']*100:.6f}",
example['benchmark_symbol'],
example['rebalance_freq'],
", ".join(example['selected']),
", ".join([f"{alloc:.2f}" for alloc in example['allocations']])
]
})
st.table(df_example)
if st.button(f"Load {example['name']}", key=f"load_{example['name']}"):
if example['name'] in [p['name'] for p in st.session_state.portfolios]:
st.warning(f"Portfolio '{example['name']}' already exists.")
else:
loaded_portfolio = {
'name': example['name'],
'start_date': pd.to_datetime(example['start_date']),
'end_date': pd.to_datetime(example['end_date']),
'rf_rate': example['rf_rate'],
'broker_fee': example['broker_fee'],
'benchmark_symbol': example['benchmark_symbol'],
'rebalance_freq': example['rebalance_freq'],
'selected': example['selected'],
'allocations': example['allocations']
}
add_new_portfolio(loaded_portfolio)
def add_portfolio_form(tickers_df):
"""Form to add a new portfolio."""
st.subheader("➕ Add New Portfolio")
with st.form("add_portfolio_form"):
st.markdown("### 🔧 Configure Details")
name = st.text_input("Portfolio Name", "", help="Enter a unique name for your portfolio.")
start_date = st.date_input(
"Start Date:",
datetime.today() - timedelta(days=365 * 15),
min_value=datetime(1900, 1, 1),
help="Choose the start date for backtesting."
)
end_date = st.date_input(
"End Date:",
datetime.today(),
min_value=datetime(1900, 1, 1),
help="Choose the end date for backtesting."
)
rf_rate = st.number_input(
"Risk-Free Rate (%)",
0.0,
10.0,
st.session_state.default_config['rf_rate'] * 100,
help="Enter the risk-free rate as a percentage."
) / 100
broker_fee = st.number_input(
"Broker Fee (%)",
0.0,
10.0,
st.session_state.default_config['broker_fee'] * 100,
step=0.000001,
format="%.6f",
help="Enter the broker fee as a percentage per transaction."
) / 100
benchmark_symbol = st.text_input(
"Benchmark Symbol (e.g., ^GSPC)",
st.session_state.default_config['benchmark_symbol'],
help="Enter the ticker symbol for your benchmark index."
)
rebalance_freq = st.selectbox(
"Rebalance Frequency",
list(frequency_mapping.keys()),
index=list(frequency_mapping.keys()).index("Monthly"),
help="Choose how often to rebalance the portfolio."
)
st.markdown("### 🛠️ Set Allocations")
asset_options = tickers_df.apply(lambda row: format_asset_option(row['Ticker'], row['Company Name']), axis=1).tolist()
selected = st.multiselect(
"Select Assets:",
options=asset_options,
help="Choose the assets you want to include in your portfolio."
)
selected_tickers = [option.split(' - ')[0] for option in selected if ' - ' in option]
allocations = []
for ticker in selected_tickers:
alloc = st.number_input(
f"{ticker} Allocation (%)",
min_value=0.0,
max_value=100.0,
value=0.0,
step=0.000001,
format="%.6f",
key=f"alloc_new_{ticker}",
help=f"Set the allocation percentage for {ticker}. The sum of all allocations must equal 100%."
)
allocations.append(alloc)
total_allocation = sum(allocations)
st.markdown(f"**Total Allocation:** {total_allocation:.6f}%")
if not np.isclose(total_allocation, 100.0, atol=1e-4):
st.warning(f"Allocations must sum to 100%. Currently sum to {total_allocation:.6f}%. Please adjust the allocations.")
submitted = st.form_submit_button("Add Portfolio")
if submitted:
if not name:
st.error("Please provide a portfolio name.")
elif name in [p['name'] for p in st.session_state.portfolios]:
st.error("Portfolio name already exists. Please choose a unique name.")
elif not selected:
st.error("Please select at least one asset.")
elif not np.isclose(sum(allocations), 100.0, atol=1e-4):
st.error(f"Allocations must sum to 100%. Currently sum to {sum(allocations):.6f}%.")
else:
new_portfolio = {
'name': name,
'start_date': pd.to_datetime(start_date),
'end_date': pd.to_datetime(end_date),
'rf_rate': rf_rate,
'broker_fee': broker_fee,
'benchmark_symbol': benchmark_symbol,
'rebalance_freq': frequency_mapping.get(rebalance_freq, 'M'),
'selected': selected_tickers,
'allocations': allocations
}
add_new_portfolio(new_portfolio)
def display_debug_info():
"""Display debugging information."""
with st.expander("🔍 Debug Information"):
st.write("Current Portfolios in Session State:")
st.write(st.session_state.portfolios)
# ----------------------------
# Main Application
# ----------------------------
def main():
# Initialize session state
initialize_session()
# ----------------------------
# Streamlit Layout
# ----------------------------
st.set_page_config(page_title="🎯 Portfolio Optimizer", layout="wide")
st.title("🎯 Portfolio Optimizer")
# Use a placeholder that hides after loading
loading_placeholder = st.empty()
loading_placeholder.info("🎯 Portfolio Optimizer is loading, please be patient...")
# Simulate loading (you can replace this with actual loading logic)
st.sleep(1) # Sleep for 1 second to simulate loading
loading_placeholder.empty()
# Sidebar Navigation
st.sidebar.header("📂 Navigation")
step = st.sidebar.radio(
"Navigate to",
["Configure Portfolio", "Run Backtest", "Optimize Portfolio", "Monte Carlo Simulations", "Risk Analysis"],
index=["Configure Portfolio", "Run Backtest", "Optimize Portfolio", "Monte Carlo Simulations", "Risk Analysis"].index(
st.session_state.get('step', "Configure Portfolio")
),
key="sidebar_radio"
)
st.session_state.step = step # Update the current step
# Get tickers data
tickers_df = get_tickers()
# Step Handling
if step == "Configure Portfolio":
col1, col2 = st.columns([1, 1])
with col1:
display_existing_portfolios(tickers_df)
edit_portfolio_form(tickers_df)
display_example_portfolios(tickers_df)
with col2:
add_portfolio_form(tickers_df)
display_debug_info()
elif step == "Run Backtest":
st.header("🔄 Run Backtest")
st.write("Backtest functionality goes here.")
# Implement Run Backtest functionality
elif step == "Optimize Portfolio":
st.header("⚙️ Optimize Portfolio")
st.write("Optimization functionality goes here.")
# Implement Optimize Portfolio functionality
elif step == "Monte Carlo Simulations":
st.header("🎲 Monte Carlo Simulations")
st.write("Monte Carlo Simulations functionality goes here.")
# Implement Monte Carlo Simulations functionality
elif step == "Risk Analysis":
st.header("📊 Risk Analysis")
st.write("Risk Analysis functionality goes here.")
# Implement Risk Analysis functionality
if __name__ == "__main__":
main()