Maximize Your Returns: How to use CAPM with Markowitz for Stocks Beating Benchmark (40%+ returns) Part — 1

--

Capital Asset pricing Model with Markowitz Model on Indian Stocks with 2.4 Sharpe Ratio and 40% Est. returns.

Introduction

Welcome readers. In this article, we will delve into the world of investing and explore how statistical approaches, such as the Markowitz Model in association with the Capital Asset Pricing Model (CAPM), can be used to minimize risk and maximize returns.

We will take a closer look at stocks, stock markets, fundamental analysis, and the Modern Portfolio Theory, with a specific focus on Indian stocks that have achieved a Sharpe Ratio of 2 or higher, which is considered to be a good investment benchmark.

Additionally, we will examine how these principles can be applied to other types of investments, such as US stocks, cryptocurrency, and bonds in the upcoming parts of this article as extension.

The goal of this article is to provide readers with a comprehensive understanding of these concepts and how they can be implemented in real-world scenarios.

what are stocks?

Stocks, also known as equities, represent ownership in a publicly traded company. When you purchase a stock, you become a shareholder of the company and have a claim on a portion of its assets and earnings. Stocks can be bought and sold on stock exchanges, such as the New York Stock Exchange (NYSE) and the NASDAQ.

How to Invest in Stocks?

To invest in stocks, an individual can open a brokerage account with a firm that offers trading services. Once the account is opened, the individual can deposit funds and start researching and buying stocks. It is important to have a clear investment strategy, diversify portfolio and regularly review and adjust it as per the market conditions.

here are some examples of famous international and Indian brokerage firms:

International:

  1. Charles Schwab
  2. Fidelity Investments
  3. E-Trade Financial
  4. TD Ameritrade
  5. Morgan Stanley

India:

  1. Kotak Securities
  2. ICICI Securities
  3. Groww
  4. Zerodha
  5. Sharekhan

These are just a few examples and there are many more brokerage firms in the market. It’s important to research and compare different firms to find one that best suits your investment needs and preferences. Factors to consider include fees, account minimums, available investment options, research and tools, and customer service.

Advantages of stock market investment compared to other asset investments

Stock market investments offer several advantages over other types of investments. One of the main advantages is the potential for higher returns. Historically, stocks have provided higher returns than bonds or other fixed-income investments over the long term. In addition, stocks offer liquidity, which means they can be easily bought and sold, and they also provide a way to participate in the growth of the economy.

How many stocks are there in BSE and NSE of Indian stock market

As of 2021, there are around 5,500 stocks listed on the Bombay Stock Exchange (BSE) and around 1,800 stocks listed on the National Stock Exchange (NSE) of India.

How relevant it is to invest in stocks with less risk and more return compared to traditional investments

Investing in stocks with less risk and more return can be achieved by diversifying the portfolio, investing in blue chip companies with stable revenue and by performing a thorough research and analysis of the company before investing in it. The risk can be further reduced by investing in index funds and ETFs which track the performance of the market as a whole.

What is “fundamental analysis” and key fundamental analysis that most financial analysts use in general

