# RiskOptima

RiskOptima is a comprehensive Python toolkit for evaluating, managing, and optimizing investment portfolios. This package is designed to empower investors and data scientists by combining financial risk analysis, backtesting, mean-variance optimization, and machine learning capabilities into a single, cohesive package.
## Stats
https://pypistats.org/packages/riskoptima
## Key Features
- Portfolio Optimization: Includes mean-variance optimization, efficient frontier calculation, and maximum Sharpe ratio portfolio construction.
- Risk Management: Compute key financial risk metrics such as Value at Risk (VaR), Conditional Value at Risk (CVaR), volatility, and drawdowns.
- Backtesting Framework: Simulate historical performance of investment strategies and analyze portfolio dynamics over time.
- Machine Learning Integration: Future-ready for implementing machine learning models for predictive analytics and advanced portfolio insights.
- Monte Carlo Simulations: Perform extensive simulations to analyze potential portfolio outcomes. See example here https://github.com/JordiCorbilla/efficient-frontier-monte-carlo-portfolio-optimization
- Comprehensive Financial Metrics: Calculate returns, Sharpe ratios, covariance matrices, and more.
## Installation
See the project here: https://pypi.org/project/riskoptima/
```
pip install riskoptima
```
## Usage
### Example 1: Setting up your portfolio
Create your portfolio table similar to the below:
| Asset | Weight | Label | MarketCap |
|-------|--------|-------------------------------|-----------|
| MO | 0.04 | Altria Group Inc. | 110.0e9 |
| NWN | 0.14 | Northwest Natural Gas | 1.8e9 |
| BKH | 0.01 | Black Hills Corp. | 4.5e9 |
| ED | 0.01 | Con Edison | 30.0e9 |
| PEP | 0.09 | PepsiCo Inc. | 255.0e9 |
| NFG | 0.16 | National Fuel Gas | 5.6e9 |
| KO | 0.06 | Coca-Cola Company | 275.0e9 |
| FRT | 0.28 | Federal Realty Inv. Trust | 9.8e9 |
| GPC | 0.16 | Genuine Parts Co. | 25.3e9 |
| MSEX | 0.05 | Middlesex Water Co. | 2.4e9 |
```python
import pandas as pd
from riskoptima import RiskOptima
import warnings
warnings.filterwarnings(
"ignore",
category=FutureWarning,
message=".*DataFrame.std with axis=None is deprecated.*"
)
# Define your current porfolio with your weights and company names
asset_data = [
{"Asset": "MO", "Weight": 0.04, "Label": "Altria Group Inc.", "MarketCap": 110.0e9},
{"Asset": "NWN", "Weight": 0.14, "Label": "Northwest Natural Gas", "MarketCap": 1.8e9},
{"Asset": "BKH", "Weight": 0.01, "Label": "Black Hills Corp.", "MarketCap": 4.5e9},
{"Asset": "ED", "Weight": 0.01, "Label": "Con Edison", "MarketCap": 30.0e9},
{"Asset": "PEP", "Weight": 0.09, "Label": "PepsiCo Inc.", "MarketCap": 255.0e9},
{"Asset": "NFG", "Weight": 0.16, "Label": "National Fuel Gas", "MarketCap": 5.6e9},
{"Asset": "KO", "Weight": 0.06, "Label": "Coca-Cola Company", "MarketCap": 275.0e9},
{"Asset": "FRT", "Weight": 0.28, "Label": "Federal Realty Inv. Trust", "MarketCap": 9.8e9},
{"Asset": "GPC", "Weight": 0.16, "Label": "Genuine Parts Co.", "MarketCap": 25.3e9},
{"Asset": "MSEX", "Weight": 0.05, "Label": "Middlesex Water Co.", "MarketCap": 2.4e9}
]
asset_table = pd.DataFrame(asset_data)
capital = 100_000
asset_table['Portfolio'] = asset_table['Weight'] * capital
ANALYSIS_START_DATE = RiskOptima.get_previous_year_date(RiskOptima.get_previous_working_day(), 1)
ANALYSIS_END_DATE = RiskOptima.get_previous_working_day()
BENCHMARK_INDEX = 'SPY'
RISK_FREE_RATE = 0.05
NUMBER_OF_WEIGHTS = 10_000
NUMBER_OF_MC_RUNS = 1_000
```
### Example 1: Creating a Portfolio Area Chart
If you want to know visually how's your portfolio doing right now
```python
RiskOptima.create_portfolio_area_chart(
asset_table,
end_date=ANALYSIS_END_DATE,
lookback_days=2,
title="Portfolio Area Chart"
)
```

