Package: pymarkowitz
PymarkowitzPymarkowitzis an open source library for implementing portfolio optimisation. This library extends beyond the classical mean-variance optimization and takes into account a variety of risk and reward metrics, as well as the skew/kurtosis of assets.Pymarkowitzcan aid your decision-making in portfolio allocation in a risk-efficient manner. Pymarkowitz covers major objectives and constraints related with major types of risk and reward metrics, as well as simulation to examine the relationship between all these metrics. The flexibility in its implementation gives you the maximum discretion to customize and suit it to your own needs.*Disclaimer: This library is for educational and entertainment purpose only. Please invest with due diligence at your own risk.Head over to the directorydemosto get an in-depth look at the project and its functionalities, or continue below to check out some brief examples.Table of ContentsInstallationFeaturesReferenceLicenseInstallationSetupinstall directly using pip$pipinstallpymarkowitzinstall from github$pipinstallgit+https://github.com/johnsoong216/pymarkowitz.gitDevelopmentFor development purposes you can clone or fork the repo and hack right away!$gitclonehttps://github.com/johnsoong216/pymarkowitz.gitFeaturesPreprocessingOptimizationSimulationBacktestingPreprocessingFirst step is to import all availble modulesimportnumpyasnpimportpandasaspdfrompymarkowitzimport*Read data with pandas. The dataset is available in thedatasetsdirectory. I will select 15 random stocks with 1000 observationssp500=pd.read_csv("datasets/sp500_1990_2000.csv",index_col='DATE').drop(["Unnamed: 0"],axis=1)selected=sp500.iloc[:1000,np.random.choice(np.arange(0,sp500.shape[1]),15,replace=False)]Use a ReturnGenerator to compute historical mean return and daily return. Note that there are a variety of options to compute rolling/continuous/discrete returns. Please refer to theReturn.ipynbjupyter notebook indemodirectoryret_generator=ReturnGenerator(selected)mu_return=ret_generator.calc_mean_return(method='geometric')daily_return=ret_generator.calc_return(method='daily')Use a MomentGenerator to compute covariance/coskewness/cokurtosis matrix and beta. Note that there are a variety of options to compute the comoment matrix and asset beta, such as with semivariance, exponential and customized weighting. Normalizing matrices are also supported. Please refer to theMoment(Covariance).ipynbjupyter notebook indemodirectorybenchmark=sp500.iloc[:1000].pct_change().dropna(how='any').sum(axis=1)/sp500.shape[1]cov_matrix=mom_generator.calc_cov_mat()beta_vec=mom_generator.calc_beta(benchmark)Construct higher moment matrices by callingcoskew_matrix=mom_generator.calc_coskew_mat()cokurt_matrix=mom_generator.calc_cokurt_mat()coseventh_matrix=mom_generator.calc_comoment_mat(7)Construct an OptimizerPortOpt=Optimizer(mu_return,cov_matrix,beta_vec)OptimizationPlease refer to theOptimization.ipynbjupyter notebook indemodirectory for more detailed explanations.Set your Objective.### Call PortOpt.objective_options() to look at all available objectivesPortOpt.add_objective("min_volatility")Set your Constraints.### Call PortOpt.constraint_options() to look at all available constraints.PortOpt.add_constraint("weight",weight_bound=(-1,1),leverage=1)# Portfolio Long/ShortPortOpt.add_constraint("concentration",top_holdings=2,top_concentration=0.5)# Portfolio ConcentrationSolve and Check SummaryPortOpt.solve()weight_dict,metric_dict=PortOpt.summary(risk_free=0.015,market_return=0.07,top_holdings=2)# Metric Dict Sample Output{'Expected Return':0.085,'Leverage':1.0001,'Number of Holdings':5,'Top 2 Holdings Concentrations':0.5779,'Volatility':0.1253,'Portfolio Beta':0.7574,'Sharpe Ratio':0.5586,'Treynor Ratio':0.0924,"Jenson's Alpha":0.0283}# Weight Dict Sample Output{'GIS':0.309,'CINF':0.0505,'USB':0.104,'HES':0.2676,'AEP':0.269}SimulationSimulate and Select the Return Format (Seaborn, Plotly, DataFrame). DataFrame Option will also have the random weights used in each iteration.Please refer to theSimulation.ipynbjupyter notebook indemodirectory for more detailed explanations.### Call Portopt.metric_options to see all available options for x, y axisPortOpt.simulate(x='expected_return',y='sharpe',y_var={"risk_free":0.02},iters=10000,weight_bound=(-1,1),leverage=1,ret_format='sns')BacktestingUsepymarkowitzto construct optimized weights and backtest with real life portfolio.
In this example, I am using SPDR sector ETFs to construct an optimized portfolio and compare against buy & hold SPY.importbtdata=bt.get('spy, rwr, xlb, xli, xly, xlp, xle, xlf, xlu, xlv, xlk',start='2005-01-01')The configurations can be adjusted flexibly, please check backtesting.ipynb in demo directory for more detail. In this case we are minimizing volatility with a capped weight of 25% on each sector.strategy=WeighMarkowitz(Config)#Imported from pymarkowitz.backtester.py# Personal Strategys1=bt.Strategy('s1',[bt.algos.RunWeekly(),bt.algos.SelectAll(),strategy,bt.algos.Rebalance()])test1=bt.Backtest(s1,data)# Buy & Holds2=bt.Strategy('s2',[bt.algos.RunWeekly(),bt.algos.SelectAll(),bt.algos.WeighEqually(),bt.algos.Rebalance()])test2=bt.Backtest(s2,data[['spy']].iloc[Config.lookback:])res=bt.run(test1,test2)res.plot()ReferenceCalculations ofCorrelation, Diversifcation & Risk Parity Factors:https://investresolve.com/file/pdf/Portfolio-Optimization-Whitepaper.pdfCalculations forSharpe, Sortino, Beta, Treynor, Jenson's Alpha:https://www.cfainstitute.org/-/media/documents/support/programs/investment-foundations/19-performance-evaluation.ashx?la=en&hash=F7FF3085AAFADE241B73403142AAE0BB1250B311https://www.investopedia.com/terms/j/jensensmeasure.asphttps://www.investopedia.com/ask/answers/070615/what-formula-calculating-beta.aspCalculations forHigher Moment Matrices:https://cran.r-project.org/web/packages/PerformanceAnalytics/vignettes/EstimationComoments.pdfLicenseMIT licenseCopyright 2020 ©