Fundamental analysis is a method of evaluating a company by analyzing its financial and economic fundamentals, such as its revenue, earnings, and assets. It aims to understand the underlying value of a company, and assess its future growth prospects, by examining its financial statements, industry trends and other qualitative and quantitative factors. Some key fundamental analysis that most financial analysts use include:

  1. Earnings per Share (EPS): This measures the company’s net income per outstanding share of stock, which is an indicator of profitability. A higher EPS indicates that the company is generating more profits per share of stock, and is therefore more attractive to investors.
  2. Price to Earnings Ratio (P/E): This measures the company’s stock price in relation to its earnings, which is an indicator of how expensive or inexpensive the stock is. A lower P/E ratio indicates that the stock is undervalued, and may be a good buying opportunity.
  3. Price to Sales Ratio (P/S): This measures the company’s stock price in relation to its revenue, which is an indicator of how well the company is generating sales. A lower P/S ratio indicates that the company is generating more revenue per share of stock, and is therefore more attractive to investors.
  4. Debt to Equity Ratio (D/E): This measures the company’s debt in relation to its equity, which is an indicator of the company’s financial leverage and risk. A lower D/E ratio indicates that the company has less debt and is therefore less risky.
  5. Return on Equity (ROE): This measures the company’s net income as a percentage of its shareholder equity, which is an indicator of how efficiently the company is using its assets to generate profits. A higher ROE indicates that the company is generating more profits per dollar of shareholder equity, and is therefore more attractive to investors.
  6. Price to Book Ratio (PB ratio): This measures the company’s stock price in relation to its book value, which is the value of its assets minus its liabilities. It is calculated by dividing the current market price per share by the book value per share. A lower PB ratio indicates that the stock is undervalued and a higher PB ratio indicates that the stock is overvalued.
  7. Alpha: Alpha is a measure of a stock or portfolio’s performance in relation to its benchmark index, such as the S&P 500/NIFTY. It is a risk-adjusted measure of the stock’s returns, and is calculated by subtracting the benchmark index’s return from the stock’s return. A positive Alpha value indicates that the stock has performed better than the benchmark index, while a negative Alpha value indicates that the stock has performed worse than the benchmark index.
  8. Beta: Beta is a measure of a stock’s volatility in relation to the overall market. It is calculated by comparing the stock’s returns to the returns of a benchmark index, such as the S&P 500/NIFTY. A Beta value of 1 indicates that the stock’s returns are closely correlated with the benchmark index, while a Beta value greater than 1 indicates that the stock is more volatile than the benchmark index, and a Beta value less than 1 indicates that the stock is less volatile than the benchmark index. A stock with a higher beta value is considered riskier than one with a lower beta value.
  9. EBITDA: EBITDA stands for Earnings Before Interest, Taxes, Depreciation, and Amortization. It is a financial metric that calculates a company’s earnings before taking into account certain expenses. The idea behind EBITDA is to measure a company’s profitability without the impact of financing and accounting decisions, as well as non-cash expenses.

EBITDA is calculated by adding back interest, taxes, depreciation, and amortization to net income. The formula is: EBITDA = Net Income + Interest + Taxes + Depreciation + Amortization

EBITDA can be useful for investors and analysts to compare a company’s profitability across different time periods or against its peers, as it eliminates the effects of financing and accounting decisions. It can also be used as a measure of a company’s cash flow from its operations, as it removes the effects of capital expenditures and debt.

However, it’s important to note that EBITDA is not a recognized financial measure under Generally Accepted Accounting Principles (GAAP) and it should not be considered as an alternative to net income or cash flow from operations as a measure of a company’s profitability or liquidity. EBITDA also ignores the cost of capital and can be manipulated by companies to make their performance look better. Therefore, it should be used in conjunction with other financial metrics and not as the sole indicator of a company’s financial health.

Formula for EPS, PE, PS, DE, ROE, PB, Alpha, Beta, EBITDA:

Earnings per Share (EPS): EPS = Net Income / Outstanding Shares

  • EPS is a measure of a company’s profitability, as it shows how much net income the company is generating per share of stock. A higher EPS indicates that the company is generating more profits per share of stock, and is therefore more attractive to investors.

Price to Earnings Ratio (P/E): P/E = Market Price per Share / Earnings per Share

  • The P/E ratio is a measure of how expensive or inexpensive a stock is in relation to its earnings. A lower P/E ratio indicates that the stock is undervalued, and may be a good buying opportunity.

Price to Sales Ratio (P/S): P/S = Market Price per Share / Revenue per Share

  • The P/S ratio is a measure of how well a company is generating sales, it shows how much the market is willing to pay for each dollar of revenue generated by the company. A lower P/S ratio indicates that the company is generating more revenue per share of stock, and is therefore more attractive to investors.

Debt to Equity Ratio (D/E): D/E = Total Debt / Shareholder’s Equity

  • The D/E ratio is a measure of a company’s financial leverage and risk, it shows the proportion of a company’s financing that comes from debt versus equity. A lower D/E ratio indicates that the company has less debt and is therefore less risky.

Return on Equity (ROE): ROE = Net Income / Shareholder’s Equity

  • ROE measures the efficiency of a company in generating profits from every unit of shareholder’s equity, it indicates how well a company is using its assets to generate profits. A higher ROE indicates that the company is generating more profits per dollar of shareholder equity, and is therefore more attractive to investors.

