Portfolio Configuration
    Portfolio Name: Enter a unique name for your portfolio.

Start Date: Choose the start date for backtesting.

End Date: Choose the end date for backtesting.

Risk-Free Rate: Enter the risk-free rate as a percentage.

Broker Fee: Enter the broker fee as a percentage per transaction.

Benchmark Symbol: Enter the ticker symbol for your benchmark index.

Rebalance Frequency: Choose how often to rebalance the portfolio (Daily, Weekly, Monthly, Quarterly, Yearly).

Asset Selection: Choose the assets you want to include in your portfolio.

Asset Allocations: Set the allocation percentage for each selected asset.

    Portfolio Management
    Edit Portfolio: Modify existing portfolio configurations.

Delete Portfolio: Remove a portfolio from the list.

Duplicate Portfolio: Create a copy of an existing portfolio.

    Example Portfolios
    Retirement Portfolio: Pre-configured portfolio example.

Tech-Heavy Portfolio: Pre-configured portfolio example.

Balanced Risk-Return Portfolio: Pre-configured portfolio example.

Income-Focused Portfolio: Pre-configured portfolio example.

Growth-Oriented Portfolio: Pre-configured portfolio example.

Value Portfolio: Pre-configured portfolio example.

Conservative Portfolio: Pre-configured portfolio example.

Dividend-Focused Portfolio: Pre-configured portfolio example.

Global Diversification Portfolio: Pre-configured portfolio example.

High-Risk Growth Portfolio: Pre-configured portfolio example.

Emerging Markets Portfolio: Pre-configured portfolio example.

    Backtesting
    Portfolio vs Benchmark: Compare portfolio performance against a selected benchmark.

Portfolio vs Portfolio: Compare the performance of two different portfolios.

Key Metrics: Display key performance metrics such as Annualized Return (CAGR), Sharpe Ratio, and Maximum Drawdown.

Performance Statistics: Detailed statistics including Start Balance, End Balance, Best Year, Worst Year, etc.

Advanced Metrics: Extended metrics including Alpha, Beta, Information Ratio, Tracking Error, etc.

Drawdowns: Detailed drawdown analysis for both portfolio and benchmark.

Visualizations:

Growth Comparison: Line chart comparing portfolio and benchmark growth.

Drawdown Comparison: Line chart comparing portfolio and benchmark drawdowns.

CAGR Over Time: Line chart showing CAGR over different time frames.

Returns Distribution Box Plot: Box plot visualizing the distribution of returns.

Correlation Heatmap: Heatmap showing correlations between assets.

Risk-Return Attribution: Scatter plot showing risk-return attribution.

Cumulative Returns Heatmap: Heatmap showing normalized cumulative returns over time.

Portfolio Allocation Pie Chart: Pie chart showing portfolio allocation.

Rolling Metrics: Line chart showing rolling metrics over user-defined periods.

    Optimization
    Optimization Constraints: Set maximum and minimum weights per asset.

Multi-Objective Selection: Choose multiple optimization objectives (Sharpe Ratio, Minimum Variance, Maximum Return, Minimum Drawdown, Maximize Alpha, Minimize Beta).

Target Return: Set the target annual return for portfolio optimization.

Optimized Weights: Display optimized asset weights.

Optimized Portfolio Performance Metrics: Display expected annual return, annualized volatility, and Sharpe Ratio for the optimized portfolio.

    Monte Carlo Simulations
    Simulation Parameters:

Number of Simulations: Set the number of simulations to run.

Number of Periods: Set the number of periods for each simulation.

Return Distribution: Choose between normal and log-normal return distributions.

Mean Reversion: Enable mean reversion with adjustable speed and long-term mean.

Time-Varying Volatility: Enable time-varying volatility with adjustable change rate.

Stress Testing: Apply stress shocks to selected assets.

Sensitivity Analysis: Adjust returns based on changes in interest rates and inflation rates.

Cross-Asset Sensitivity Analysis: Adjust returns based on changes in currency exchange rates and commodity prices.

Simulation Results:

Descriptive Statistics: Summary statistics of simulated returns.

Returns Distribution Histogram: Histogram showing the frequency of different return outcomes.

Cumulative Distribution Function (CDF): CDF showing the probability of returns.

Box Plot of Simulated Returns: Box plot visualizing the distribution of simulated returns.

Summary Statistics Table: Table summarizing key metrics from the simulation runs.

    Risk Analysis
    Risk Metrics:

Value at Risk (VaR): Calculate the worst expected loss under normal market conditions.

Conditional Value at Risk (CVaR): Calculate the average loss exceeding the VaR.

Skewness: Measure the asymmetry of the return distribution.

Kurtosis: Measure the "tailedness" of the return distribution.

Annualized Volatility: Measure the variability of portfolio returns.

Maximum Drawdown: Measure the largest peak-to-trough decline.

Visualizations:

VaR Plot: Line chart showing VaR over time.

CVaR Plot: Line chart showing CVaR over time.

VaR and CVaR Distribution Plot: Histogram showing the distribution of returns with VaR and CVaR lines.

Adjusted Returns Distribution: Histogram showing the distribution of returns after applying stress shocks and sensitivity adjustments.

Risk vs Return Scatter Plot: Scatter plot showing the relationship between risk and return.

    Additional Features
    Efficient Frontier: Plot the efficient frontier of portfolios based on different objectives.

Performance Attribution: Break down portfolio performance by individual assets.

Recommendation Engine: Provide suggestions for portfolio adjustments based on current allocations and objectives.

Final Score: Calculate and display a final score for the portfolio based on various metrics.

Documentation: Detailed documentation explaining each metric and its formula.

    Caching and Session Management
    Caching Functions: Use caching to store and retrieve data efficiently.

Session State: Manage session state to store portfolio configurations, backtest results, and other user inputs.

    Onboarding and Debugging
    Onboarding Process: Guide new users through the initial setup.

Debug Information: Display debug information for troubleshooting.

code and build a stock portfolio optimizer based on the above, I will deployed it in a website with aapanel, give me full code and how to use it
use Shiny for Python