Creating a comprehensive stock portfolio optimizer as described is a substantial project that involves multiple components, including portfolio configuration, backtesting, risk analysis, optimization, Monte Carlo simulations, and more. Below, I'll provide a structured approach to building this application using Shiny for Python, along with sample code snippets to help you get started.
Please note that due to the complexity and size of the project, this response will outline the main components and provide example implementations for key features. You can expand upon these examples to build the full application.
1. Project Structure
Organize your project with a clear structure to manage different components effectively.
portfolio_optimizer/
├── app.py
├── requirements.txt
├── data/
│ └── example_portfolios.csv
├── utils/
│ ├── portfolio.py
│ ├── optimization.py
│ ├── backtesting.py
│ ├── risk_analysis.py
│ └── simulations.py
├── assets/
│ └── styles.css
└── templates/
└── README.md
2. Setting Up the Environment
First, create a virtual environment and install the necessary packages.
requirements.txt
pandas
numpy
plotly
shiny
cvxpy
yfinance
scipy
matplotlib
seaborn
Install the dependencies using pip:
pip install -r requirements.txt
3. Building the Application with Shiny for Python
app.py
from shiny import App, ui, render, reactive
import pandas as pd
import yfinance as yf
import plotly.express as px
from utils.portfolio import calculate_portfolio_metrics
from utils.optimization import optimize_portfolio
from utils.backtesting import backtest_portfolio
from utils.risk_analysis import perform_risk_analysis
from utils.simulations import run_monte_carlo_simulation
# Define the UI layout
app_ui = ui.page_fluid(
ui.h2("Stock Portfolio Optimizer"),
ui.layout_sidebar(
ui.panel_sidebar(
ui.h3("Portfolio Configuration"),
ui.input_text("portfolio_name", "Portfolio Name", value="My Portfolio"),
ui.input_date("start_date", "Start Date", value="2020-01-01"),
ui.input_date("end_date", "End Date", value="2023-01-01"),
ui.input_numeric("risk_free_rate", "Risk-Free Rate (%)", value=1.5, step=0.1),
ui.input_numeric("broker_fee", "Broker Fee (%)", value=0.1, step=0.01),
ui.input_text("benchmark", "Benchmark Symbol", value="SPY"),
ui.input_select("rebalance_frequency", "Rebalance Frequency",
["Daily", "Weekly", "Monthly", "Quarterly", "Yearly"], selected="Monthly"),
ui.input_text("assets", "Asset Selection (comma separated)", value="AAPL,MSFT,GOOGL,AMZN"),
ui.input_numeric("allocations", "Asset Allocations (%) (comma separated)", value="25,25,25,25"),
ui.action_button("run_backtest", "Run Backtest"),
ui.tags.hr(),
ui.h3("Portfolio Management"),
ui.input_action_button("edit_portfolio", "Edit Portfolio"),
ui.input_action_button("delete_portfolio", "Delete Portfolio"),
ui.input_action_button("duplicate_portfolio", "Duplicate Portfolio"),
ui.tags.hr(),
ui.h3("Monte Carlo Simulations"),
ui.input_numeric("num_simulations", "Number of Simulations", value=1000),
ui.input_numeric("num_periods", "Number of Periods", value=252),
ui.input_select("return_distribution", "Return Distribution",
["normal", "log-normal"], selected="normal"),
ui.action_button("run_simulation", "Run Simulation")
),
ui.panel_main(
ui.tabset_panel(
ui.tab("Backtesting",
ui.output_text_verbatim("backtest_results"),
ui.plot_output("growth_comparison"),
ui.plot_output("drawdown_comparison")),
ui.tab("Risk Analysis",
ui.output_text_verbatim("risk_metrics"),
ui.plot_output("var_plot"),
ui.plot_output("cvar_plot")),
ui.tab("Monte Carlo",
ui.plot_output("mc_returns_distribution"),
ui.output_text_verbatim("mc_summary")),
ui.tab("Optimization",
ui.input_numeric("target_return", "Target Return (%)", value=10),
ui.action_button("optimize", "Optimize Portfolio"),
ui.output_table("optimized_weights"),
ui.output_text_verbatim("optimized_metrics"))
)
)
)
)
# Define server logic
def server(input, output, session):
@reactive.Effect
@reactive.event(input.run_backtest)
def _():
# Parse inputs
assets = [asset.strip() for asset in input.assets().split(",")]
allocations = [float(a) for a in input.allocations().split(",")]
if len(assets) != len(allocations):
session.send_custom_message("error", "Number of assets and allocations must match.")
return
portfolio = dict(zip(assets, allocations))
# Fetch data
data = yf.download(assets + [input.benchmark()], start=input.start_date(), end=input.end_date())['Adj Close']
# Backtest
backtest_results = backtest_portfolio(data, portfolio, input.benchmark())
# Display results
output.backtest_results.set_text(backtest_results['metrics'].to_string())
# Plot growth comparison
fig_growth = px.line(backtest_results['growth'], x=backtest_results['growth'].index, y=["Portfolio", "Benchmark"],
title="Growth Comparison")
output.growth_comparison.set_plotly(fig_growth)
# Plot drawdown comparison
fig_drawdown = px.line(backtest_results['drawdown'], x=backtest_results['drawdown'].index,
y=["Portfolio Drawdown", "Benchmark Drawdown"],
title="Drawdown Comparison")
output.drawdown_comparison.set_plotly(fig_drawdown)
@reactive.Effect
@reactive.event(input.run_simulation)
def _():
assets = [asset.strip() for asset in input.assets().split(",")]
allocations = [float(a) for a in input.allocations().split(",")]
portfolio = dict(zip(assets, allocations))
# Run Monte Carlo Simulations
simulation_results = run_monte_carlo_simulation(portfolio, input.num_simulations(),
input.num_periods(),
input.return_distribution())
# Plot Returns Distribution Histogram
fig_hist = px.histogram(simulation_results['returns'], nbins=50, title="Monte Carlo Returns Distribution")
output.mc_returns_distribution.set_plotly(fig_hist)
# Display Summary Statistics
summary = simulation_results['summary'].to_string()
output.mc_summary.set_text(summary)
@reactive.Effect
@reactive.event(input.optimize)
def _():
assets = [asset.strip() for asset in input.assets().split(",")]
# Perform optimization
optimized = optimize_portfolio(assets, input.target_return())
# Display optimized weights
output.optimized_weights.set_table(optimized['weights'].to_frame(name='Allocation (%)'))
# Display optimization metrics
metrics = pd.Series(optimized['metrics'])
output.optimized_metrics.set_text(metrics.to_string())
# Additional reactive expressions and outputs can be added similarly
app = App(app_ui, server)
Explanation:
-
UI Components:
- Sidebar: For portfolio configuration, management, and simulation parameters.
- Main Panel: Contains tabs for Backtesting, Risk Analysis, Monte Carlo Simulations, and Optimization.
-
Server Logic:
- Backtesting: When the user clicks "Run Backtest," the app fetches historical data using
yfinance, performs backtesting, and displays results and plots.
- Monte Carlo Simulations: Runs simulations based on user inputs and displays the distribution of returns.
- Optimization: Optimizes the portfolio based on the target return and displays the optimized weights and metrics.
-
Utility Functions:
- The actual implementation of
backtest_portfolio, run_monte_carlo_simulation, and optimize_portfolio would reside in the utils directory.
4. Implementing Utility Functions
utils/portfolio.py
This module can contain functions related to portfolio metrics calculation.
import numpy as np
import pandas as pd
def calculate_portfolio_metrics(returns, weights):
portfolio_return = np.dot(returns.mean(), weights)
portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(returns.cov(), weights)))
return {
'Return': portfolio_return,
'Volatility': portfolio_volatility
}
utils/backtesting.py
Implement the backtesting logic.
def backtest_portfolio(data, portfolio, benchmark):
# Calculate portfolio returns
weights = np.array(list(portfolio.values())) / 100.0
portfolio_returns = data[list(portfolio.keys())].pct_change().dropna().dot(weights)
# Calculate benchmark returns
benchmark_returns = data[benchmark].pct_change().dropna()
# Compute cumulative returns
cumulative_portfolio = (1 + portfolio_returns).cumprod()
cumulative_benchmark = (1 + benchmark_returns).cumprod()
# Calculate drawdowns
drawdown_portfolio = cumulative_portfolio / cumulative_portfolio.cummax() - 1
drawdown_benchmark = cumulative_benchmark / cumulative_benchmark.cummax() - 1
# Metrics
metrics = calculate_portfolio_metrics(portfolio_returns, weights)
metrics_df = pd.DataFrame(metrics, index=[0])
return {
'growth': pd.DataFrame({
'Portfolio': cumulative_portfolio,
'Benchmark': cumulative_benchmark
}),
'drawdown': pd.DataFrame({
'Portfolio Drawdown': drawdown_portfolio,
'Benchmark Drawdown': drawdown_benchmark
}),
'metrics': metrics_df
}
utils/optimization.py
Implement portfolio optimization using cvxpy.
import cvxpy as cp
import numpy as np
import pandas as pd
import yfinance as yf
def optimize_portfolio(assets, target_return):
# Fetch historical data
data = yf.download(assets, period="5y")['Adj Close'].dropna()
returns = data.pct_change().dropna()
mean_returns = returns.mean()
cov_matrix = returns.cov()
n = len(assets)
weights = cp.Variable(n)
# Define the optimization problem
portfolio_return = mean_returns.values @ weights
portfolio_volatility = cp.quad_form(weights, cov_matrix.values)
# Objective: Minimize volatility
objective = cp.Minimize(portfolio_volatility)
# Constraints:
constraints = [
cp.sum(weights) == 1,
portfolio_return >= target_return / 100.0,
weights >= 0
]
prob = cp.Problem(objective, constraints)
prob.solve()
optimized_weights = weights.value * 100 # Convert to percentage
optimized_weights_series = pd.Series(optimized_weights, index=assets)
# Calculate metrics
portfolio_return_opt = mean_returns.values @ weights.value
portfolio_volatility_opt = np.sqrt(weights.value.T @ cov_matrix.values @ weights.value)
sharpe_ratio = (portfolio_return_opt - 0.015) / portfolio_volatility_opt # Assuming risk-free rate of 1.5%
metrics = {
'Expected Return (%)': portfolio_return_opt * 100,
'Expected Volatility (%)': portfolio_volatility_opt * 100,
'Sharpe Ratio': sharpe_ratio
}
return {
'weights': optimized_weights_series,
'metrics': metrics
}
utils/risk_analysis.py
Implement risk metrics calculations.
def perform_risk_analysis(portfolio_returns):
VaR = portfolio_returns.quantile(0.05)
CVaR = portfolio_returns[portfolio_returns <= VaR].mean()
skewness = portfolio_returns.skew()
kurtosis = portfolio_returns.kurtosis()
annualized_volatility = portfolio_returns.std() * np.sqrt(252)
max_drawdown = (portfolio_returns.cummax() - portfolio_returns).max()
metrics = {
'Value at Risk (VaR)': VaR,
'Conditional VaR (CVaR)': CVaR,
'Skewness': skewness,
'Kurtosis': kurtosis,
'Annualized Volatility': annualized_volatility,
'Maximum Drawdown': max_drawdown
}
return pd.Series(metrics)
utils/simulations.py
Implement Monte Carlo simulations.
def run_monte_carlo_simulation(portfolio, num_simulations, num_periods, distribution='normal'):
assets = list(portfolio.keys())
allocations = np.array(list(portfolio.values())) / 100.0
data = yf.download(assets, period="5y")['Adj Close'].dropna()
returns = data.pct_change().dropna()
mean_returns = returns.mean()
cov_matrix = returns.cov()
portfolio_mean = np.dot(mean_returns, allocations)
portfolio_std = np.sqrt(np.dot(allocations.T, np.dot(cov_matrix, allocations)))
simulations = np.zeros(num_simulations)
for i in range(num_simulations):
if distribution == 'normal':
simulated_return = np.random.normal(portfolio_mean, portfolio_std, num_periods).sum()
else:
simulated_return = np.random.lognormal(portfolio_mean, portfolio_std, num_periods).sum()
simulations[i] = simulated_return
summary = pd.DataFrame(simulations, columns=['Simulated Returns']).describe()
return {
'returns': simulations,
'summary': summary
}
5. Deploying the Application with aapanel
Step 1: Prepare Your Server
Ensure you have a server with aapanel installed. You can follow the aapanel installation guide if you haven't set it up yet.
Step 2: Set Up Python Environment
-
Create a Virtual Environment:
python3 -m venv venv
source venv/bin/activate
-
Install Dependencies:
pip install -r requirements.txt
Step 3: Configure a Web Server in aapanel
-
Log into aapanel:
- Navigate to
http://your-server-ip:8888/ and log in.
-
Add a New Site:
- Go to the Website section and add a new site.
- Configure the domain and root directory as needed.
-
Set Up Reverse Proxy:
- Install and configure a reverse proxy (e.g., Nginx) to route traffic to your Shiny app.
-
Configure Firewall:
- Ensure that the necessary ports are open (e.g., port 80 for HTTP and 443 for HTTPS).
Step 4: Run the Shiny App
-
Start the Shiny App:
You can run the Shiny app using a process manager like screen, tmux, or systemd to keep it running in the background.
export PORT=3838
shiny run app.py --port 3838 --host 0.0.0.0
-
Set Up systemd Service (Optional):
Create a service file to manage the Shiny app.
sudo nano /etc/systemd/system/shinyapp.service
Add the following content:
[Unit]
Description=Shiny Portfolio Optimizer
After=network.target
[Service]
User=your_username
WorkingDirectory=/path/to/portfolio_optimizer
ExecStart=/path/to/portfolio_optimizer/venv/bin/shiny run app.py --port 3838 --host 0.0.0.0
Restart=always
[Install]
WantedBy=multi-user.target
Enable and Start the Service:
sudo systemctl enable shinyapp
sudo systemctl start shinyapp
-
Configure Reverse Proxy in Nginx:
Edit your Nginx configuration to proxy requests to the Shiny app.
sudo nano /etc/nginx/sites-available/your_site.conf
Add the following within the server block:
location / {
proxy_pass http://127.0.0.1:3838;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
Test and Reload Nginx:
sudo nginx -t
sudo systemctl reload nginx
Step 5: Access Your Application
Navigate to your domain (e.g., http://yourdomain.com) to access the Shiny Portfolio Optimizer.
6. Enhancing the Application
The provided code offers a foundational structure. To fully realize all the features mentioned in your requirements, consider the following enhancements:
-
Portfolio Management: Implement CRUD operations for managing multiple portfolios, possibly storing configurations in a database like SQLite or PostgreSQL.
-
Advanced Visualizations: Utilize Plotly and other visualization libraries to create interactive charts for efficient front-end user experience.
-
Risk Analysis: Expand the risk_analysis.py module to include more risk metrics and visualizations.
-
Documentation: Create detailed documentation within the templates/README.md and use tooltips or help sections within the UI for user guidance.
-
Recommendation Engine: Develop algorithms to suggest portfolio adjustments based on optimization results and user preferences.
-
Caching and Session Management: Use caching mechanisms (like Redis) to store frequently accessed data and manage user sessions effectively.
-
Testing: Implement unit tests for your utility functions and integration tests for the Shiny app to ensure reliability.
7. Security Considerations
-
Input Validation: Ensure all user inputs are validated to prevent security vulnerabilities like injection attacks.
-
HTTPS: Secure your site with SSL certificates to encrypt data transmission.
-
Authentication: Implement user authentication if the application will handle sensitive financial data.
8. Conclusion
Building a full-featured stock portfolio optimizer is a complex task that involves integrating various financial models, data sources, and user interface components. The provided framework using Shiny for Python should serve as a solid starting point. You can iteratively develop each feature, test thoroughly, and deploy progressively to create a robust and user-friendly application.
Feel free to ask for more detailed implementations of specific components or further assistance on particular aspects of the project!