Price to Book Ratio (PB ratio): PB ratio = Market price per share / Book value per share

  • The PB ratio is a measure of a company’s stock price in relation to its book value, which is the value of its assets minus its liabilities. A lower PB ratio indicates that the stock is undervalued and a higher PB ratio indicates that the stock is overvalued.

Alpha: Alpha = (Stock’s return — Benchmark index’s return)

  • Alpha is a measure of a stock or portfolio’s performance in relation to its benchmark index, such as the S&P 500. A positive Alpha value indicates that the stock has performed better than the benchmark index, while a negative Alpha value indicates that the stock has performed worse than the benchmark index.

Beta: Beta = Covariance(Stock returns, Benchmark returns) / Variance(Benchmark returns)

  • Beta is a measure of a stock’s volatility in relation to the overall market. A Beta value of 1 indicates that the stock’s returns are closely correlated with the benchmark index, while a Beta value greater than 1 indicates that the stock is more volatile than the benchmark index, and a Beta value less than 1 indicates that the stock is less volatile than the benchmark index. A stock with a higher beta value is considered riskier than one with a lower beta value.

EBITDA: EBITDA = Net Income + Interest + Taxes + Depreciation + Amortization

  • EBITDA is a financial metric that calculates a company’s earnings before taking into account certain expenses. It aims to measure a company’s profitability without the impact of financing and accounting decisions, as well as non-cash expenses.

It’s important to mention that these formulas are the basic way of calculating these ratios, and the actual calculation may vary depending on the data and the method used. The values of these ratios can be used as a relative indicator to compare the performance and relative value of a stock against the market or its peers. But, as with any financial ratio, it’s important to use them in context and not solely rely on them to make investment decisions.

How tickertape website can be used for fundamental analysis ?

Ticker tape website can be used for fundamental analysis by providing historical financial data such as stock prices, revenues, earnings, dividends, and other financial metrics. Additionally, it can also provide news and analysis on the company and its industry, as well as data on insider trading and institutional ownership.

link: https://www.tickertape.in/screener/equity

What is Markowitz Model

The Markowitz Model is a mathematical framework that helps in constructing portfolios that maximize expected return for a given level of risk or minimize risk for a given level of expected return. The basic steps to implement the Markowitz model include defining the set of assets to be included in the portfolio, estimating the expected return and volatility of each asset, calculating the covariance matrix of returns between all pairs of assets, and using a mathematical optimization algorithm to find the optimal portfolio weights.

The Markowitz model and Modern Portfolio Theory (MPT) are closely related, but not identical. The Markowitz model, developed by Harry Markowitz in the 1950s, is a mathematical framework for constructing portfolios that maximize expected return for a given level of risk, or minimize risk for a given level of expected return. MPT is a broader theory that incorporates the Markowitz model as well as other concepts, such as diversification and the Capital Asset Pricing Model (CAPM).

Both the Markowitz model and MPT are still widely used in the field of finance and investment management. The basic steps for implementing the Markowitz model are as follows:

  1. Define the set of assets to be included in the portfolio
  2. Estimate the expected return and volatility (standard deviation) of each asset
  3. Calculate the covariance matrix of returns between all pairs of assets
  4. Use a mathematical optimization algorithm to find the portfolio weights that optimize the portfolio’s expected return for a given level of risk, or minimize risk for a given level of expected return
  5. Rebalance the portfolio as needed to maintain the optimal weights

Here is an example of Python code that implements the Markowitz model:

import numpy as np
from scipy.optimize import minimize
# Define the set of assets
assets = ['Asset 1', 'Asset 2', 'Asset 3']
# Estimate expected returns and volatilities
expected_returns = np.array([0.1, 0.2, 0.15])
volatilities = np.array([0.15, 0.25, 0.20])
# Calculate the covariance matrix of returns
cov_matrix = np.array([[0.025, 0.01, 0.0075],
[0.01, 0.0625, 0.005],
[0.0075, 0.005, 0.04]])
# Define a function to minimize risk for a given level of expected return
def portfolio_risk(weights, return_target):
portfolio_return = np.sum(weights * expected_returns)
portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
return portfolio_volatility
# Define the optimization constraints
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1},
{'type': 'ineq', 'fun': lambda x: np.dot(x, expected_returns) - return_target})
# Set the initial guess for the portfolio weights
initial_guess = [1/3, 1/3, 1/3]
# Set the return target
return_target = 0.18
# Minimize the risk for the given return target
optimal_weights = minimize(portfolio_risk, initial_guess, args=return_target, constraints=constraints)
# Print the optimal portfolio weights
print(optimal_weights.x)

