Portfolio Management, Analysis, and Optimization using Python-1

Amit Kumar Jha
7 min readDec 12, 2022

--

Portfolio management selects the right mix of investments to achieve specific goals. Python is a popular language for implementing portfolio management strategies due to its robust data analysis and visualization libraries.

To implement portfolio management using python, you would need to gather data on the investments you want to include in your portfolios, such as their historical prices and performance metrics. This data can be obtained from finance websites or stock exchanges.

Once you have the data, you can use python’s libraries, such as Pandas and NumPy to clean and analyze the data. You can then use data visualization libraries such as Matplotlib and Seaborn to create charts and plots that help you understand the performance of your investments and identify potential areas for improvement.

Based on your analysis, you can develop a portfolio management strategy that considers factors such as your investments’ expected returns, risks, and correlations. This can involve techniques such as diversification, rebalancing, and asset allocation.

To automate the execution of your portfolio management strategy, you can use python to create algorithms that make buy and sell decisions based on your system and the current market conditions. These algorithms can be run regularly, daily or weekly, to keep your portfolio aligned with your investment goals.

What if I tell you, you can do all these things within five lines of code in Python? Sounds exciting? Yes, it’s possible using the EMPYRIAL framework. In this first part, I will illustrate how you can do backtesting using this fantastic framework.

Empyrial:

In formally published in Mars 2021, Empyrial is a Python-based open-source quantitative investing library aimed at financial institutions and retail investors. Empyrial, which is now utilized by thousands of professionals in the banking sector, aspires to become a one-stop shop for portfolio management, analysis, and optimization.
By combining the best of performance and risk analysis in a simple, adaptable, and practical framework, Empyrial enables portfolio management.
You may quickly examine security or a portfolio using Empyrial to gain the most valuable insights.

Installation

You can install Empyrial using pip:

pip install empyrial

For a better experience, I advise you to use Empyrial on a notebook (Jupyter, Google Colab…)

Working

from empyrial import empyrial, Engine
portfolio = Engine(    
start_date= "2018-01-01", #start date for the backtesting
portfolio= ["IRCTC.NS", "RELIANCE.NS", "INFY.NS", "HDFCBANK.NS"], #assets in your portfolio
weights = [0.2, 0.2, 0.2, 0.2], #equal weighting is set by default
benchmark = ["^NSEI"] #NIFTY50 is set by default
)

Engine function arguments

start_date: start date for the backtesting (format: YYYY/MM/DD)
end_date: end date for the backtesting. The end date is by default today's date. (format: YYYY/MM/DD)
portfolio: assets you invest in (tickers in a list)
weights: allocation of the capital in every asset (proportion in a list). The default allocation is equal weighting.
benchmark: the benchmark for the backtesting. SPY is the default benchmark.
optimizer: portfolio optimizer used to allocate capital in your strategy.
rebalance: rebalance frequency (for calendar rebalancing) or custom rebalance dates (in a list, format: YYYY/MM/DD)
max_vol: max level of volatility for the Mean-Variance ("MEANVAR") optimizer only. The default value is 0.15.
diversification: level of diversification in the allocation (works with every optimizer except Efficient Frontier, "EF"). The default value is 1.
max_weights: maximum proportion of capital you can invest in a single asset.
min_weights: minimum proportion of capital you can invest in a single asset.
risk_manager: risk management for your strategy (Stop Loss, Take Profit, Max Drawdown).

empyrial

Getting the stats and back testing data

empyrial(portfolio)

After executing the above code, you’ll get the output stats as the value of each , metrics

Annual return 23.69% Cumulative return 179.91% Annual volatility 16.51 % Winning day ratio 54.59% Sharpe ratio 1.37 Calmar ratio 0.68 Information ratio 0.0 Stability 0.94 Max Drawdown-34.26 % Sortino ratio 1.97 Skew-0.63 Kurtosis 8.68 Tail Ratio 1.19 Common sense ratio 1.53 Daily value at risk-2.0 % Alpha 0.13 Beta0.71

Cumulative vs Benchmark

Cumulative return is the total return of an investment or portfolio over a given period, including any income, dividends, and capital gains. A benchmark is a standard or point of reference against which the performance of a security, mutual fund, or investment manager can be measured.

The cumulative return of an investment or portfolio is calculated by taking the initial value of the investment and adding any income, dividends, or capital gains earned over a given period. This total is then divided by the initial value of the investment and multiplied by 100 to express the return as a percentage. For example, if an asset has an initial value of $10,000 and earns a total of $500 in dividends over a year, the cumulative return would be 5% ($500 / $10,000 x 100).

A benchmark is typically a well-known market index, such as the NIFTY50 or the Dow Jones Industrial Average, that is used as a standard against which the performance of an investment or portfolio can be measured. The cumulative return of an investment or portfolio can be compared to its benchmark to see whether it has outperformed or underperformed the market as a whole.

EOY vs Benchmark

End-of-year return is the total return of an investment or portfolio at the end of a given year. This is calculated by taking the initial value of the investment and adding any income, dividends, or capital gains earned over the course of the year. This total is then divided by the initial value of the investment and multiplied by 100 to express the return as a percentage.

Underwater plot

The maximum drawdown is a popular measure of the full amount an investor can expect to lose. It is used as a measure of the riskiness of a trading strategy.
Another measure of a trading strategy’s riskiness is the Time under Water.
The Term underwater is derived from the calculation of the drawdown. It is the maximum distance in time from a previous peak to a new peak. In other words, it calculates how long it takes an investor to recover their money at the start of the maximum drawdown period.

Monthly Returns

Monthly returns refer to the amount of profit or loss that an investment has generated over one month. These returns can be calculated by dividing the profit or loss by the initial investment and multiplying by 100 to express the result as a percentage.

Worst five drawdown periods

A drawdown period, also known as a “drawdown” or a “drawdown event,” is a period of time during which an investment experiences a decline in value. This can happen for a variety of reasons, including market volatility, changes in economic conditions, or other factors. The length of a drawdown period can vary, and it is typically measured from the time when an investment reaches its peak value until it reaches its lowest point, known as the “trough.” During a drawdown period, an investor may experience losses, but it is important to remember that investments can recover and may eventually return to or even exceed their previous peak values.

Rolling Volatility

Rolling volatility is a measure of the short-term fluctuations in the value of an investment over a specific period of time. It is calculated by taking the average of the differences between the daily closing price of an investment and its average closing price over a given period, such as 20 trading days. Rolling volatility is commonly used to assess the level of risk associated with an investment, and it can be compared to the volatility of other investments or to market benchmarks to determine how much an investment is likely to fluctuate in value. Higher rolling volatility generally indicates a higher level of risk, while lower rolling volatility may indicate a lower level of risk.

Rolling Sharpe

The rolling Sharpe ratio measures an investment’s performancerelative to its risk over a specific period. It is calculated by dividing the investment’s excess return over a given period (such as one month) by its rolling volatility over the same period. The Sharpe ratio is commonly used to evaluate an investment’s performance andcompare the performance of different investments. A higher rolling Sharpe ratio indicates that an asset has performed well relative to its level of risk. In comparison,a lower rolling Sharpe ratio may suggest that the investment has not performed as well as expected, given its level of risk.

In the next part, we’ll try portfolio optimization using various methodologies like mean-risk, black letterman, etc.

I hope you liked this part; get the code here and follow me on GitHub as well as on medium: https://github.com/AIM-IT4

Thank you :)

--

--

Amit Kumar Jha

Risk Quant at UBS, MS from Indian Institute of Technology Jodhpur