### Install yfinance for examples Source: https://github.com/dcajasn/riskfolio-lib/blob/master/docs/source/riskfoliolib/install.md Install the yfinance library using pip. This is required to run certain examples that utilize historical stock data. ```bash pip install yfinance ``` -------------------------------- ### Install vectorbt for backtesting Source: https://github.com/dcajasn/riskfolio-lib/blob/master/docs/source/riskfoliolib/install.md Install the vectorbt library using pip. This is required for running the backtesting examples. ```bash pip install vectorbt ``` -------------------------------- ### Install Target Description Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/CMakeLists.txt Describes the 'install' target, including header installation paths and how to customize them. ```cmake message(STATUS "install | Install Eigen. Headers will be installed to:") message(STATUS " | /") message(STATUS " | Using the following values:") message(STATUS " | CMAKE_INSTALL_PREFIX: ${CMAKE_INSTALL_PREFIX}") message(STATUS " | INCLUDE_INSTALL_DIR: ${INCLUDE_INSTALL_DIR}") message(STATUS " | Change the install location of Eigen headers using:") message(STATUS " | cmake . -DCMAKE_INSTALL_PREFIX=yourprefix") message(STATUS " | Or:") message(STATUS " | cmake . -DINCLUDE_INSTALL_DIR=yourdir") ``` -------------------------------- ### Build and Run Example Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/spectra-1.0.1/examples/DavidsonSymEigs_example.md Commands to build and run the DavidsonSymEigs example from source. ```bash mkdir build && cd build && cmake ../ make DavidsonSymEigs_example ./example/DavidsonSymEigs_example ``` -------------------------------- ### Loop Through Example Sources and Build Executables Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/unsupported/doc/examples/CMakeLists.txt Iterates through each found example source file, creates an executable for it, links necessary libraries, and sets up a post-build command to run the example and capture its output. ```cmake foreach(example_src ${examples_SRCS}) get_filename_component(example ${example_src} NAME_WE) add_executable(example_${example} ${example_src}) if(EIGEN_STANDARD_LIBRARIES_TO_LINK_TO) target_link_libraries(example_${example} ${EIGEN_STANDARD_LIBRARIES_TO_LINK_TO}) endif() add_custom_command( TARGET example_${example} POST_BUILD COMMAND example_${example} ARGS >${CMAKE_CURRENT_BINARY_DIR}/${example}.out ) add_dependencies(unsupported_examples example_${example}) endforeach(example_src) ``` -------------------------------- ### Install Pybind11 Source: https://github.com/dcajasn/riskfolio-lib/blob/master/docs/source/riskfoliolib/install.md Install Pybind11 using pip. This is a prerequisite for installing Riskfolio-Lib. ```bash pip install pybind11 ``` -------------------------------- ### Install Riskfolio-Lib Source: https://github.com/dcajasn/riskfolio-lib/blob/master/docs/source/riskfoliolib/install.md Install the Riskfolio-Lib package using pip. Ensure Python 3.10 or higher is installed. ```bash pip install riskfolio-lib ``` -------------------------------- ### Configuring Example Executables with Spectra Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/spectra-1.0.1/examples/CMakeLists.txt This snippet shows how to define and build example executables from C++ source files, ensuring they are linked against the Spectra library. It's useful for setting up a build system for library examples. ```cmake set(example_target_sources) list(APPEND example_target_sources DavidsonSymEigs_example.cpp ) foreach(EXAMPLE_SOURCE ${example_target_sources}) # Extract the filename without extension (NAME_WE) as a name for our executable get_filename_component(EXAMPLE_NAME ${EXAMPLE_SOURCE} NAME_WE) # Add an executable based on the source add_executable(${EXAMPLE_NAME} ${EXAMPLE_SOURCE}) # Configure (include headers and link libraries) the example target_link_libraries(${EXAMPLE_NAME} PRIVATE Spectra) endforeach() ``` -------------------------------- ### Portfolio Construction and Optimization Example Source: https://github.com/dcajasn/riskfolio-lib/blob/master/docs/source/riskfoliolib/plot.md This example demonstrates how to download historical data, calculate returns, create a portfolio object, estimate asset statistics, and perform various portfolio optimizations including Sharpe ratio maximization, efficient frontier construction, and risk parity for both assets and factors. It uses historical data for mean and covariance estimation. ```Python import numpy as np import pandas as pd import yfinance as yf import riskfolio as rp # Date range start = '2016-01-01' end = '2019-12-30' # Tickers of assets assets = ['JCI', 'TGT', 'CMCSA', 'CPB', 'MO', 'APA', 'MRSH', 'JPM', 'ZION', 'PSA', 'BAX', 'BMY', 'LUV', 'PCAR', 'TXT', 'TMO', 'DE', 'MSFT', 'HPQ', 'SEE', 'VZ', 'CNP', 'NI', 'T', 'BA'] assets.sort() # Tickers of factors factors = ['MTUM', 'QUAL', 'VLUE', 'SIZE', 'USMV'] factors.sort() tickers = assets + factors tickers.sort() # Downloading the data data = yf.download(tickers, start = start, end = end) data = data.loc[:,('Adj Close', slice(None))] data.columns = tickers returns = data.pct_change().dropna() Y = returns[assets] X = returns[factors] # Creating the Portfolio Object port = rp.Portfolio(returns=Y) # To display dataframes values in percentage format pd.options.display.float_format = '{:.4%}'.format # Choose the risk measure rm = 'MSV' # Semi Standard Deviation # Estimate inputs of the model (historical estimates) method_mu='hist' # Method to estimate expected returns based on historical data. method_cov='hist' # Method to estimate covariance matrix based on historical data. port.assets_stats(method_mu=method_mu, method_cov=method_cov) mu = port.mu cov = port.cov # Estimate the portfolio that maximizes the risk adjusted return ratio w1 = port.optimization(model='Classic', rm=rm, obj='Sharpe', rf=0.0, l=0, hist=True) # Estimate points in the efficient frontier mean - semi standard deviation ws = port.efficient_frontier(model='Classic', rm=rm, points=20, rf=0, hist=True) # Estimate the risk parity portfolio for semi standard deviation w2 = port.rp_optimization(model='Classic', rm=rm, rf=0, b=None, hist=True) # Estimate the risk parity portfolio for semi standard deviation w2 = port.rp_optimization(model='Classic', rm=rm, rf=0, b=None, hist=True) # Estimate the risk parity portfolio for risk factors port.factors = X port.factors_stats(method_mu=method_mu, method_cov=method_cov, feature_selection='stepwise', stepwise='Forward') w3 = port.rp_optimization(model='FC', rm='MV', rf=0, b_f=None) # Estimate the risk parity portfolio for principal components port.factors = X port.factors_stats(method_mu=method_mu, method_cov=method_cov, feature_selection='PCR', n_components=0.95) w4 = port.rp_optimization(model='FC', rm='MV', rf=0, b_f=None) wb = pd.DataFrame(np.ones((len(assets), 1))/len(assets), index=assets) ``` -------------------------------- ### Install MOSEK solver Source: https://github.com/dcajasn/riskfolio-lib/blob/master/docs/source/riskfoliolib/install.md Install the MOSEK solver using pip. This is necessary for specific optimization problems handled by Riskfolio-Lib. Refer to MOSEK's official documentation for detailed installation and licensing. ```bash pip install mosek ``` -------------------------------- ### Install Spectra using CMake Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/spectra-1.0.1/README.md Provides CMake commands for installing the Spectra library headers. It specifies the installation prefix, the path to Eigen3, and enables build tests. ```bash mkdir build && cd build cmake .. -DCMAKE_INSTALL_PREFIX='intended installation directory' -DCMAKE_PREFIX_PATH='path where the installation of Eigen3 can be found' -DBUILD_TESTS=TRUE make all && make tests && make install ``` -------------------------------- ### Configure and Install Pkgconfig File Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/CMakeLists.txt If `EIGEN_BUILD_PKGCONFIG` is enabled, this snippet configures the `eigen3.pc.in` template and installs the resulting `eigen3.pc` file to the specified pkgconfig directory. ```cmake if(EIGEN_BUILD_PKGCONFIG) configure_file(eigen3.pc.in eigen3.pc @ONLY) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/eigen3.pc DESTINATION ${PKGCONFIG_INSTALL_DIR} ) endif() ``` -------------------------------- ### Comma-Initializer Syntax Example Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/TutorialMatrixClass.dox Shows how to initialize matrix and vector coefficients using the comma-initializer syntax. ```C++ #include #include int main() { Matrix2d a; a << 1, 2, 3, 4; std::cout << a << std::endl; return 0; } ``` -------------------------------- ### Project and Demo Target Setup Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/demos/CMakeLists.txt Initializes the EigenDemos project and defines a custom target named 'demos'. This is a standard CMake setup for a project. ```cmake project(EigenDemos) add_custom_target(demos) ``` -------------------------------- ### Output of Example 1: Basic Matrix Indexing Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/CustomizingEigen_NullaryExpr.dox The output produced by the first indexing example, showing the selected submatrix. ```text Indexed matrix (main1): 1 3 4 11 13 14 ``` -------------------------------- ### Discover and Build Eigen Examples Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/examples/CMakeLists.txt This snippet uses CMake's GLOB command to find all C++ source files in the current directory and then iterates through them to create an executable for each. It includes logic for linking standard libraries and setting up post-build custom commands to execute the compiled examples and redirect their output. ```cmake file(GLOB examples_SRCS "*.cpp") foreach(example_src ${examples_SRCS}) get_filename_component(example ${example_src} NAME_WE) add_executable(${example} ${example_src}) if(EIGEN_STANDARD_LIBRARIES_TO_LINK_TO) target_link_libraries(${example} ${EIGEN_STANDARD_LIBRARIES_TO_LINK_TO}) endif() add_custom_command( TARGET ${example} POST_BUILD COMMAND ${example} ARGS >${CMAKE_CURRENT_BINARY_DIR}/${example}.out ) add_dependencies(all_examples ${example}) endforeach() ``` -------------------------------- ### Matrix and Array Type Conversion Example Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/QuickReference.dox A placeholder example showing the declaration of matrix and array objects, implying potential for conversion or interaction between them. ```c++ Array44f a1, a2; Matrix4f m1, m2; ``` -------------------------------- ### Find Example Source Files Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/unsupported/doc/examples/CMakeLists.txt Uses the GLOB command to find all .cpp files in the examples directory. This is a common pattern for collecting source files in CMake. ```cmake file(GLOB examples_SRCS "*.cpp") ``` -------------------------------- ### Install Eigen Signature File Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/CMakeLists.txt Installs the `signature_of_eigen3_matrix_library` file to the specified include directory as part of the 'Devel' component. ```cmake install(FILES signature_of_eigen3_matrix_library DESTINATION ${INCLUDE_INSTALL_DIR} COMPONENT Devel ) ``` -------------------------------- ### Output of Example 2: Indexing with Expressions Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/CustomizingEigen_NullaryExpr.dox The output from the second indexing example, demonstrating the result of using expressions for row and column indices. ```text Indexed matrix (main2): 1 3 4 11 13 14 Indexed matrix with expressions (main2): 1 3 4 11 13 14 ``` -------------------------------- ### Matrix and Vector Operations (Fixed Size) Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/QuickStartGuide.dox Demonstrates creating and manipulating matrices and vectors with sizes determined at compile time. This example focuses on fixed-size declarations and operations, complementing the dynamic-size example. ```cpp #include #include int main() { Eigen::Matrix m; m = Eigen::Matrix::Random(); m = (m + Eigen::Matrix::Constant(1.2)) * 5; Eigen::Vector v; v << 1, 2, 3; std::cout << "m = " << std::endl << m << std::endl << std::endl; std::cout << "v = " << std::endl << v << std::endl << std::endl; std::cout << "m * v = " << std::endl << m * v << std::endl; return 0; } ``` -------------------------------- ### Matrix Block Operations Example Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/TutorialBlockOperations.dox Illustrates the usage of various matrix block operations. ```cpp #include #include int main() { Eigen::MatrixXf matrix(4,4); matrix << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15; std::cout << "topRightCorner(2,2):\n" << matrix.topRightCorner(2,2) << "\n\n"; std::cout << "bottomRows(2):\n" << matrix.bottomRows(2) << "\n\n"; std::cout << "leftCols<2>():\n" << matrix.leftCols<2>() << "\n\n"; return 0; } ``` ```text topRightCorner(2,2): 2 3 6 7 10 11 14 15 bottomRows(2): 8 9 10 11 12 13 14 15 leftCols<2>(): 0 1 4 5 8 9 12 13 ``` -------------------------------- ### Column-Major Storage Example Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/StorageOrders.dox Demonstrates the memory layout of a matrix stored in column-major order. ```cpp #include #include int main() { Eigen::Matrix Acolmajor; Acolmajor << 8, 2, 2, 9, 9, 1, 4, 4, 3, 5, 4, 5; std::cout << "Acolmajor:\n" << Acolmajor << std::endl; std::cout << "Acolmajor.data(): "; for (int i = 0; i < Acolmajor.size(); ++i) { std::cout << Acolmajor.data()[i] << " "; } std::cout << std::endl; Eigen::Matrix Arowmajor; Arowmajor << 8, 2, 2, 9, 9, 1, 4, 4, 3, 5, 4, 5; std::cout << "Arowmajor:\n" << Arowmajor << std::endl; std::cout << "Arowmajor.data(): "; for (int i = 0; i < Arowmajor.size(); ++i) { std::cout << Arowmajor.data()[i] << " "; } std::cout << std::endl; Acolmajor = Arowmajor; std::cout << "Acolmajor = Arowmajor:\n" << Acolmajor << std::endl; std::cout << "Acolmajor.data(): "; for (int i = 0; i < Acolmajor.size(); ++i) { std::cout << Acolmajor.data()[i] << " "; } std::cout << std::endl; return 0; } ``` -------------------------------- ### GDB Backtrace Example Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/UnalignedArrayAssert.dox Demonstrates how to obtain a backtrace using GDB to identify the source of the assertion failure in your own code. ```bash $ gdb ./my_program # Start GDB on your program > run # Start running your program ... # Now reproduce the crash! > bt # Obtain the backtrace ``` -------------------------------- ### Get Riskfolio-Lib Version Source: https://github.com/dcajasn/riskfolio-lib/blob/master/examples/Tutorial 16 - Riskfolio-Lib Reports in Jupyter Notebook and Excel.ipynb Retrieves the installed version of the Riskfolio-Lib library. Useful for checking compatibility or reporting issues. ```python rp.__version__ ``` -------------------------------- ### Run Backtest and Plot Results Source: https://github.com/dcajasn/riskfolio-lib/blob/master/examples/Tutorial 5 - Multi Assets Algorithmic Trading Backtesting with Backtrader.ipynb Executes a backtest using the defined benchmark and strategy. It configures matplotlib for plotting and specifies the start and end periods for the backtest. Requires `backtrader` and `matplotlib` to be installed. ```python %matplotlib inline import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (10, 6) # (w, h) plt.plot() # We need to do this to avoid errors in inline plot start = 1004 end = prices.shape[0] - 1 dd, cagr, sharpe = backtest([benchmark], BuyAndHold, start=start, end=end, plot=True) ``` -------------------------------- ### Setting Up Portfolio Optimization Parameters Source: https://github.com/dcajasn/riskfolio-lib/blob/master/examples/Tutorial 37 - OWA Portfolio Optimization.ipynb Configure the solver, risk measure, objective function, and other parameters for portfolio optimization. This setup is crucial before running the optimization algorithms. ```python port.solvers = ['MOSEK'] port.sol_params = {'MOSEK': {'mosek_params': {mosek.iparam.num_threads: 2}}} alpha = 0.05 port.alpha = alpha model ='Classic' rms = ['CVaR', 'WR'] objs = ['MinRisk', 'Sharpe'] hist = True rf = 0 l = 0 ``` -------------------------------- ### Install CMake Configuration Files Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/CMakeLists.txt Installs necessary CMake configuration files for Eigen to the package installation directory. ```cmake install ( FILES ${CMAKE_CURRENT_SOURCE_DIR}/cmake/UseEigen3.cmake ${CMAKE_CURRENT_BINARY_DIR}/Eigen3Config.cmake ${CMAKE_CURRENT_BINARY_DIR}/Eigen3ConfigVersion.cmake DESTINATION ${CMAKEPACKAGE_INSTALL_DIR} ) ``` -------------------------------- ### Install Riskfolio-XL Package Source: https://github.com/dcajasn/riskfolio-lib/blob/master/docs/source/riskfolioxl/excel.md Install the latest stable release of Riskfolio-XL from PyPI using pip. This command is used after PyXLL has been installed. ```bash pip install riskfolio-xl ``` -------------------------------- ### Example 1: Basic Matrix Indexing Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/CustomizingEigen_NullaryExpr.dox Demonstrates basic usage of the indexing function to select specific rows and columns from a matrix. ```C++ #include #include // Include the indexing_functor and indexing function definitions here int main() { Eigen::MatrixXd m(4, 5); m << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19; Eigen::VectorXi rows(2); rows << 0, 2; Eigen::VectorXi cols(3); cols << 1, 3, 4; auto indexed_m = indexing(m, rows, cols); std::cout << "Indexed matrix (main1):\n" << indexed_m << std::endl; return 0; } ``` -------------------------------- ### Build Optimum Portfolio and Generate Reports Source: https://github.com/dcajasn/riskfolio-lib/blob/master/docs/source/riskfoliolib/reports.md This example demonstrates how to build an optimum portfolio and generate both a Jupyter Notebook and an Excel report. It includes data downloading, portfolio object creation, and optimization based on specified risk measures and objectives. ```python import numpy as np import pandas as pd import yfinance as yf import riskfolio as rp yf.pdr_override() # Date range start = '2016-01-01' end = '2019-12-30' # Tickers of assets tickers = ['JCI', 'TGT', 'CMCSA', 'CPB', 'MO', 'APA', 'MRSH', 'JPM', 'ZION', 'PSA', 'BAX', 'BMY', 'LUV', 'PCAR', 'TXT', 'TMO', 'DE', 'MSFT', 'HPQ', 'SEE', 'VZ', 'CNP', 'NI', 'T', 'BA'] tickers.sort() # Downloading the data data = yf.download(tickers, start = start, end = end) data = data.loc[:,('Adj Close', slice(None))] data.columns = tickers assets = data.pct_change().dropna() Y = assets # Creating the Portfolio Object port = rp.Portfolio(returns=Y) # To display dataframes values in percentage format pd.options.display.float_format = '{:.4%}'.format # Choose the risk measure rm = 'MV' # Standard Deviation # Estimate inputs of the model (historical estimates) method_mu='hist' # Method to estimate expected returns based on historical data. method_cov='hist' # Method to estimate covariance matrix based on historical data. port.assets_stats(method_mu=method_mu, method_cov=method_cov) # Estimate the portfolio that maximizes the risk adjusted return ratio w = port.optimization(model='Classic', rm=rm, obj='Sharpe', rf=0.0, l=0, hist=True) ``` -------------------------------- ### Initialize Portfolio and Estimate Statistics Source: https://github.com/dcajasn/riskfolio-lib/blob/master/examples/Tutorial 58 - Mean Variance Skewness Kurtosis Optimization.ipynb Initializes a Riskfolio-Lib Portfolio object with the calculated returns and sets up methods for estimating expected returns, covariance, and kurtosis using historical data. This is a prerequisite for portfolio optimization. ```python import riskfolio as rp import mosek # Building the portfolio object port = rp.Portfolio(returns=Y) # Calculating optimum portfolio # Select method and estimate input parameters: method_mu='hist' # Method to estimate expected returns based on historical data. method_cov='hist' # Method to estimate covariance matrix based on historical data. method_kurt='hist' # Method to estimate kurtosis based on historical data. port.assets_stats(method_mu=method_mu, method_cov=method_cov, method_kurt=method_kurt, ) ``` -------------------------------- ### Install Exported Targets Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/CMakeLists.txt Installs the exported Eigen3 targets to the specified destination directory. ```cmake install (EXPORT Eigen3Targets NAMESPACE Eigen3:: DESTINATION ${CMAKEPACKAGE_INSTALL_DIR}) ``` -------------------------------- ### Dynamic-size Matrix Initialization Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/QuickReference.dox Demonstrates initializing dynamic-size Eigen matrices with specified dimensions using static factory methods and setters. ```C++ typedef {MatrixXf|ArrayXXf} Dynamic2D; Dynamic2D x; x = Dynamic2D::Zero(rows, cols); x = Dynamic2D::Ones(rows, cols); x = Dynamic2D::Constant(rows, cols, value); x = Dynamic2D::Random(rows, cols); N/A x.setZero(rows, cols); x.setOnes(rows, cols); x.setConstant(rows, cols, value); x.setRandom(rows, cols); N/A ``` -------------------------------- ### Set Pkgconfig Installation Directory Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/CMakeLists.txt Specifies the installation directory for the `eigen3.pc` pkgconfig file. ```cmake set(PKGCONFIG_INSTALL_DIR "${CMAKE_INSTALL_DATADIR}/pkgconfig" CACHE PATH "The directory relative to CMAKE_INSTALL_PREFIX where eigen3.pc is installed" ) ``` -------------------------------- ### Output of the circulant matrix example Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/CustomizingEigen_NullaryExpr.dox The expected output when the makeCirculant example program is executed. ```text Circulant matrix: 1 8 4 2 2 1 8 4 4 2 1 8 8 4 2 1 ``` -------------------------------- ### Configure Portfolio for Short Weights and Leverage Source: https://github.com/dcajasn/riskfolio-lib/blob/master/examples/Tutorial 8 - Short and Leveraged Portfolios.ipynb Sets up a portfolio object to allow short weights and leverage. Configure maximum individual short/long weights and budget constraints for short positions and overall leverage. ```python # Building the portfolio object port = rp.Portfolio(returns=Y[assets]) # Calculating optimal portfolio # Select method and estimate input parameters: method_mu='hist' # Method to estimate expected returns based on historical data. method_cov='hist' # Method to estimate covariance matrix based on historical data. port.assets_stats(method_mu=method_mu, method_cov=method_cov) # Configuring short weights options port.sht = True # Allows to use Short Weights port.uppersht = 0.3 # Maximum absolute value of individual negative weights port.upperlng = 1.3 # Maximum value of individual positive weights port.budgetsht = 0.3 # Maximum absolute value of sum of negative weights # Configuring leverage port.budget = 1.3 # Sum of all weights ``` -------------------------------- ### Sparse Matrix Initialization Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/SparseQuickReference.dox Demonstrates how to declare and initialize sparse matrices with different data types and storage orders. The default storage order is column-major. ```C++ SparseMatrix sm1(1000,1000); SparseMatrix,RowMajor> sm2; ``` -------------------------------- ### Install Eigen Target and Export Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/CMakeLists.txt Installs the Eigen target and its export set for use by other CMake projects. ```cmake install (TARGETS eigen EXPORT Eigen3Targets) ``` -------------------------------- ### Initialize Portfolio and Estimate Statistics Source: https://github.com/dcajasn/riskfolio-lib/blob/master/examples/Tutorial 17 - Riskfolio-Lib with MOSEK for Real Applications (612 assets and 4943 observations).ipynb Initializes a Riskfolio-Lib Portfolio object with historical returns and estimates expected returns and covariance matrix using historical data. MOSEK is set as the solver. ```python import riskfolio as rp # Building the portfolio object port = rp.Portfolio(returns=Y) # Calculating optimum portfolio # Select method and estimate input parameters: method_mu='hist' # Method to estimate expected returns based on historical data. method_cov='hist' # Method to estimate covariance matrix based on historical data. port.assets_stats(method_mu=method_mu, method_cov=method_cov) # Input model parameters: port.solvers = ['MOSEK'] # Setting MOSEK as the default solver # if you want to set some MOSEK params use this code as an example # import mosek # port.sol_params = {'MOSEK': {'mosek_params': {mosek.iparam.intpnt_solve_form: mosek.solveform.dual}}} port.alpha = 0.05 # Significance level for CVaR, EVaR y CDaR model='Classic' # Could be Classic (historical), BL (Black Litterman) or FM (Factor Model) obj = 'Sharpe' # Objective function, could be MinRisk, MaxRet, Utility or Sharpe hist = True # Use historical scenarios for risk measures that depend on scenarios rf = 0 # Risk free rate l = 0 # Risk aversion factor, only useful when obj is 'Utility' ``` -------------------------------- ### Initialization Lists for Small Vectors (Pre-C++11) Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/TutorialMatrixClass.dox Provides examples of initializing small fixed-size column vectors (up to size 4) using lists of coefficients, applicable before C++11. ```C++ Vector2d a(5.0, 6.0); Vector3d b(5.0, 6.0, 7.0); Vector4d c(5.0, 6.0, 7.0, 8.0); ``` -------------------------------- ### Identity Matrix Initialization Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/QuickReference.dox Shows how to create identity matrices for fixed-size types using static methods and setters. ```C++ x = FixedXD::Identity(); x.setIdentity(); ``` -------------------------------- ### Set CMake Package Installation Directory Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/CMakeLists.txt Defines the installation directory for Eigen's CMake configuration files. ```cmake set(CMAKEPACKAGE_INSTALL_DIR "${CMAKE_INSTALL_DATADIR}/eigen3/cmake" CACHE PATH "The directory relative to CMAKE_INSTALL_PREFIX where Eigen3Config.cmake is installed" ) ``` -------------------------------- ### Matrix Initialization and Assignment Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/AsciiQuickReference.txt Demonstrates initializing matrices from data and performing element-wise operations. ```C++ Matrix2i mat2x2(data); // copies data into mat2x2 ``` ```C++ Matrix2i::Map(data) = 2*mat2x2; // overwrite elements of data with 2*mat2x2 ``` ```C++ MatrixXi::Map(data, 2, 2) += mat2x2; // adds mat2x2 to elements of data (alternative syntax if size is not know at compile time) ``` -------------------------------- ### Make Absolute Paths Relative to Install Prefix Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/CMakeLists.txt Ensures that any absolute paths specified for installation directories are converted to be relative to `CMAKE_INSTALL_PREFIX`. ```cmake foreach(var INCLUDE_INSTALL_DIR CMAKEPACKAGE_INSTALL_DIR PKGCONFIG_INSTALL_DIR) # If an absolute path is specified, make it relative to "{CMAKE_INSTALL_PREFIX}". if(IS_ABSOLUTE "${${var}}") file(RELATIVE_PATH "${var}" "${CMAKE_INSTALL_PREFIX}" "${${var}}") endif() endforeach() ``` -------------------------------- ### Conditional Subdirectory for SYCL Examples Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/unsupported/doc/examples/CMakeLists.txt Conditionally includes the 'SYCL' subdirectory if the EIGEN_TEST_SYCL variable is set. This allows for building SYCL-specific examples. ```cmake if(EIGEN_TEST_SYCL) add_subdirectory(SYCL) endif(EIGEN_TEST_SYCL) ``` -------------------------------- ### Initialize Portfolio and Estimate Statistics Source: https://github.com/dcajasn/riskfolio-lib/blob/master/examples/Tutorial 57 - Mean Risk Optimization using Entropy Pooling.ipynb Initializes a Portfolio object with the calculated returns and estimates the assets' statistics (mean, covariance, kurtosis) using historical data. ```python import riskfolio as rp # Building the portfolio object port = rp.Portfolio(returns=Y) # Calculating optimal portfolio # Select method and estimate input parameters: method_mu='hist' # Method to estimate expected returns based on historical data. method_cov='hist' # Method to estimate covariance matrix based on historical data. method_kurt='hist' # Method to estimate covariance matrix based on historical data. port.assets_stats(method_mu=method_mu, method_cov=method_cov, method_kurt=method_kurt) ``` -------------------------------- ### Add Custom Target for Unsupported Examples Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/unsupported/doc/examples/CMakeLists.txt Defines a custom target named 'unsupported_examples'. This target can be used to build all unsupported examples collectively. ```cmake add_custom_target(unsupported_examples) ``` -------------------------------- ### Initialize Portfolio and Estimate Statistics Source: https://github.com/dcajasn/riskfolio-lib/blob/master/examples/Tutorial 10 - Risk Parity Portfolio Optimization.ipynb Initializes a Portfolio object from the Riskfolio library with the calculated returns and estimates the historical mean and covariance matrix. Ensure Riskfolio and its dependencies are installed. ```python import riskfolio as rp # Building the portfolio object port = rp.Portfolio(returns=Y) # Calculating optimal portfolio # Select method and estimate input parameters: method_mu='hist' # Method to estimate expected returns based on historical data. method_cov='hist' # Method to estimate covariance matrix based on historical data. port.assets_stats(method_mu=method_mu, method_cov=method_cov) ``` -------------------------------- ### Fixed-size Matrix Initialization Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/QuickReference.dox Shows how to initialize fixed-size Eigen matrices and vectors with common patterns like zero, ones, constant, random, and linear spacing. ```C++ typedef {Matrix3f|Array33f} FixedXD; FixedXD x; x = FixedXD::Zero(); x = FixedXD::Ones(); x = FixedXD::Constant(value); x = FixedXD::Random(); x = FixedXD::LinSpaced(size, low, high); x.setZero(); x.setOnes(); x.setConstant(value); x.setRandom(); x.setLinSpaced(size, low, high); ``` -------------------------------- ### Initializing 2x2 and 2x3 Matrices Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/TutorialMatrixClass.dox Shows how to construct matrices of different sizes using initializer lists of initializer lists. ```C++ MatrixXi a { // construct a 2x2 matrix {1, 2}, // first row {3, 4} // second row }; Matrix b { {2, 3, 4}, {5, 6, 7}, }; ``` -------------------------------- ### Install Eigen Header Directory Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/CMakeLists.txt Installs the entire 'Eigen' directory, containing header files, to the specified include directory as part of the 'Devel' component. ```cmake install(DIRECTORY Eigen DESTINATION ${INCLUDE_INSTALL_DIR} COMPONENT Devel) ``` -------------------------------- ### Initialize and Estimate Portfolio Statistics Source: https://github.com/dcajasn/riskfolio-lib/blob/master/examples/Tutorial 16 - Riskfolio-Lib Reports in Jupyter Notebook and Excel.ipynb Initializes a Riskfolio-Lib Portfolio object with the calculated returns and estimates the expected returns and covariance matrix using historical data. Requires the 'riskfolio' library to be installed. ```python import riskfolio as rp # Building the portfolio object port = rp.Portfolio(returns=Y) # Calculating optimal portfolio # Select method and estimate input parameters: method_mu='hist' # Method to estimate expected returns based on historical data. method_cov='hist' # Method to estimate covariance matrix based on historical data. port.assets_stats(method_mu=method_mu, method_cov=method_cov) ``` -------------------------------- ### Initialization Lists for Vectors and Matrices (C++11) Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/TutorialMatrixClass.dox Shows how to initialize fixed-size column vectors, dynamic-size matrices, and row vectors using initializer lists when C++11 is enabled. ```C++ Vector2i a(1, 2); // A column vector containing the elements {1, 2} Matrix b {1, 2, 3, 4, 5}; // A row-vector containing the elements {1, 2, 3, 4, 5} ``` -------------------------------- ### Set Eigen Header Installation Directory Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/CMakeLists.txt Configures the installation directory for Eigen header files. It prioritizes the `EIGEN_INCLUDE_INSTALL_DIR` if provided, otherwise defaults to a standard location. ```cmake if(EIGEN_INCLUDE_INSTALL_DIR AND NOT INCLUDE_INSTALL_DIR) set(INCLUDE_INSTALL_DIR ${EIGEN_INCLUDE_INSTALL_DIR} CACHE PATH "The directory relative to CMAKE_INSTALL_PREFIX where Eigen header files are installed") else() set(INCLUDE_INSTALL_DIR "${CMAKE_INSTALL_INCLUDEDIR}/eigen3" CACHE PATH "The directory relative to CMAKE_INSTALL_PREFIX where Eigen header files are installed" ) endif() ``` -------------------------------- ### Initialize Portfolio and Estimate Statistics Source: https://github.com/dcajasn/riskfolio-lib/blob/master/examples/Tutorial 7 - Index Tracking-Replicating Portfolios.ipynb Initializes a Riskfolio-Lib Portfolio object with asset returns and estimates the mean and covariance using historical data. This is a prerequisite for portfolio optimization. ```python import riskfolio as rp # Building the portfolio object port = rp.Portfolio(returns=Y[assets]) # Calculating optimal portfolio # Select method and estimate input parameters: method_mu='hist' # Method to estimate expected returns based on historical data. method_cov='hist' # Method to estimate covariance matrix based on historical data. port.assets_stats(method_mu=method_mu, method_cov=method_cov) ``` -------------------------------- ### Initializing a Column Vector Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/TutorialMatrixClass.dox Demonstrates initializing a fixed-size column vector with integer elements. ```C++ Matrix c = {1, 2, 3, 4, 5}; // A column vector containing the elements {1, 2, 3, 4, 5} ``` -------------------------------- ### BrinsonAttribution Example Source: https://github.com/dcajasn/riskfolio-lib/blob/master/docs/source/riskfoliolib/risk.md Example of how to use the BrinsonAttribution function to calculate performance attribution. Ensure 'data', 'w', 'wb', and 'asset_classes' are defined and properly formatted before use. ```python BrinAttr, (start, end) = BrinsonAttribution( prices=data, w=w, wb=wb, start='2019-01-07', end='2019-12-06', asset_classes=asset_classes, classes_col='Industry', ) ``` -------------------------------- ### Basic Benchmark Results Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/bench/README.txt Example output from the basic benchmark, showing execution times for different matrix dimensions (3x3, 4x4, Xx4, Xx20) across various compiler versions and optimization flags. ```text g++-4.1 -O3 -DNDEBUG -finline-limit=10000 3d-3x3 / 4d-4x4 / Xd-4x4 / Xd-20x20 / 0.271102 0.131416 0.422322 0.198633 0.201658 0.102436 0.397566 0.207282 g++-4.2 -O3 -DNDEBUG -finline-limit=10000 3d-3x3 / 4d-4x4 / Xd-4x4 / Xd-20x20 / 0.107805 0.0890579 0.30265 0.161843 0.127157 0.0712581 0.278341 0.191029 g++-4.3 -O3 -DNDEBUG -finline-limit=10000 3d-3x3 / 4d-4x4 / Xd-4x4 / Xd-20x20 / 0.134318 0.105291 0.3704 0.180966 0.137703 0.0732472 0.31225 0.202204 icpc -fast -DNDEBUG -fno-exceptions -no-inline-max-size 3d-3x3 / 4d-4x4 / Xd-4x4 / Xd-20x20 / 0.226145 0.0941319 0.371873 0.159433 0.109302 0.0837538 0.328102 0.173891 ``` -------------------------------- ### Minimalistic Matrix Inheritance Example Source: https://github.com/dcajasn/riskfolio-lib/blob/master/lib/eigen-3.4.0/doc/CustomizingEigen_InheritingMatrix.dox A basic example demonstrating the essential members required when inheriting from Eigen's Matrix class to ensure compatibility within the Eigen framework. ```cpp #include #include // Define a custom scalar type struct MyScalar { double val; // ... other members and methods ... }; // Inherit from Eigen::Matrix class MyMatrix : public Eigen::Matrix { public: // Required typedefs for Eigen compatibility typedef Eigen::Matrix Base; EIGEN_DYN_TYPEDEF(MyScalar) // Constructor MyMatrix(int rows, int cols) : Base(rows, cols) {} // Add custom methods or members here void printVal() const { for (int i = 0; i < rows(); ++i) { for (int j = 0; j < cols(); ++j) { std::cout << this->coeff(i, j).val << " "; } std::cout << std::endl; } } }; int main() { // Create an instance of MyMatrix MyMatrix mat(2, 2); // Initialize with custom scalar values mat.coeffRef(0, 0).val = 1.1; mat.coeffRef(0, 1).val = 1.2; mat.coeffRef(1, 0).val = 2.1; mat.coeffRef(1, 1).val = 2.2; // Use the custom method mat.printVal(); return 0; } ``` -------------------------------- ### Initialize Portfolio Object and Calculate Statistics Source: https://github.com/dcajasn/riskfolio-lib/blob/master/examples/Tutorial 15 - Mean Entropic Value at Risk (EVaR) Optimization.ipynb Initializes a Riskfolio-Lib Portfolio object with the calculated returns. It then estimates the assets' statistics (expected returns and covariance matrix) using historical data. Ensure riskfolio is installed. ```python import riskfolio as rp # Building the portfolio object port = rp.Portfolio(returns=Y) # Calculating optimum portfolio # Select method and estimate input parameters: method_mu='hist' # Method to estimate expected returns based on historical data. method_cov='hist' # Method to estimate covariance matrix based on historical data. port.assets_stats(method_mu=method_mu, method_cov=method_cov) ```