MPT is a more general framework, which takes into account the diversification and the Capital Asset Pricing Model (CAPM) as well as correlation matrix. It is used to create efficient frontier of portfolios and the optimum portfolio is selected based on the risk-return trade-off.

MPT, CAPM and how markowitz can be used for CAPM with example

Modern Portfolio Theory (MPT) is a broader theory that incorporates the Markowitz model as well as other concepts, such as diversification and the Capital Asset Pricing Model (CAPM). The MPT helps in creating an efficient frontier of portfolios and the optimum portfolio is selected based on the risk-return trade-off. Using the CAPM with the Markowitz Model helps in reducing the risk and maximizing returns by incorporating the beta of the assets and the expected market return in the optimization process.

The Capital Asset Pricing Model (CAPM) is a theory that describes the relationship between the expected return of an investment and its systematic risk. The model states that an investor should expect to earn a higher return on an investment as compensation for the higher risk that the investment entails. The formula for the CAPM is:

Expected return = Risk-free rate + (Expected market return — Risk-free rate) * Beta

Where:

  • Risk-free rate is the return on a risk-free investment, such as a Treasury bond
  • Expected market return is the average return of the overall market
  • Beta is a measure of an investment’s systematic risk, or its sensitivity to the market as a whole

The Markowitz model can be used in conjunction with the CAPM to construct portfolios that optimize expected return for a given level of risk. The basic steps are as follows:

  1. Estimate the expected return, volatility, and beta for each asset
  2. Use the CAPM formula to estimate the required return for each asset
  3. Use the Markowitz model to find the portfolio weights that optimize the portfolio’s expected return for a given level of risk

Here is an example of Python code that implements the Markowitz model with the CAPM:

import numpy as np
from scipy.optimize import minimize
# Define the set of assets
assets = ['Asset 1', 'Asset 2', 'Asset 3']
# Estimate expected returns, volatilities, and betas
expected_returns = np.array([0.1, 0.2, 0.15])
volatilities = np.array([0.15, 0.25, 0.20])
betas = np.array([1.2, 1.0, 0.8])
# Set the risk-free rate and expected market return
risk_free_rate = 0.03
expected_market_return = 0.1
# Calculate the required returns using the CAPM formula
required_returns = risk_free_rate + (expected_market_return - risk_free_rate) * betas
# Calculate the covariance matrix of returns
cov_matrix = np.array([[0.025, 0.01, 0.0075],
[0.01, 0.0625, 0.005],
[0.0075, 0.005, 0.04]])
# Define a function to minimize risk for a given level of expected return
def portfolio_risk(weights, return_target):
portfolio_return = np.sum(weights * required_returns)
portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
return portfolio_volatility
# Define the optimization constraints
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1},
{'type': 'ineq', 'fun': lambda x: np.dot(x, required_returns) - return_target})
# Set the initial guess for the portfolio weights
initial_guess = [1/3, 1/3, 1/3]
# Set the return target
return_target = 0.18
# Minimize the risk for the given return target
optimal_weights = minimize(portfolio_risk, initial_guess, args=return_target, constraints=constraints)

Steps I Followed

Step — 1:

Browsed into tickertape screener and added above mentioned fundamental analysis filters with certain ranges and we got 15 short listed stocks after the analysis is done using the platform.

tickertape screener to do fundamental analysis and short list Indian stocks as needed
tickertape screener to do fundamental analysis and short list Indian stocks as needed

Step — 2:

Browsed into Yahoo finance link — https://finance.yahoo.com/quote/SPLPETRO.NS?p=SPLPETRO.NS&.tsrc=fin-srch

and added related stock names in to the code

