Portfolio, Asset Allocation and Stock Market Data Analysis

Ajay krishnan
10 min readFeb 24, 2022

Topic for today is stock market data analysis , we’ll discuss about different kinds of securities/assets , allocation of assets and different methods of portfolio analysis such as portfolio returns , risks, and Sharpe ratio.

So what is a portfolio ?

A portfolio is a collection of financial investments such as :

  • Stocks
  • Fixed Income Securities [bonds]
  • Cash
  • Mutual Funds
  • Exchange Traded Funds [ETFs]

Suppose are a portfolio manager and you are approached by a client who want your advice. Your client have 1-million dollars and wants to invest that with the goal of capital appreciation. What would you do ? Where would advice him to invest the money?

  • Would you advise to invest all the money in equities, like S&P500 ?
  • Would you advise to invest all the money tech-companies like google , twitter , amazon etc…
  • Bonds have low risk , so invest in bonds ?
  • How about Mutal Funds and ETFs ?

All these questions can be answered by acquiring data from the clients, like how much risk are they willing to take , What’s the time-span of investment and many other things. This is exactly what portfolio mangers do.

Asset allocation is an investment strategy that is used to allocate clients assests based on their risk tolerance , target returns and investment time span

What Is a Stock/Equity?

A stock (also known as equity) is a security that represents the ownership of a fraction of a corporation. This entitles the owner of the stock to a proportion of the corporation’s assets and profits equal to how much stock they own. Units of stock are called “shares.”

Why do people buy stocks?

Investors buy stocks for various reasons. Here are some of them:

  • Capital appreciation, which occurs when a stock rises in price
  • Dividend payments, which come when the company distributes some of its earnings to stockholders
  • Ability to vote shares and influence the company

Why do companies issue stock?

Companies issue stock to get money for various things, which may include:

  • Paying off debt
  • Launching new products
  • Expanding into new markets or regions
  • Enlarging facilities or building new ones

What kinds of stocks are there?

There are two main kinds of stocks, common stock and preferred stock.

Common stock entitles owners to vote at shareholder meetings and receive dividends.

Preferred stockholders usually don’t have voting rights but they receive dividend payments before common stockholders do, and have priority over common stockholders if the company goes bankrupt and its assets are liquidated.

What are the benefits and risks of stocks?

Stocks offer investors the greatest potential for growth (capital appreciation) over the long haul. Investors willing to stick with stocks over long periods of time, say 15 years or more, generally have been rewarded with strong, positive returns.

But stock prices move down as well as up. There’s no guarantee that the company whose stock you hold will grow and do well, so you can lose money you invest in stocks.

What happens when a company goes bankrupt?

If a company goes bankrupt and its assets are liquidated, common stockholders are the last in line to share in the proceeds. The company’s bondholders will be paid first, then holders of preferred stock. If you are a common stockholder, you get whatever is left, which may be nothing.

How to invest for a long term goal ?

Stocks usually are one part of an investor’s holdings. If you are young and saving for a long-term goal such as retirement, you may want to hold more stocks than bonds. Investors nearing or in retirement may want to hold more bonds than stocks.

The risks of stock holdings can be offset in part by investing in a number of different stocks. Investing in other kinds of assets that are not stocks, such as bonds, is another way to offset some of the risks of owning stocks.

What are the different types of Assets/Securities ?

Equities (stocks)

  • Stocks are a type of security that gives stockholders a share of ownership in a company. Stocks also are called “equities.”
  • A stock gives the owner the right to some shares in a given company depending on how much stock (share ) they own.
  • Stocks are traded on stock exchange such as Newyork Stock Exchange(NYSE) and an individual can buy them via online brokerage firms.
  • Stocks are generally liquid as compared to real estate which could take much longer time to sell

Fixed Income Securities (Bonds)

  • A fixed-income security is a debt instrument issued by a government, corporation or other entity to finance and expand their operations.
  • Bonds are fixed income that are generally issued by governments or corporations and represents a loan made by an investor to the borrower
  • Fixed Income Investments offer a stream of return on a fixed schedule. The amount of the payout could vary though.
  • One of the most common forms of Fixed Income Investments is the individual bonds.
  • Bond pay the investor a fixed interest rate.
  • Bonds are used by companies and governments to raise money to fund future project
  • Bonds are less risky when compared to stocks , but when compared to stocks which pays more interest the bonds pay less because they take out the risk factor
  • Fixed Income Securities offer a fixed rate of return with the interest getting accumulated over a predetermined period of time.
  • These can be used by investors to diversify their portfolio given these are not as risky as derivatives and equities. Because the returns in fixed income investments are reliable, it is particularly popular amongst the retired investors.

