Portfolio Optimization
Overview
The Portfolio Optimizer provides sophisticated portfolio optimization tools based on modern portfolio theory and advanced allocation techniques. The API enables you to find optimal asset weights that maximize returns for a given level of risk or minimize risk for a given level of return.
Multiple optimization methods are available:
- Mean-Variance Optimization (maximize Sharpe ratio)
- Mean-Variance Optimization (minimize volatility)
- Hierarchical Risk Parity
- Kelly Criterion
These methods can be applied in both point-in-time analysis and walkforward testing to evaluate how portfolio allocations would have performed through time.
Optimization Methods
Mean-Variance Optimization
Mean-Variance Optimization (MVO) is based on Harry Markowitz's Modern Portfolio Theory. This approach:
- Analyzes expected returns, volatilities, and correlations between assets
- Finds portfolios that offer the highest expected return for a given level of risk
- Can be configured to either maximize the Sharpe ratio or Minimize Volatility
MVO Max Sharpe
This method optimizes the portfolio to achieve the highest possible Sharpe ratio (excess return divided by volatility).
MVO Min Volatility
This method finds the combination of assets that produces the lowest possible portfolio volatility. It's useful for conservative allocation strategies focused on risk reduction.
Surprisingly the volatility minimization portfolio will frequently result in higher out of sample Sharpe ratios than the MVO Max Sharpe optimization target.
Hierarchical Risk Parity
Hierarchical Risk Parity (HRP) is a modern portfolio optimization technique developed by Marcos Lopez de Prado that:
- Uses machine learning to build a hierarchical clustering of assets
- Distributes risk equally among different clusters in the hierarchy
- Does not rely on expected returns, focusing solely on the covariance structure
- Is less susceptible to estimation errors compared to classical mean-variance optimization
HRP is particularly effective when dealing with large numbers of assets or when return estimates are unreliable. Warning: HRP with a moderate set of assets HRP can fail to converge to a solution.
Kelly Criterion
The Kelly Criterion optimization:
- Maximizes the expected logarithm of wealth
- Balances potential growth against risk of ruin
- Is theoretically optimal for long-term wealth growth
- Can produce more aggressive allocations than traditional methods
Full Kelly allocations can be very aggressive and may not be suitable for all portfolios. Consider using fractional kelly allocations for a more conservative approach.
API Endpoints
One-Time Optimization
POST /portfolio-optimizer/v1/optimize-weights
This endpoint calculates optimal portfolio weights for the provided historical asset data.
Request Parameters
mode(query): The optimization method to use. Options:MeanVarianceMaxSharpeMeanVarianceMinVolatilityHierarchicalRiskParityKellyCriterion
topAlloc(query): The number of top assets to include in the final allocationriskFreeRate(query, optional): Annual risk-free rate (decimal format, e.g., 0.05 for 5%). Defaults to 0.
Request Body
CSV data with historical prices for each asset:
DateTime,Asset1,Asset2,Asset3,...
2020-01-01,100.0,50.0,75.0,...
2020-01-02,101.5,49.5,76.2,...
...
- The first column must be labeled
DateTimeand contain dates or datetimes - Each subsequent column represents an asset and contains its price or NAV values
- Values should be numeric and represent comparable metrics (typically prices)
Response
{
"Asset1": 0.25,
"Asset2": 0.35,
"Asset3": 0.40,
...
}
The response is a JSON object mapping asset names to their optimal allocation weights. The weights sum to 1.0 (or 100%).
Walkforward Portfolio Analysis
POST /portfolio-optimizer/v1/walkforward-portfolio
This endpoint performs walkforward optimization, rebalancing the portfolio at specified intervals, and returns the resulting portfolio performance.
Request Parameters
mode(query): Same options as optimize-weightstopAlloc(query): Number of top assets to includewindowSize(query): Number of days used for each optimization periodreweightPeriod(query, optional): Number of days between rebalances. Defaults to 1.riskFreeRate(query, optional): Annual risk-free rate. Defaults to 0.
Request Body
Same CSV format as optimize-weights.
Response
CSV data containing the walkforward portfolio's performance:
DateTime,Portfolio
2020-01-15,10000.0
2020-01-16,10050.0
...
The response includes:
- A header row with "DateTime" and "Portfolio" columns
- Daily values of the portfolio, assuming the specified rebalancing frequency
- The portfolio starts after the initial
windowSizeperiod
Walkforward Weights History
POST /portfolio-optimizer/v1/walkforward-weights
This endpoint performs walkforward optimization and returns the historical weights at each rebalancing period.
Request Parameters
Same parameters as walkforward-portfolio.
Request Body
Same CSV format as optimize-weights.
Response
CSV data containing the historical weights at each rebalance point:
DateTime,Asset1,Asset2,Asset3,...
2020-01-15,0.25,0.35,0.40,...
2020-02-15,0.30,0.30,0.40,...
...
The response includes:
- A header row with "DateTime" and each asset name
- One row for each rebalance date with the optimal weights at that time
- Weights will always sum to 1.0 at each date
Usage Examples
Basic One-Time Optimization
import requests
csv_data = """DateTime,Strategy1,Strategy2,Strategy3,Strategy4
2022-01-01,10000,20000,15000,30000
2022-01-02,10050,20100,14950,30300
2022-01-03,10100,20050,15100,30150
# ... more rows
"""
response = requests.post(
"https://q-api.example-customer.mesosim.io/portfolio-optimizer/v1/optimize-weights?mode=HierarchicalRiskParity&topAlloc=3",
headers={"Authorization": "Bearer YOUR_API_TOKEN", "Content-Type": "text/plain"},
data=csv_data
)
optimal_weights = response.json()
print(optimal_weights)
Walkforward Portfolio Analysis
import requests
csv_data = """DateTime,Strategy1,Strategy2,Strategy3,Strategy4
2022-01-01,10000,20000,15000,30000
# ... many more rows covering at least several months
"""
response = requests.post(
"https://q-api.example-customer.mesosim.io/portfolio-optimizer/v1/walkforward-portfolio?mode=MeanVarianceMaxSharpe&topAlloc=4&windowSize=30&reweightPeriod=7",
headers={"Authorization": "Bearer YOUR_API_TOKEN", "Content-Type": "text/plain"},
data=csv_data
)
# Save the portfolio performance to a CSV file
with open("portfolio_performance.csv", "w") as f:
f.write(response.text)
Practical Considerations
Data Requirements
- Provide sufficient historical data (at least 2× the window size for walkforward analysis)
- Ensure data is clean and free of outliers
- Missing values or non-trading days should be handled consistently
- All assets should have data for the same time periods
Optimization Parameters
- Window Size: Longer windows provide more statistical confidence but may miss regime changes
- Rebalance Period: More frequent rebalancing can capture changes faster but may increase transaction costs
- Top Allocations: Limiting to fewer assets simplifies the portfolio but may reduce diversification
- Risk-Free Rate: Should match the expected return on cash for the time period analyzed
Interpreting Results
- The optimizers seek mathematical optimality based on historical data; past performance doesn't guarantee future results
- Hierarchical Risk Parity is sensitive to number of assets and may fail to converge with small sets
- Kelly criterion tends to produce the most aggressive allocations and should be used with caution
Common Use Cases
- Asset Allocation: Determine optimal weights across asset classes
- Strategy Selection: Select and weight trading strategies in a portfolio
- Risk Management: Find the minimum volatility portfolio for conservative allocations
- Performance Analysis: Use walkforward testing to evaluate how portfolio allocation would have performed historically