stocks = [ 'GORANIN.BO', 'BRPL.BO', 'RITESHIN.BO', 'SHISHIND.BO', 'GOLKUNDIA.BO', 'CRSTCHM.BO', 'UVDRHOR.BO', 'GARGFUR.BO', 'BRADYM.BO', 'RAMAPPR-B.BO', 'ORIENTTR.BO', 'RATNABHUMI.BO' ]

Step — 3:

Considered trading days as 252 in a year and taken 10000 random portfolio generate with different weights on each stock which sums up to 100% overall.

# on average there are 252 trading days in a year
NUM_TRADING_DAYS = 252
# we will generate random w (different portfolios)
NUM_PORTFOLIOS = 10000

considered start_date and end_date of 5 years data

# historical data - define START and END dates
start_date = '2017-12-31'
end_date = '2022-12-31'

imported few libraries to run the operations and downloaded data using yahoo finance tikcer, scipy to calculate optimum results through random generation of various results through optimize_portfolio method and the below shows what I used for plotting and normalizing the whole data of various stocks into single comparable metrics calculate_return(data)

import numpy as np
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import scipy.optimize as optimization

def download_data():
# name of the stock (key) - stock values (2010-1017) as the values
stock_data = {}

for stock in stocks:
# closing prices
ticker = yf.Ticker(stock)
stock_data[stock] = ticker.history(start=start_date, end=end_date)['Close']

return pd.DataFrame(stock_data)


def show_data(data):
data.plot(figsize=(10, 5))
plt.show()


def calculate_return(data):
# NORMALIZATION - to measure all variables in comparable metric
log_return = np.log(data / data.shift(1))
return log_return[1:]


def show_statistics(returns):
# instead of daily metrics we are after annual metrics
# mean of annual return
print(returns.mean() * NUM_TRADING_DAYS)
print(returns.cov() * NUM_TRADING_DAYS)


def show_mean_variance(returns, weights):
# we are after the annual return
portfolio_return = np.sum(returns.mean() * weights) * NUM_TRADING_DAYS
portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(returns.cov()
* NUM_TRADING_DAYS, weights)))
print("Expected portfolio mean (return): ", portfolio_return)
print("Expected portfolio volatility (standard deviation): ", portfolio_volatility)


def show_portfolios(returns, volatilities):
plt.figure(figsize=(10, 6))
plt.scatter(volatilities, returns, c=returns / volatilities, marker='o')
plt.grid(True)
plt.xlabel('Expected Volatility')
plt.ylabel('Expected Return')
plt.colorbar(label='Sharpe Ratio')
plt.show()

generate_portfolios(returns) method is used to identify mean, risk level through variance and possible weights suitable for each stock

def generate_portfolios(returns):
portfolio_means = []
portfolio_risks = []
portfolio_weights = []

for _ in range(NUM_PORTFOLIOS):
w = np.random.random(len(stocks))
w /= np.sum(w)
portfolio_weights.append(w)
portfolio_means.append(np.sum(returns.mean() * w) * NUM_TRADING_DAYS)
portfolio_risks.append(np.sqrt(np.dot(w.T, np.dot(returns.cov()
* NUM_TRADING_DAYS, w))))

return np.array(portfolio_weights), np.array(portfolio_means), np.array(portfolio_risks)
def statistics(weights, returns):
portfolio_return = np.sum(returns.mean() * weights) * NUM_TRADING_DAYS
portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(returns.cov()
* NUM_TRADING_DAYS, weights)))
return np.array([portfolio_return, portfolio_volatility,
portfolio_return / portfolio_volatility])


# scipy optimize module can find the minimum of a given function
# the maximum of a f(x) is the minimum of -f(x)
def min_function_sharpe(weights, returns):
return -statistics(weights, returns)[2]


# what are the constraints? The sum of weights = 1 !!!
# f(x)=0 this is the function to minimize
def optimize_portfolio(weights, returns):
# the sum of weights is 1
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
# the weights can be 1 at most: 1 when 100% of money is invested into a single stock
bounds = tuple((0, 1) for _ in range(len(stocks)))
return optimization.minimize(fun=min_function_sharpe, x0=weights[0], args=returns
, method='SLSQP', bounds=bounds, constraints=constraints)