Mutual Funds

  • Essentially, the money pooled in by a large number of people (or investors) is what makes up a Mutual Fund
  • It is a trust that collects money from a number of investors who share a common investment objective.
  • Mutual Funds invests the money it pooled in equities, bonds, money market instruments and/or other securities.
  • Mutual Funds are brought directly from companies issuing shares
  • Each investor owns units, which represent a portion of the holdings of the fund.
  • The income/gains generated from this collective investment is distributed proportionately amongst the investors after deducting certain expenses, by calculating a scheme’s Net Asset Value

Exchange Traded Funds (ETF)

  • An exchange-traded fund is a type of investment fund and exchange-traded product, i.e. they are traded on stock exchanges.
  • ETFs are a type of security that includes a group of securities and possibly track and index
  • ETFs are like mutual funds however they are marketable securities and are being traded on exchanges similar to any other stock.
  • ETFs can include a collection of stocks, bonds and commodities.
  • ETFs have generally low management fees and offer a tool for risk diversification
  • ETFs allow investors to buy many stocks or bonds in certain market segments at once
  • An ETF provider owns a variety of assets, such as stocks, bonds, or commodities. The provider then creates a basket of these assets in the form of an exchange-traded fund and sells shares to investors.

Stock Market Data Analysis

Lets now look at a dataset that give us information about stock prices of different companies from 2012 to 2020. Lets check the impact of pandemic on the stock market .

stocks_df = pd.read_csv(…path to csv…)
stocks_df.head()

Lets create an interactive visualization of the data using plotly

# Interactive plots with plotly
import
plotly.express as px
fig = px.line()
for col in stock_df.columns[1:]:
fig.add_scatter(x=stock_df[‘Date’], y=stock_df[col], name=col)
fig.show()
Interactive visualization

What is Asset Allocation?

Asset allocation refers to an investment strategy in which individuals divide their investment portfolios between different diverse asset classes to minimize investment risks.
The asset classes fall into three broad categories:

  • Equities
  • Fixed income
  • Cash & equivalent.

Anything outside these three categories (e.g., real estate, commodities, art) is often referred to as alternative assets.

Factors Affecting Asset Allocation Decision

When making investment decisions, an investors’ portfolio distribution is influenced by factors such as :

  • Personal goals
  • Level of risk tolerance
  • Investment time-span or horizon.

The goal of portfolio managers is to reduce the risk and maximize the returns.
A long-term investment strategy may prompt an investor to invest in a more volatile or higher risk portfolio since the dynamics of the economy are uncertain and may change in favor of the investor. However, investors with short-term goals may not invest in riskier portfolios.

How Asset Allocation Works

Financial advisors usually advise that to reduce the level of volatility of portfolios, investors must diversify their investment into various asset classes. Such basic reasoning is what makes asset allocation popular in portfolio management because different asset classes will always provide different returns. Thus, investors will receive a shield to guard against the deterioration of their investments.

Example of Asset Allocation

Let’s say john wants to invest $10,000 for a time horizon of five years. His financial advisor may advise John to diversify his portfolio across the three major categories at a mix of 50/40/10 among stocks, bonds, and cash. His portfolio may look like below:

Stocks

  • Small-Cap Growth Stocks — 25%
  • Large-Cap Value Stocks — 15%
  • International stocks — 10%

Bonds

  • Government bonds — 15%
  • High yield bonds — 25%

Cash

  • Money market — 10%

The distribution of his investment across the three broad categories, therefore, may look like this: $5,000/$4,000/$1,000.

Simulation

We have historic data of stocks from 2012–2020. Lets suppose that one of our client had invested 10,000,00$ . Client was young and invested in popular equities after studying the market.
Securites : [AAPL, BA, T, MGM, AMZN, IBM, TSLA, GOOG, SP500]
Time-span 2012–2020

Did the client win big time or did he lose money ? Lets do some analysis using the historic data. We don’t know the actual allocation percentage, this is a simulation and we are experimenting so lets not sweat and use random values.