### Example 2: Efficient Frontier - Monte Carlo Portfolio Optimization
```python
RiskOptima.plot_efficient_frontier_monte_carlo(
asset_table,
start_date=ANALYSIS_START_DATE,
end_date=ANALYSIS_END_DATE,
risk_free_rate=RISK_FREE_RATE,
num_portfolios=NUMBER_OF_WEIGHTS,
market_benchmark=BENCHMARK_INDEX,
set_ticks=False,
x_pos_table=1.15, # Position for the weight table on the plot
y_pos_table=0.52, # Position for the weight table on the plot
title=f'Efficient Frontier - Monte Carlo Simulation {ANALYSIS_START_DATE} to {ANALYSIS_END_DATE}'
)
```

### Example 3: Portfolio Optimization using Mean Variance and Machine Learning
```python
RiskOptima.run_portfolio_optimization_mv_ml(
asset_table=asset_table,
training_start_date='2022-01-01',
training_end_date='2023-11-27',
model_type='Linear Regression',
risk_free_rate=RISK_FREE_RATE,
num_portfolios=100000,
market_benchmark=[BENCHMARK_INDEX],
max_volatility=0.25,
min_weight=0.03,
max_weight=0.2
)
```

### Example 4: Portfolio Optimization using Probability Analysis
```python
RiskOptima.run_portfolio_probability_analysis(
asset_table=asset_table,
analysis_start_date=ANALYSIS_START_DATE,
analysis_end_date=ANALYSIS_END_DATE,
benchmark_index=BENCHMARK_INDEX,
risk_free_rate=RISK_FREE_RATE,
number_of_portfolio_weights=NUMBER_OF_WEIGHTS,
trading_days_per_year=RiskOptima.get_trading_days(),
number_of_monte_carlo_runs=NUMBER_OF_MC_RUNS
)
```

### Example 54: Macaulay Duration
```
from riskoptima import RiskOptima
cf = RiskOptima.bond_cash_flows_v2(4, 1000, 0.06, 2) # 2 years, semi-annual, hence 4 periods
md_2 = RiskOptima.macaulay_duration_v3(cf, 0.05, 2)
md_2
```