def print_optimal_portfolio(optimum, returns):
print(f"Optimal portfolio: {optimum['x'].round(4)*100}%" )
print("Expected return, volatility and Sharpe ratio: ",
statistics(optimum['x'].round(3), returns))


def show_optimal_portfolio(opt, rets, portfolio_rets, portfolio_vols):
plt.figure(figsize=(10, 6))
plt.scatter(portfolio_vols, portfolio_rets, c=portfolio_rets / portfolio_vols, marker='o')
plt.grid(True)
plt.xlabel('Expected Volatility')
plt.ylabel('Expected Return')
plt.colorbar(label='Sharpe Ratio')
plt.plot(statistics(opt['x'], rets)[1], statistics(opt['x'], rets)[0], 'g*', markersize=20.0)
plt.show()

as given in comments, have deduced possible return based on data and volatility is calculated using covariance matrix with weights combined. Sharpe ratio is “portfolio_return / portfolio_volatility”

The key constraint to notice is , sum of all the assets is always 1 (i.e; 100%)

Final Step:

run all the methods to get graph and also result as shown below in command prompt. We can also run it on jupiter or google colab notebook, I preferred to run it directly through command prompt on my windows laptop.

Normalized Distribution using log returns
Normalized Distribution using log returns
Expected Returns Vs Expected Volatility compared to Sharpe Ratio
Expected Returns Vs Expected Volatility compared to Sharpe Ratio

Result:

Optimal portfolio: [11.15  0.   13.12 10.71  8.62  9.11 11.49 15.01  6.66  4.03  9.19  0.92]%
Expected return, volatility and Sharpe ratio: [0.40539076 0.1668275 2.42999966]

Conclusion:

From the above execution it is clear that

Returns = 40.54% (Approximate)

Volatility = 16.68% (Approximate)

Sharpe Ratio = 2.43 (Approximate)

Portfolio Return:

‘GORANIN.BO’ = 11.15%,

‘BRPL.BO’ = 0,

‘RITESHIN.BO’ = 13.12%,

‘SHISHIND.BO’ = 10.71%,

‘GOLKUNDIA.BO’ = 8.62%,

‘CRSTCHM.BO’ = 9.11%,

‘UVDRHOR.BO’ = 11.49%,

‘GARGFUR.BO’ = 15.01%,

‘BRADYM.BO’ = 6.66%,

‘RAMAPPR-B.BO’ = 4.03%,

‘ORIENTTR.BO’ = 9.12%,

‘RATNABHUMI.BO’ = 0.92%

as we can observe that, one of the stocks portfolio weight has shown 0%, through the calculations, sometimes to reduce the possible risk factor, few stocks will be given 0%.

The main goal of Markoqitz Model is to reduce risks through low volatility and higher returns. and We have considered stocks with low Beta value while choosing them on tickertape compelling to CAMP process.

Sp, by combining both the methods, we got higher Sharpe Ratio of 2.4+ with returns of 40%+ annual by beating the market benchmark returns.

I hope you have found this article on financial analytics to be informative and helpful. As a creator, I am dedicated to providing valuable insights and analysis on the cryptocurrency, stock market and other assets management.

If you have enjoyed this article and would like to support my ongoing efforts, I would be honored to have you as a member of my Patreon community. As a member, you will have access to exclusive content, early access to new analysis, and the opportunity to be a part of shaping the direction of my research.

Membership starts at just $4, and you can choose to contribute on a monthly basis. Your support will help me to continue to produce high-quality content and bring you the latest insights on financial analytics.

Patreon https://patreon.com/pppicasso

Thank you Readers.

Regards,

Puranam Pradeep Picasso

Linkedin — https://www.linkedin.com/in/puranampradeeppicasso/

Patreon — https://patreon.com/pppicasso

Facebook — https://www.facebook.com/puranam.p.picasso/

Twitter — https://twitter.com/picasso_999

--

--

Puranam Pradeep Picasso - ImbueDesk Profile

Algorithmic Trader, AI/ML & Crypto Enthusiast, Certified Blockchain Architect, Certified Lean Six SIgma Green Belt, Certified SCRUM Master and Entrepreneur