We will start with random weights for all those nine securities
Weights: [w1, w2, w3, w4, w5, w6, w7, w8, w9]
These weights must sums to one

The initial portfolio = Σweight*security

Now we can track the overall value of portfolio overtime from 2012 to 2020 , calculate portfolio daily returns and much more. The weights are random , so depending on the weights client may lose or win big time. The idea is to do analysis using then historic data and make intelligent decisions.

# seed
np.random.seed(42)
# create random weights
Weights = np.random.random(len(stocks_df.columns[1:]))
# make the weigts sums to one
Weights = Weights/sum(Weights)

# check wheather weights sums to one
w_sum = 0
for w in Weights:
w_sum+=w
print('Sum of Weights',w_sum)

Weight s = [ w1 , w2 , w3 …,W9 ]

We have historic data from 2012–01–12 to 2020–08–11
We have a record for every day, this is a time-series data

stocks_df.head()
historic_data = stocks_df.values[:,1:]
start = stocks_df.values[0,1:]

# lets divide the historic data with starting value
X = historic_data / start

portfolio_daily_worth = X@Weights

portfolio_daily_worth = portfolio_daily_worth*1000000
stocks_df['portfolio daily worth in $'] = portfolio_daily_worth
stocks_df.head()
portfolio daily worth in dollars

Let’s calculate the portfolio daily return

  • Subtract the opening price from the closing price.
  • Multiply the difference by the stocks you own
  • Divide the daily return by the current stock price and multiply by 100 to get a percentage.
val = stocks_df['portfolio daily worth in $'].copy().values
daily_return = [0]
for i,v in enumerate(val):
if i==0:
continue
daily_return.append(((val[i]-val[i-1])/val[i-1])*100)
stocks_df['portfolio daily % return'] = daily_return
stocks_df.head()
portfolio daily percentage return

Visualization

import plotly.express as px

fig = px.line(stocks_df, x='Date', y='portfolio daily % return', title='Portfolio daily percentage return')
fig.show()
portfolio percentage daily return
# histogram of daily % return
import plotly.express as px
fig = px.histogram(data_frame=stocks_df, x='portfolio daily % return')
fig.show()
histogram of daily % return
# 'Portfolio individual stocks worth in $ over time'
import plotly.express as px

historic_data = raw_df.copy().values[:,1:]
start = raw_df.copy().values[0,1:]
X = historic_data/start

for i in range(9):
X[:,i] = X[:,i]*Weights[i]*100

fig = px.line(title='Portfolio individual stocks worth in $ over time')
for i, col in enumerate(raw_df.columns[1:]):
fig.add_scatter(x=raw_df.Date, y=X[:,i], name=col)

fig.show()
Portfolio individual stocks worth in $ over time

What Is Cumulative Return?

A cumulative return on an investment is the aggregate amount that the investment has gained or lost over time, independent of the amount of time involved. The cumulative return is expressed as a percentage

c = Current price of security
o = Original price of security

cumulative return = (c-o)/o

What Is the Sharpe Ratio?

The Sharpe ratio was developed by Nobel laureate William F. Sharpe and is used to help investors understand the return of an investment compared to its risk. The ratio is the average return earned in excess of the risk-free rate per unit of volatility or total risk. Volatility is a measure of the price fluctuations of an asset or portfolio.

  • The Sharpe ratio adjusts a portfolio’s past performance — or expected future performance — for the excess risk that was taken by the investor.
  • A high Sharpe ratio is good when compared to similar portfolios or funds with lower returns.
  • The Sharpe ratio has several weaknesses, including an assumption that investment returns are normally distributed.
Formula sharpe ratio

Subtracting the risk-free rate from the mean return allows an investor to better isolate the profits associated with risk-taking activities.

The risk free rate of return is the return of an investment with zero risks, meaning it’s the return investors could expect for taking no risk.

mean = stocks_df['portfolio daily % return'].mean()
std = stocks_df['portfolio daily % return'].std()
sharpe_ratio = (mean/std) * np.sqrt(252)
print('Sharpe ratio of the portfolio is {}'.format(sharpe_ratio))

we want to maximize the return compared to the risk , so will try to maximize the sharpe ratio for portfolio optimization

Github : Notebook link

--

--