## Documentation
For complete documentation and usage examples, visit the GitHub repository:
[RiskOptima GitHub](https://github.com/JordiCorbilla/RiskOptima)
## Contributing
We welcome contributions! If you'd like to improve the package or report issues, please visit the GitHub repository.
## License
RiskOptima is licensed under the MIT License.
### Support me
<a href="https://www.buymeacoffee.com/jordicorbilla" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>
Raw data
{
"_id": null,
"home_page": "https://github.com/JordiCorbilla/RiskOptima",
"name": "riskoptima",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.11",
"maintainer_email": null,
"keywords": "portfolio, risk, optimization, VaR, CVaR, backtesting, monte-carlo, machine-learning, random-forest, linear-regression, gradient-boosting, mean-variance, black-litterman, stochastic-volatility, option-pricing, black-scholes, heston-model, merton-jump-diffusion, efficient-frontier, financial-modeling, quantitative-finance",
"author": "Jordi Corbilla",
"author_email": "jordi.coll.corbilla@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/ac/04/b6b32cea28ef08a2b651c6d558430e41e095d35316768ee2b4a8ecce95c1/riskoptima-1.24.0.tar.gz",
"platform": null,
"description": "# RiskOptima\n\n\n\n\nRiskOptima is a comprehensive Python toolkit for evaluating, managing, and optimizing investment portfolios. This package is designed to empower investors and data scientists by combining financial risk analysis, backtesting, mean-variance optimization, and machine learning capabilities into a single, cohesive package.\n\n## Stats\nhttps://pypistats.org/packages/riskoptima\n\n## Key Features\n\n- Portfolio Optimization: Includes mean-variance optimization, efficient frontier calculation, and maximum Sharpe ratio portfolio construction.\n- Risk Management: Compute key financial risk metrics such as Value at Risk (VaR), Conditional Value at Risk (CVaR), volatility, and drawdowns.\n- Backtesting Framework: Simulate historical performance of investment strategies and analyze portfolio dynamics over time.\n- Machine Learning Integration: Future-ready for implementing machine learning models for predictive analytics and advanced portfolio insights.\n- Monte Carlo Simulations: Perform extensive simulations to analyze potential portfolio outcomes. See example here https://github.com/JordiCorbilla/efficient-frontier-monte-carlo-portfolio-optimization\n- Comprehensive Financial Metrics: Calculate returns, Sharpe ratios, covariance matrices, and more.\n\n## Installation\n\nSee the project here: https://pypi.org/project/riskoptima/\n\n```\npip install riskoptima\n```\n## Usage\n\n### Example 1: Setting up your portfolio\n\nCreate your portfolio table similar to the below:\n\n| Asset | Weight | Label | MarketCap |\n|-------|--------|-------------------------------|-----------|\n| MO | 0.04 | Altria Group Inc. | 110.0e9 |\n| NWN | 0.14 | Northwest Natural Gas | 1.8e9 |\n| BKH | 0.01 | Black Hills Corp. | 4.5e9 |\n| ED | 0.01 | Con Edison | 30.0e9 |\n| PEP | 0.09 | PepsiCo Inc. | 255.0e9 |\n| NFG | 0.16 | National Fuel Gas | 5.6e9 |\n| KO | 0.06 | Coca-Cola Company | 275.0e9 |\n| FRT | 0.28 | Federal Realty Inv. Trust | 9.8e9 |\n| GPC | 0.16 | Genuine Parts Co. | 25.3e9 |\n| MSEX | 0.05 | Middlesex Water Co. | 2.4e9 |\n\n```python\nimport pandas as pd\nfrom riskoptima import RiskOptima\n\nimport warnings\nwarnings.filterwarnings(\n \"ignore\", \n category=FutureWarning, \n message=\".*DataFrame.std with axis=None is deprecated.*\"\n)\n\n# Define your current porfolio with your weights and company names\nasset_data = [\n {\"Asset\": \"MO\", \"Weight\": 0.04, \"Label\": \"Altria Group Inc.\", \"MarketCap\": 110.0e9},\n {\"Asset\": \"NWN\", \"Weight\": 0.14, \"Label\": \"Northwest Natural Gas\", \"MarketCap\": 1.8e9},\n {\"Asset\": \"BKH\", \"Weight\": 0.01, \"Label\": \"Black Hills Corp.\", \"MarketCap\": 4.5e9},\n {\"Asset\": \"ED\", \"Weight\": 0.01, \"Label\": \"Con Edison\", \"MarketCap\": 30.0e9},\n {\"Asset\": \"PEP\", \"Weight\": 0.09, \"Label\": \"PepsiCo Inc.\", \"MarketCap\": 255.0e9},\n {\"Asset\": \"NFG\", \"Weight\": 0.16, \"Label\": \"National Fuel Gas\", \"MarketCap\": 5.6e9},\n {\"Asset\": \"KO\", \"Weight\": 0.06, \"Label\": \"Coca-Cola Company\", \"MarketCap\": 275.0e9},\n {\"Asset\": \"FRT\", \"Weight\": 0.28, \"Label\": \"Federal Realty Inv. Trust\", \"MarketCap\": 9.8e9},\n {\"Asset\": \"GPC\", \"Weight\": 0.16, \"Label\": \"Genuine Parts Co.\", \"MarketCap\": 25.3e9},\n {\"Asset\": \"MSEX\", \"Weight\": 0.05, \"Label\": \"Middlesex Water Co.\", \"MarketCap\": 2.4e9}\n]\nasset_table = pd.DataFrame(asset_data)\n\ncapital = 100_000\n\nasset_table['Portfolio'] = asset_table['Weight'] * capital\n\nANALYSIS_START_DATE = RiskOptima.get_previous_year_date(RiskOptima.get_previous_working_day(), 1)\nANALYSIS_END_DATE = RiskOptima.get_previous_working_day()\nBENCHMARK_INDEX = 'SPY'\nRISK_FREE_RATE = 0.05\nNUMBER_OF_WEIGHTS = 10_000\nNUMBER_OF_MC_RUNS = 1_000\n```\n\n### Example 1: Creating a Portfolio Area Chart\n\nIf you want to know visually how's your portfolio doing right now\n\n```python\nRiskOptima.create_portfolio_area_chart(\n asset_table,\n end_date=ANALYSIS_END_DATE,\n lookback_days=2,\n title=\"Portfolio Area Chart\"\n)\n```\n\n\n### Example 2: Efficient Frontier - Monte Carlo Portfolio Optimization\n```python\nRiskOptima.plot_efficient_frontier_monte_carlo(\n asset_table,\n start_date=ANALYSIS_START_DATE,\n end_date=ANALYSIS_END_DATE,\n risk_free_rate=RISK_FREE_RATE,\n num_portfolios=NUMBER_OF_WEIGHTS,\n market_benchmark=BENCHMARK_INDEX,\n set_ticks=False,\n x_pos_table=1.15, # Position for the weight table on the plot\n y_pos_table=0.52, # Position for the weight table on the plot\n title=f'Efficient Frontier - Monte Carlo Simulation {ANALYSIS_START_DATE} to {ANALYSIS_END_DATE}'\n)\n```\n\n\n### Example 3: Portfolio Optimization using Mean Variance and Machine Learning\n```python\nRiskOptima.run_portfolio_optimization_mv_ml(\n asset_table=asset_table,\n training_start_date='2022-01-01',\n training_end_date='2023-11-27',\n model_type='Linear Regression', \n risk_free_rate=RISK_FREE_RATE,\n num_portfolios=100000,\n market_benchmark=[BENCHMARK_INDEX],\n max_volatility=0.25,\n min_weight=0.03,\n max_weight=0.2\n)\n```\n\n\n### Example 4: Portfolio Optimization using Probability Analysis\n```python\nRiskOptima.run_portfolio_probability_analysis(\n asset_table=asset_table,\n analysis_start_date=ANALYSIS_START_DATE,\n analysis_end_date=ANALYSIS_END_DATE,\n benchmark_index=BENCHMARK_INDEX,\n risk_free_rate=RISK_FREE_RATE,\n number_of_portfolio_weights=NUMBER_OF_WEIGHTS,\n trading_days_per_year=RiskOptima.get_trading_days(),\n number_of_monte_carlo_runs=NUMBER_OF_MC_RUNS\n)\n```\n\n\n### Example 54: Macaulay Duration\n```\nfrom riskoptima import RiskOptima\ncf = RiskOptima.bond_cash_flows_v2(4, 1000, 0.06, 2) # 2 years, semi-annual, hence 4 periods\nmd_2 = RiskOptima.macaulay_duration_v3(cf, 0.05, 2)\nmd_2\n```\n\n\n## Documentation\n\nFor complete documentation and usage examples, visit the GitHub repository:\n\n[RiskOptima GitHub](https://github.com/JordiCorbilla/RiskOptima)\n\n## Contributing\n\nWe welcome contributions! If you'd like to improve the package or report issues, please visit the GitHub repository.\n\n## License\n\nRiskOptima is licensed under the MIT License.\n\n### Support me\n\n<a href=\"https://www.buymeacoffee.com/jordicorbilla\" target=\"_blank\"><img src=\"https://cdn.buymeacoffee.com/buttons/default-orange.png\" alt=\"Buy Me A Coffee\" height=\"41\" width=\"174\"></a>\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "RiskOptima is a powerful Python toolkit for financial risk analysis, portfolio optimization, and advanced quantitative modeling. It integrates state-of-the-art methodologies, including Monte Carlo simulations, Value at Risk (VaR), Conditional VaR (CVaR), Black-Scholes, Heston, and Merton Jump Diffusion models, to aid investors in making data-driven investment decisions.",
"version": "1.24.0",
"project_urls": {
"Homepage": "https://github.com/JordiCorbilla/RiskOptima",
"Repository": "https://github.com/JordiCorbilla/RiskOptima"
},
"split_keywords": [
"portfolio",
" risk",
" optimization",
" var",
" cvar",
" backtesting",
" monte-carlo",
" machine-learning",
" random-forest",
" linear-regression",
" gradient-boosting",
" mean-variance",
" black-litterman",
" stochastic-volatility",
" option-pricing",
" black-scholes",
" heston-model",
" merton-jump-diffusion",
" efficient-frontier",
" financial-modeling",
" quantitative-finance"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "b037288344e7837ed32af40fafd062b57dc8d84a88b91cc49c83eec28ea57aa3",
"md5": "0866d6c3141552a585efc6947401fc99",
"sha256": "5dc65cf548a74a8305419e7c2a587803124de5491a4d2abbb7dbd7b3c24af19c"
},
"downloads": -1,
"filename": "riskoptima-1.24.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "0866d6c3141552a585efc6947401fc99",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.11",
"size": 35489,
"upload_time": "2025-02-16T19:26:08",
"upload_time_iso_8601": "2025-02-16T19:26:08.572184Z",
"url": "https://files.pythonhosted.org/packages/b0/37/288344e7837ed32af40fafd062b57dc8d84a88b91cc49c83eec28ea57aa3/riskoptima-1.24.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "ac04b6b32cea28ef08a2b651c6d558430e41e095d35316768ee2b4a8ecce95c1",
"md5": "09de23452c591e2144c1b6e50a93f8b8",
"sha256": "505f2d546e5d56d3af70c00278745ff6be8fa1af58b1bdf37cb1921c16519622"
},
"downloads": -1,
"filename": "riskoptima-1.24.0.tar.gz",
"has_sig": false,
"md5_digest": "09de23452c591e2144c1b6e50a93f8b8",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.11",
"size": 37244,
"upload_time": "2025-02-16T19:26:10",
"upload_time_iso_8601": "2025-02-16T19:26:10.974770Z",
"url": "https://files.pythonhosted.org/packages/ac/04/b6b32cea28ef08a2b651c6d558430e41e095d35316768ee2b4a8ecce95c1/riskoptima-1.24.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-02-16 19:26:10",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "JordiCorbilla",
"github_project": "RiskOptima",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "riskoptima"
}