AlgoTrading101 Wiki https://algotrading101.com/wiki Quantitative Finance in 500 Simple Words Fri, 08 Jan 2021 21:13:59 +0000 en-US hourly 1 https://wordpress.org/?v=5.4.17 What is Modern Portfolio Theory? https://algotrading101.com/wiki/what-is-modern-portfolio-theory/?utm_source=rss&utm_medium=rss&utm_campaign=what-is-modern-portfolio-theory Tue, 04 Aug 2020 23:22:51 +0000 http://algotrading101.com/wiki/?p=919 Modern Portfolio Theory (MPT) is a method to select which stocks and what amounts to buy such that as a group, these stocks give the highest amount of returns for a given amount of risk. In this article, risk is defined as the volatility[2] of your returns[1]. [1] Returns are the money made or lost […]

The post What is Modern Portfolio Theory? appeared first on AlgoTrading101 Wiki.

]]>
Modern Portfolio Theory (MPT)

Modern Portfolio Theory (MPT) is a method to select which stocks and what amounts to buy such that as a group, these stocks give the highest amount of returns for a given amount of risk.

In this article, risk is defined as the volatility[2] of your returns[1].

[1] Returns are the money made or lost over a period of time.

[2] Volatility refers to returns that change rapidly and unexpectedly.

Understanding Modern Portfolio Theory

The 2 main ideas behind MPT are:

  1. Preference for higher reward per risk
  2. Risk cancellation

Preference for higher reward per risk

Let’s say you are betting at a casino and you have 2 games to choose from.

  • In the first game, you gain $5 if you win. But if you lose, you’re out $3.
  • In the second, you could win $5, but if you lose, you are down $1.

Assume that the odds of winning is the same for both games.

Which will you choose?

I hope you choose the second game. If you chose the first, please go ahead and close your trading account now.

This shows that for a given set of returns, we naturally want to risk as little as possible.

Similarly, if we were to compare 2 stocks with the same gain, we prefer the one with less volatility.

Returns vs risks. Chart of 2 stocks. One is more volatile than the other but the overall returns are the same.
Chart style inspired by xkcd.com

We prefer Stock X!

Risk cancellation

Let’s talk about stocks now.

To understand risk cancellation, we look at 2 stocks.

Stock A looks like this:

Stock price chart

Stock B looks like this:

Stock price chart

Both Stock A and B look similar. They both move up.

However, there is a difference, they are inversely correlated in the short run.

Combining Stock A and B

Short-term inversely correlated stock price chart

Both Stock A and B moves up at the same rate (i.e. have the same returns).

However, their short term moves cancel out.

As an example, if we own $50 of Stock A and $50 of Stock B, our $100 total investment can be represented by the red line.

The red line is better than owning $100 of either Stock A or Stock B alone as it is less volatile.

Remember we want the highest returns per risk (where risk is defined as the volatility of return).

So, what is MPT really?

MPT tells us to choose stocks in a way that their risks cancel out and that the overall returns are the highest for the amount of risk we take on.

Increasing stocks to cancel out more risks

One more concept of MPT is the required number of stocks for risk cancellation.

Using 2 stocks to cancel risks might not be ideal as it is difficult for the 2 stocks to be inversely correlated (in the short term) all the time.

If we have 3 stocks, it would be easier. If we have 4, it’s even easier.

However, each stock addition reduces risks to a lesser extent. The reason is, as our overall risk declines, there isn’t much risk left to eliminate.

Legendary hedge fund manager Ray Dalio describes this better than me: Ray Dalio breaks down his “Holy Grail”

A key takeaway from the video: Once you have about 10 assets in your portfolio, every additional asset provides minimal risk reduction.

One thing to note – when the risks to any individual stock are minimized, the main risk that is left is the exposure to the overall market movement.

Note that we use stocks in our examples but MPT applies to any asset – Commodities, Fixed Income, Forex, Cryptocurrency, etc.

Why is MPT important to you?

3 reasons.

Being able to size up to make more profits!

If your portfolio has low volatility, you will be able to increase your bet size without fear of losing it all.

Here is what happens when you double the amount you trade when your portfolio is volatile.

You hit $0 and get wiped out.

Here is what happens when you double the amount you trade when your portfolio is less volatile.

You stay in the game and make more monies!

Staying in the game

Even if your account does not hit zero. You might be in an unrecoverable position.

If you lose 50% need to make 100% to recover.

If your portfolio is worth $100 and you lose $90, you’ll only have $10 left. You need to make 1000% to hit $100 again.

Thus, if your returns are too volatile, you might not be able to recover.

Examples of Modern Portfolio Theory

Modern Portfolio theory has inspired certain specific portfolios such as the Ray Dalio All Weather Portfolio.


The post What is Modern Portfolio Theory? appeared first on AlgoTrading101 Wiki.

]]>
What is Backtesting? https://algotrading101.com/wiki/what-is-backtesting/?utm_source=rss&utm_medium=rss&utm_campaign=what-is-backtesting Tue, 28 Jul 2020 08:43:22 +0000 http://algotrading101.com/wiki/?p=867 Backtesting is the process of testing a trading or investment strategy using data from the past to see how it would have performed. Understanding backtesting Running a backtest The general idea of a backtest is to run through stock prices in the past, usually with software, and hypothetically firing trades based on a certain trading […]

The post What is Backtesting? appeared first on AlgoTrading101 Wiki.

]]>
backtesting

Backtesting is the process of testing a trading or investment strategy using data from the past to see how it would have performed.

Understanding backtesting

Running a backtest

The general idea of a backtest is to run through stock prices in the past, usually with software, and hypothetically firing trades based on a certain trading strategy.

For example, let’s say your trading strategy is to buy Amazon when it falls 3% in a day, your backtest software will check Amazon’s prices in the past and fire a trade when it fell 3% in a day.

The backtest results will show if the trades were profitable.

Backtesting can be as simple as running analysis in Excel to something more complex such as creating custom backtesting software. It all comes down to your individual requirements.

The Aim of Backtesting

Backtesting accomplishes 3 things:

  1. Shows if a strategy performs well in periods when it is supposed to, and vice versa
  2. Provides an understanding of how the strategy performs in different markets.
  3. Produces insights on how the strategy might be improved on.

1. Performance during selected periods

With a backtest, we can check to see if a strategy makes money when it is supposed to and loses money when it is supposed to.

For instance, let’s say that our strategy is expected to perform better when the markets are volatile, or in other words, when they move much more than they normally do.

If our backtests then show that we make more money than expected during less volatile periods, this is a red flag (even though we made money).

We need to examine our strategy and figure out why.

2. Understand how the strategy performs in different markets

To gain more confidence over how consistently a trading strategy will perform, backtests can be run in different market environments.

This means running backtests with different stocks or other market assets.

It could also mean performing tests during periods where there are clear trends and comparing them to periods where there weren’t.

3. Improving the strategy

This involves making changes to a strategy after looking through the results of the backtest.

A common pitfall here is to continuously tweak the strategy so that it shows better results in a backtest.

This approach rarely leads to profitability when you trade it with real money and is known as overfitting.

Why is backtesting important to you?

Backtesting is an essential part of developing a trading strategy.

Pass, improve, or fail

A backtest can help decide if a strategy is suitable to trade real money, can use improvement, or if it’s best to give up on it.

Deploying a strategy

As mentioned, backtesting helps us understand how our strategy performs in different market environments, this will allow us to deploy our strategy better.

A trader might have multiple strategies. By knowing the strength and weaknesses of each of the strategies, it will be clear when is it best to deploy a certain strategy.

Certain strategies pair well with others. Some strategies don’t work well when market conditions are unfavorable. Running backtests will provide the information needed to decide when to deploy which.

Examples of Backtests

There are several tools available to help you conduct a backtest. 

A common way is to use a trading platform. Popular trading platforms that include backtesting capabilities include MetaTrader4, Tradingview, ThinkorSwim, and Ninjatrader.

The benefit of using such a platform is that most of them include the necessary data. Several of them also have built-in analysis.

Performance summary of a backtest in Tradingview

As an alternative to using a solution tied to a trading platform, there are several coding libraries that can help in backtesting.

For those familiar with Python, Backtrader and Zipline are both great options.

These libraries can accommodate a lot of customization. The trade-off is that the learning curve is a bit steeper.

Returns chart created in PyFolio

Analysis tools usually come with backtesting software. There are also third-party solutions available such as Pyfolio. This Python library simplifies creating charts and calculating statistics.

Backtesting software is not a necessity. The above image shows a chart that tests a hypothesis that gold prices rally for a few days after a Fed meeting

All it took was a simple charting library and some historical data.

The post What is Backtesting? appeared first on AlgoTrading101 Wiki.

]]>
What is a Hedge Fund? https://algotrading101.com/wiki/what-is-a-hedge-fund/?utm_source=rss&utm_medium=rss&utm_campaign=what-is-a-hedge-fund Mon, 08 Apr 2019 17:51:59 +0000 http://algotrading101.com/wiki/?p=245 A hedge fund is a company that takes money from people and invests it to make a profit. Understanding Hedge Funds Hedge funds usually take money from high net-worth individuals or other companies. These people, or companies, are clients of the hedge fund. Note that the money the client hands over to the hedge fund […]

The post What is a Hedge Fund? appeared first on AlgoTrading101 Wiki.

]]>
A hedge fund is a company that takes money from people and invests it to make a profit.

Understanding Hedge Funds

Hedge funds usually take money from high net-worth individuals or other companies. These people, or companies, are clients of the hedge fund.

Note that the money the client hands over to the hedge fund belongs to the client. The hedge fund controls how the money is invested but does not take ownership of the funds.

How do hedge funds make money?

They make money by taking a cut of the profits from the investment of their clients’ money.

What if they lose money?

If the hedge fund loses money, the clients bear all the losses.

How much of a cut do hedge funds make? (Hedge Fund Fee Structure)

In the past, it was common to charge a 2% management fee along with a 20% performance fee.

Management fee:

A management fee is a fixed yearly fee and hedge funds will collect it whether the fund makes a loss or a profit.

The management fee, which is usually 2%, is deducted from the total amount invested by the client.

As an example, if a client invests $100 million with a hedge fund, they will need to pay $2 million as a management fee. It doesn’t matter if the fund makes or loses money that year, this fee has to be paid.

Hedge funds will typically deduct the management fee every month, pro-rated from the total yearly fee.

Performance fee:

A performance fee is collected from the total amount of profits a fund makes. If the fund loses money, the performance fee is $0 (it does not return money to investors).

The usual 20% performance fee is deducted from any profits the fund makes.

For instance, if the client places $100 million with a hedge fund and the hedge fund makes $20 million from that $100 million, the hedge fund’s cut is 20% of that $20 million or $4 million.

Clients usually pay performance fees on a quarterly basis.

Trend of Decreasing Fees

Hedge fund fees have consistently declined over the years as poor returns have led to pressure by clients for lower fees.

Active vs Passive Fund Management

Hedge funds fall under the category of active management. This means that the fund manager and his/her team make day-to-day decisions regarding investments.

Mutual funds are a good example of passive management. The mutual fund manager makes broad investment decisions and reviews them sporadically.

Alpha vs Benchmark-Tracking

Alpha funds are a type of fund that aims to make profits no matter how the market is performing.

Benchmark-tracking funds are a type of fund that attempts to perform better than an index. An index offers a value for comparison, derived from the performance of a group of stocks or other assets.

They choose a specific index as a reference target and aim to outperform it.

A common target index is the S&P 500 and several benchmark-tracking fund have set their aim to outperform it. If the S&P 500 gains, they must gain more. If the S&P 500 loses, they are content if they lose less.

Quantitative vs Non-Quantitative Fund

Quantitative funds use mathematical or high-tech methods to generate profits. Such methods include:

Non-quantitative funds use qualitative methods to generate alpha. Such methods include reading annual reports, talking to a company’s management, evaluating a company’s CEO and understanding the macroeconomic conditions of a country.

Examples of Hedge Funds

Here are some famous hedge funds.

  • Bridgewater Associates (Qualitative)
  • Renaissance Technologies (Quantitative)
  • AQR Capital Management (Mixed)

How are Hedge Funds Important to You?

If you are rich and are choosing which hedge fund to put your money in, then knowing how hedge funds work is useful.

Otherwise, hedge funds are not important to you.

The post What is a Hedge Fund? appeared first on AlgoTrading101 Wiki.

]]>
What is Negative Correlation? https://algotrading101.com/wiki/what-is-negative-correlation/?utm_source=rss&utm_medium=rss&utm_campaign=what-is-negative-correlation Mon, 20 Jul 2020 21:55:35 +0000 http://algotrading101.com/wiki/?p=757 Negative correlation occurs when the rise in one item accompanies a fall in another. Example of Negative Correlation When gas prices go up, stocks of shipping companies tend to fall, and vice versa. When interest rates go up, bond prices tend to fall, and vice versa. In the short run, when stock prices go up, […]

The post What is Negative Correlation? appeared first on AlgoTrading101 Wiki.

]]>
Negative correlation occurs when the rise in one item accompanies a fall in another.

Example of Negative Correlation

When gas prices go up, stocks of shipping companies tend to fall, and vice versa.

When interest rates go up, bond prices tend to fall, and vice versa.

In the short run, when stock prices go up, bond prices tend to fall, and vice versa.

Negative correlation between a shipping stock and oil prices

Why is this Important to You?

Negatively correlated assets provide diversification to an investment portfolio.

Imagine you had a portfolio with all positively correlated instruments. If the price of one of the instruments increased, then all the other prices will theoretically increase as well. By doing this you are essentially putting all of your eggs in one basket. If you were wrong about the market direction, then you lose on all of your investments. 

The current market conditions completely determine the success of a non-diversified portfolio. As a trader, your goal is to use strategies that take control of making profits regardless of the market situation. Therefore, managing risk is essential to increasing your effectiveness.

Note, however, that decreasing your risk in this way often lowers the highest potential return. For instance, if you had two perfectly negatively correlated assets then your return would be 0. This is because the profit from one asset would be canceled out by the loss in the other.

On the flip-side, managing your risk increases your probability of having a positive return. This is where the risk/reward trade-off comes from.

Some risks are inherent to a sector which is also something to be mindful of. For instance, in a year of drought, the entire farming industry will be affected. This emphasizes the importance of holding assets across multiple sectors to achieve a balanced portfolio.

Understanding Negative Correlation

To be a little bit more precise, correlation is a statistical concept that measures the linear relationship between two variables.

The correlation coefficient is a number between -1 and 1 which describes the strength and direction of a correlation.

Two perfectly correlated have a correlation coefficient of 1.

Two perfectly negatively correlated variables have a coefficient of -1.

If the coefficient is 0 then we say there is no linear relationship. We say no linear relationship since the correlation coefficient cannot determine whether there are other more complex relationships.

How do you chart a correlation?

In practice, we can visualize the correlation between two stocks by fitting a linear regression line through historical price data. The correlation coefficient determines the slope (in red) in the example below.

This graph is a little extreme but it shows the relationship between oil prices and the price of airline stock. Since the price of fuel is such a major factor in the airline costs, it plays a direct role in profitability of airline operations. Therefore, as the cost of oil rises, the price of airline stock falls.

The post What is Negative Correlation? appeared first on AlgoTrading101 Wiki.

]]>
What are Parametric Equations? https://algotrading101.com/wiki/what-are-parametric-equations/?utm_source=rss&utm_medium=rss&utm_campaign=what-are-parametric-equations Thu, 16 Jul 2020 11:21:02 +0000 http://algotrading101.com/wiki/?p=770 Parametric equations are math statements that describe a relationship between 2 items via a common third item. Examples of Parametric Equations Parametric equations come in pairs.         Understanding Parametric Equations To understand parametric equations, you need to understand regular mathematical equations. If you don’t understand regular equations, detour over here to learn […]

The post What are Parametric Equations? appeared first on AlgoTrading101 Wiki.

]]>

Parametric equations are math statements that describe a relationship between 2 items via a common third item.

Examples of Parametric Equations

Parametric equations come in pairs.

    \[y = 2t\]

    \[x = 4t\]

Understanding Parametric Equations

To understand parametric equations, you need to understand regular mathematical equations.

If you don’t understand regular equations, detour over here to learn them: What is an Equation?

Simplifying a parametric equation

If an apple costs 2 dollars and a banana costs 1 dollar. One apple can buy you two bananas.

Thus, in math terms, Apple = 2 Bananas.

I.e. Apple = 2 x Banana. Or in other words,

Apple = 2 Banana

Similarly, if an orange costs 4 dollars and a banana still costs 1 dollar.

Orange = 4 Banana

This tells us that we can get 2 apples for 1 orange.

2 Apple = Orange

Converting Fruits to Math

Let’s use a single letter to represent the names apple, banana and orange. I will call them y, t and x respectively.

Thus… Apple = 2Banana becomes

    \[y = 2t\]

Orange = 4Banana becomes

    \[x = 4t\]

In this case, the pair of equations are a parametric equation because they describe the relationship between y (apples) and x (oranges) using a 3rd item t (banana).

In the above math equations, the items x, t, and y are known as parameters.

Merging a parametric equation

From the above fruit example, we saw that 2Apple = Orange.

Therefore, 2Apple = Orange becomes

    \[2x = y\]

The above equation is a merged form of the parametric equation:

    \[y = 2t\]

    \[x = 4t\]

To merge a parametric equation into a single equation, rearrange the common parameter to one side. We shall put the parameter t on its own, on the right side.

    \[0.5y = t\]

    \[0.25x = t\]

Now equate both left sides. Hence,

    \[0.5y = 0.25x\]

Multiply 4 to both sides to beautify it.

    \[2y = x\]

Why is it Important to You?

Parametric equations help us understand relationships between 2 parameters when they are related to other parameters.

In finance, we use parametric equations to understand the relationship between different financial products.

One use of parametric equations is to check the sensitivity of stocks against the overall market movement.

Knowing these sensitivities will allow us to size our bets when running a trading strategy that involves buying and shorting (To short a stock is to bet that it will drop).

One example is the pair trading strategy.

Sensitivity to the overall market

The overall market is a term that refers to the majority of stocks. This often refers to a group of stocks that represent the local stock market.

In the US, the most popular group of stocks is the S&P500. The S&P500 is a group of 500 major stocks in the US.

When the overall market moves, individual stocks will likely move in a similar manner.

However, each stock might move to a different extent.

Let’s assume that when the S&P500 moves by 1%, Tesla moves by 2% and General Motors (GM) moves by 0.5%.

Thus, the parametric equations are:

    \[2Tesla = S&P500\]

    \[0.5GM = S&P500\]

The S&P500 is our common factor. Therefore:

    \[2Tesla = 0.5GM\]

Beautifying it…

    \[4Tesla = GM\]

We now know that a 4% move in Tesla is equivalent to a 1% move in GM.

Using this information in a Pair Trading Strategy

A pair trading strategy involves buying one stock and shorting another at the same time.

The idea of this strategy is to cancel out the exposure to the overall market while betting that one stock does better than the other.

If we were to buy Tesla and short GM, we could buy 1 share of Tesla and short 4 shares of GM.

    \[4Tesla = GM\]

This way, if the S&P500 moves up 1%, we should gain 2% on our Tesla shares while the GM shares will will lose 2% in value (0.5% * 4 shares).

Netting them (2% – 2%) will result in no movement for our pair trade.

Our pair trade should not fluctuate when the overall markets move, but will work in our favor if Tesla’s business performs better than GM.

This is the bet we are making in this hypothetical scenario.

The post What are Parametric Equations? appeared first on AlgoTrading101 Wiki.

]]>
Turtle Trading https://algotrading101.com/wiki/turtle-trading/?utm_source=rss&utm_medium=rss&utm_campaign=turtle-trading Sun, 09 Jun 2019 17:28:15 +0000 http://algotrading101.com/wiki/?p=694 Definition Turtle trading refers to the way a group of traders in the 1980s traded. This group, who is known as the turtle traders, made $175 million in 5 years using a fixed strategy that was taught to them. Description History of the Turtle Traders In the 1980s, Richard Dennis and William Eckhardt developed a […]

The post Turtle Trading appeared first on AlgoTrading101 Wiki.

]]>
Definition


Turtle trading refers to the way a group of traders in the 1980s traded. This group, who is known as the turtle traders, made $175 million in 5 years using a fixed strategy that was taught to them.

Description


History of the Turtle Traders

In the 1980s, Richard Dennis and William Eckhardt developed a systematic trading system that turned $5,000 into $100 million (a lot of money in the 1980s).

Dennis believed successful traders can be trained while Eckhardt believed they are born with a gift for trading. To settle this debate, they started an experiment that will go on to be world famous.

Turtle Experiment

Dennis picked people off the streets, interviewed them and selected a handful for the experiment. He and Eckhardt taught these traders (they were called the Turtles) how to trade for two weeks.

They gave the Turtles money to manage after the training.

Why the name “Turtles”? Dennis, visited a turtle farm in Singapore and believed he could “grow” traders and efficiently as they grow turtles there.

The result of the experiment

The Turtles made $175 million in 5 years.

The Turtle Trading Strategy

The Turtle Traders used a long term breakout strategy. They mainly traded Forex and commodity futures.

Their strategy is based on fixed rules and the traders are required to abide by it strictly.

Entries and Exits

Whenever an asset rise significantly, they will long (i.e. buy) the asset. They will long more as the asset continues to rise.

Whenever an asset falls significantly, they will short (i.e. bet that it falls) the asset. They will short more as the asset continues to fall.

In both long and short trades, they will close the trade when it moves significantly against them. This means that they give back some profits near the end of the trade. However, it also means that they will stick will a trend for a long time.

As it takes discipline not to close a trade when taking on a significant loss. Many Turtle Traders fail to make the cut due to the lack of discipline in this aspect.

Position Sizing and Risk Management

The Turtle Traders strength is their position sizing (how much to bet) and risk management

They use the volatility of the markets to determine how much to trade. The more volatile the markets are, the less they bet per trade.

Their trades are spread over many different assets so as to diversify their risks. The traders’ overall positions can’t be overwhelming long or short.

The Original Turtle Trading Strategy

Link: The Original Turtle Trading Strategy – Tradingblox.com

The Turtle Trading Strategy Today

There is little evidence that the original trading strategy works today.

However, many former Turtle Traders continued to be successful traders, using techniques that are similar but not identical, to the original Turtle Trading Strategy

Links to Other Explanations


Related Terms


The post Turtle Trading appeared first on AlgoTrading101 Wiki.

]]>
Stochastic Calculus https://algotrading101.com/wiki/stochastic-calculus/?utm_source=rss&utm_medium=rss&utm_campaign=stochastic-calculus Fri, 07 Jun 2019 09:00:21 +0000 http://algotrading101.com/wiki/?p=517 Definition Stochastic calculus is a way to conduct regular calculus when there is a random element. Regular calculus is the study of how things change and the rate at which they change. Description Think of stochastic calculus as the analysis of regular calculus + randomness. Regular Calculus Regular calculus studies the rate at which things […]

The post Stochastic Calculus appeared first on AlgoTrading101 Wiki.

]]>

Definition


Stochastic calculus is a way to conduct regular calculus when there is a random element.

Regular calculus is the study of how things change and the rate at which they change.

Description


Think of stochastic calculus as the analysis of regular calculus + randomness.

Regular Calculus

Regular calculus studies the rate at which things changes.

Normal Calculus
Just a normal chart
  • At W, there is 0 change
  • At X, there is an increasing increase
  • At Y, there is a constant increase
  • At Z, there is a decreasing increase
Credits to coolmath.com!

The red lines indicate the rate of increase at the black dots.

As the red lines become steeper, the increase in values is going up at a faster pace.

Imagine that we are climbing up a ladder, but now we are climbing up at a faster pace.

Randomness

Let’s talk about randomness before combining this with the earlier section on regular calculus.

This is what a bunch of random charts look like:

Randomness chart
Randomness charts over time

This behavior is described as Brownian motion.

This means that their behaviour is random, but over the long run and with enough samples, their overall movement resembles a bell shape. In other words, they are normally distributed.

Brownian motion. Image credits to link.springer.com.

This randomness is not so random after all. The end result of all these random movements is a bell shaped output. (See the bell shape by tilting your head to the right.)

That means that most of the data points end in the middle while the rest are spread out across the sides.

More info on Normal Distribution: Normal Distribution – MathIsFun

In Brownian motion, the values can be negative. However, stock prices can’t be negative.

Thus, in finance, we use geometric Brownian motion to model our stock prices.

Geometric Brownian motion (GBM) is essentially regular Brownian motion but with an upward drift.

geometric brownian motion with normal distribution
Geometric Brownian motion. Image credits to link.springer.com.

The end result of all these GBM movements is a skewed bell shaped output.

This skewed bell-shaped curve no longer resembles a normal distribution. It now resembles a log-normal distribution.

normal vs lognormal distribution
Top: Log-normal distribution. Bottom: Normal Distribution.

Stochastic Calculus = Regular Calculus + Randomness

When we zoom in on a curve chart, we get a nice curve line. We can then measure the rate of increase using those slopes.

x power of 2 chart
A regular non-random chart
Increasing steepest of the slopes zoomed in

The curve is smooth

Now let’s look at a chart with randomness.

fractals chart
A price chart with randomness

If we zoom in, we see that it looks… somewhat the same.

Randomness zoomed in fractals
After zooming in, it still looks random.

We can keep zooming in but we will not be able to find a smooth curve. Without a smooth curve, we can’t draw those slope lines productively.

Thus, normal calculus will fail here. This is why we need stochastic calculus.

Stochastic Calculus Mathematics

The main aspects of stochastic calculus revolve around Itô calculus, named after Kiyoshi Itô.

The main equation in Itô calculus is Itô’s lemma. This equation takes into account Brownian motion.

Itô’s lemma:

    \[   dX_t = \mu_t dt + \sigma dB_t\]

Explanation: Change in X = Constant A * change in time + Constant B * change due to randomness as modeled by Brownian motion.

Which means the change in the value of a variable = some constant value over time + change due to randomness multiplied by another constant.

More info on the derivation of Itô’s lemma: Derivation of Itô’s lemma by Math Partner

A variation of Itô’s lemma that uses GBM is:

    \[   dX_t = \mu_t X_t  dt + \sigma X_t dB_t\]

Before we explain it. Let’s replace X (a regular variable) with S (stock price) so that you can visualize this better.

    \[   dS_t = \mu_t S_t  dt + \sigma S_t dB_t\]

In this case, we try to link the equation to finance. Let S be stock price.

Explanation: Change in S = Constant A * Current S * change in time + Constant B * Current S * change due to randomness as modeled by GBM

Which means the change in the stock price = current stock price multiplied by some constant value over time +
current stock price + change due to randomness multiplied by another constant.

That should intuitively make sense as over time, the change of the stock price is based on some overall trend (the Constant A part) and an element of randomness (the Constant B part and randomness part).

Constant A and Constant B are usually derived by analyzing historical market data.

Finance and Stochastic Calculus

This is where we relate everything we’ve just said to finance.

In 1900, Louis Bachelier, a mathematician, first introduced the idea of using geometric Brownian motion (GBM) on stock prices.

His theory is later built upon by Robert Merton and Paul Samuelson in their work on options pricing. They won an Nobel Prize in Economics for it.

Essentially, these mathematicians argue that GBM can be used to model stock prices because it is said that:

  • The GBM process has only positive values. Stock prices only has positive values.
  • Expected value of the data in the next time period has nothing to do with the last time period. Similarly, it is said that the expected value of the stock price in the next time period has nothing to do with the last time period
  • The GBM chart is rough and random. Stock prices look rough and random.
  • Calculations with GBM processes are relatively easy

However, those points above are debatable.

  • In reality, the randomness and volatility changes over time. In GBM, the volatility is assumed to be constant.
  • In reality, there are sudden jumps in prices. In GBM, there are not.
  • In reality, the stock prices may not be random and log-normally distributed in the long run. In GBM, they are.

Stochastic calculus as applied to finance, is a form of pseudo science. There are assumptions that may not hold in real-life. Some of the assumptions are there for the convenience of mathematical modelling.

Black Scholes Model – Application to Finance

The most famous application of stochastic calculus to finance is to price options (options are a special financial instrument that gives the holder the choice to buy or sell an asset at a certain price).

The main intuition is that the price of an option is the cost of hedging it.

By hedging, we mean that we can separately create a combination of stocks and cash to mimic the market exposure of the option.

Thus, the cost of this hedging process should be the price that option is worth.

Price of option = cost of hedging with stock and cash.

Now, we can calculate the price of the option if we assume that the stock can be modeled using Ito’s lemma, which brings us back to the equation above:

    \[   dS_t = \mu_t S_t  dt + \sigma S_t dB_t\]

Using the above equation and the fact that the price of the option = cost of hedging with stock and cash, we can derive our Black-Scholes equation

Black-Scholes Equation

    \[ \frac{\partial V}{\partial t} + \frac{1}{2}\sigma^2 S^2 \frac{\partial^2 V}{\partial S^2} + rS\frac{\partial V}{\partial S} - rV = 0 \]

We are not going to do the derivation here as it is too technical.

Here is the derivation: Paul Wilmott on Quantitative Finance, Chapter 5, Black-Scholes

Once you solve that equation and turn it into a form that we can plug in figures and use, you’ll get the Black-Scholes Formula:

    \[      \mathrm C(\mathrm S,\mathrm t)= \mathrm N(\mathrm d_1)\mathrm S - \mathrm N(\mathrm d_2) \mathrm K \mathrm e^{-rt}     \label{eq:2} \]

    \[ \hspace*{-10cm} \text{where} \]

    \[     \mathrm d_1= \frac{1}{\sigma \sqrt{\mathrm t}} \left[\ln{\left(\frac{S}{K}\right)} + t\left(r + \frac{\sigma^2}{2} \right) \right]  \]

    \[      \mathrm d_2= \frac{1}{\sigma \sqrt{\mathrm t}} \left[\ln{\left(\frac{S}{K}\right)} + t\left(r - \frac{\sigma^2}{2} \right) \right]  \]

    \[      N(x)=\frac{1}{\sqrt{2\pi}} \int_{-\infty}^{x} \mathrm e^{-\frac{1}{2}z^2} dz     \label{eq:5}  \]

This is how you get from the equation to the formula:
Solution of the Black-Scholes Equation – University of Nebraska (warning: It gets technical)

Links to Other Explanations


Related Terms


The post Stochastic Calculus appeared first on AlgoTrading101 Wiki.

]]>
Options Trading Basics https://algotrading101.com/wiki/options-trading-basics/?utm_source=rss&utm_medium=rss&utm_campaign=options-trading-basics Thu, 06 Jun 2019 08:34:15 +0000 http://algotrading101.com/wiki/?p=521 Definition An option gives the option holder a choice to buy or sell a pre-agreed asset at a certain pre-agreed price. Description There are 2 main types of options: 1) Call option and 2) Put option. Call options gives the option holder a choice to buy a pre-agreed asset at a certain pre-agreed price. Put […]

The post Options Trading Basics appeared first on AlgoTrading101 Wiki.

]]>
Definition


An option gives the option holder a choice to buy or sell a pre-agreed asset at a certain pre-agreed price.

Description


There are 2 main types of options: 1) Call option and 2) Put option.

Call options gives the option holder a choice to buy a pre-agreed asset at a certain pre-agreed price.

Put options gives the option holder a choice to sell a pre-agreed asset at a certain pre-agreed price.

This pre-agreed asset is called the underlying asset, in other words, it is the asset that is attached to this option.

This pre-agreed price is called the strike price.

Example of an Option Trade

Call option example:

Trader A buys the Apple’s call option at strike price $190. In this case, Apple is the underlying asset.

Let’s assume Apple is trading at $180 today. Trader A’s call option is not very valuable as we can buy Apple stock directly for $180. Thus, we don’t want to exercise the choice to buy it at $190 (a more expensive price).

If Apple goes to $200 tomorrow, Trader A’s call option becomes more valuable. We can now exercise our choice to buy Apple at $190 and immediately sell Apple at the exchange for $200 (a $10 profit).

Put option example:

Trader B buys the Google’s put option at strike price $1200.

Let’s assume Google is trading at $1300 today. Trader B’s put option is not very valuable as we can sell Google in the market for $1300. Thus, we don’t want to exercise the choice to sell it at $1200 (a lower price).

If Google drops to $1100 tomorrow, Trader B’s put option becomes more valuable. We can now immediately buy Google from the exchange at $1100 and exercise our choice to sell Google at $1200 (a $100 profit).

Payoff Charts

We use charts to get a better look at our payoffs, i.e. how much we will make (or lose) as the underlying asset’s price moves.

call-option-payoff-diagram
Call Option Payoff Diagram. Strike price at $50.
put-option-payoff-diagram
Put Option Payoff Diagram. Strike price at $50.

From the diagram above, we can see that when the payoff is:

  • $50. The payoff is $0.
  • $40. The payoff is $10.
  • $30. The payoff is $20.
  • $20. The payoff is $30.

This makes sense as if we own this put option when the underlying is $30, we can immediately buy the underlying from the exchange at $30, and exercise our choice to sell it at $50. Thus, netting a $20 profit.

To exercise an option means to buy or sell the underlying assets at the pre-agreed strike price.

Moneyness

Moneyness describes how we name options at different profit or loss levels. There are 3 terms used to describe this:

  1. In-the-money (ITM): Our payoff is positive.
  2. At-the-money (ATM): Our payoff is zero. Strike price = Underlying asset’s price.
  3. Out-of-the-money (OTM): Our payoff is zero (or negative after considering the cost of the option).
    • For call options, strike price is greater than underlying asset’s price.
    • For put options, strike price is less than underlying asset’s price.

Expiration

Options expire at a certain pre-agreed date.

If the options holder did not exercise the option by then, the option becomes worthless if it is ATM or OTM. If the option is ITM, it will be automatically exercised.

Cost of Options (Premiums)

If the stock goes higher than your call option strike price, you make profits. If it doesn’t, you don’t make losses. It might seem like a deal too good to be true.

And yes, it is.

The catch is that you need to pay to buy call or put options. The costs of the option is known as the premium.

The premium goes up as the the option gets more ITM as we need to take into account the profit already accumulated by this option.

The premium goes down as the option gets less ITM as we need to take into account that the profit is far in sight.

call option with premium
Call option with $200 premium. Credits to theoptionsguide.com.
put option with premium
Put option with $200 premium. Credits to theoptionsguide.com.

The premium shifts your diagram down, as you need to earn the premium amount before you go on to make a profit.

This is an example of some of Apple’s options as viewed in a trading terminal:

Apple stock options

Selling Options

Traders are able to sell options too. The payoff will be the exact opposite of that of an option buyer.

In this case we are selling that option without first owning it. When you do that, you are said to have shorted that option.

Option buyers pay a premium and hope that the option goes ITM.

Option sellers receive a premium and hope that the option does not go ITM.

In this aspect, options seller have a limit on how much they can make but their potential losses are unlimited. Vice versa for option buyers.

Short call option payoff diagram. Credits to optionsplaybook.com.

Short put option payoff diagram.
Credits to optionsplaybook.com.

Option Combinations – Strategies

You can combine different options to create unique structures. Here is a short non-exhaustive list:

  • Straddle
  • Put Spreads
  • Iron Condor

Straddle

When Trader A buys a call option and a put option at the same strike price, the resulting position is a long straddle.

Long straddle.
Credits to optionsplaybook.com.

The above is your payoff diagram when you long a straddle.

You long a straddle when you want to bet that there is going to be a big move, but you’re not sure if the move will be up or down.

The cost of this trade is double that of a regular call or put option.

Short straddle.
Credits to optionsplaybook.com.

The above is your payoff diagram when you short a straddle.

This involves selling a call and put option at the same strike price.

You short a straddle when you want to bet that there isn’t going to be much movement.

Put Spread

Long put spread. Credits to optionsplaybook.com.

When Trader A sells a put option at strike price A and buys a put at strike price B (where B is greater than A), the resulting position is a long put spread.

The rationale of this trade is that you want to bet that the underlying asset will fall by a little. But you want some insurance to protect yourself if the price rises.

The long put option at strike price B will provide that insurance. The cost of this insurance is the premium of that put option.

A long put spread is also known as a bear put spread or vertical spread.

Short put spread. Credits to optionsplaybook.com.

When Trader A buys a put option at strike price A and sells a put at strike price B (where B is greater than A), the resulting position is a short put spread.

The rationale of this trade is that you want to bet that the underlying asset will rise by a little. But you want some insurance to protect yourself if the price falls.

The long put option at strike price A will provide that insurance. The cost of this insurance is the premium of that put option.

A short put spread is also known as a bull put spread or vertical spread.

Iron Condor

Iron Condor

The iron condor is formed by buying a put option at strike A, selling a put option at strike B, selling a call option at strike C and buying a call option at strike D.

The rationale of this trade is that you want to bet that the underlying stock price will stay between B and C.

You give up some profits (when the underlying is between B and C) in order to gain some premiums from selling 2 options, to reduce the cost of this structure.

We have only listed 3 option strategies that can be made by combining options and stocks. Here are 40 more option strategies: Options Strategies – Optionsplaybook.com

Why Trade Options

  • To create creative trades by trading structures as seen in the above section.
  • To hedge certain exposure. Think of this as buying insurance on your trades by giving up potential gains.
  • To leverage. Option premiums are relatively low compared to the potential gains. (This doesn’t mean trading options is generally profitable.)

Regular Options

These are common options that are traded in the markets.

American Options

These are the most common options which can be exercised anytime. Despite it’s name, it has nothing to do with American stocks.

European Options

These are options which can only be exercised on expiration. Despite it’s name, it has nothing to do with European stocks.

Exotic Options

There also exist unique options with quirky features.

Barrier Options

These come into existence or become worthless once the underlying asset reaches a certain pre-agreed price.

Asian Options

Asian options’ payoffs are determined by the average price of the underlying asset over a pre-set period of time.

Basket Options

Basket Options are based on more than one underlying asset. The payoff of the basket option is based on the average price of a group of underlying assets.

Lookback Options

Lookback options have no strike price initially. On the expiry date, the option holder will choose a strike price among all the prices that have occurred during the lifetime of the option. Usually the holder will choose the most favorable strike price.

We have covered 4 exotic options, read about another 8 more here: What are Exotic Options – Corporate Finance Institute.

Links to Other Explanations


Related Terms


The post Options Trading Basics appeared first on AlgoTrading101 Wiki.

]]>
Backtesting Biases and Risks https://algotrading101.com/wiki/backtesting-biases-and-risks/?utm_source=rss&utm_medium=rss&utm_campaign=backtesting-biases-and-risks Wed, 15 May 2019 16:22:44 +0000 http://algotrading101.com/wiki/?p=464 Definition Backtesting biases refer to how the results of a trading strategy backtest can be misleading. Description Here are the 8 common biases: Black Swan Reconciliation Survivorship Bias Spreads Cost of carry/Holding costs Inaccurate Price Simulation Change in Contract Specifications Look-ahead Bias Curve-Fitting and Optimization Bias Bias 1 – Black Swan Reconciliation Black swan events […]

The post Backtesting Biases and Risks appeared first on AlgoTrading101 Wiki.

]]>
Definition


Backtesting biases refer to how the results of a trading strategy backtest can be misleading.

Description


Here are the 8 common biases:

  1. Black Swan Reconciliation
  2. Survivorship Bias
  3. Spreads
  4. Cost of carry/Holding costs
  5. Inaccurate Price Simulation
  6. Change in Contract Specifications
  7. Look-ahead Bias
  8. Curve-Fitting and Optimization Bias

black swan events trading
Black swans in real life

Bias 1 – Black Swan Reconciliation

Black swan events refer to events that come as a surprise and have a huge impact.

Brokers and exchanges may alter the prices of assets after a volatile price moves (black swan events). There are 2 types of alteration.

Type 1 – Changing the fill price

After an unexpected large price move, brokers and exchanges might change the prices that you got filled on your trades.

Example

EURUSD is trading at 1.1300. A black swan event occurs and EURUSD spikes up 2000 pips (to 1.3300) (1 pip = $0.0001).

You long EURUSD 1000 pips into the 2000 pips move. You are long EURUSD at 1.2300. It is now trading at 1.3300. You close the trade at a 1000 pips profit.

A few hours after the trade, you receive an email saying that “In view of this unexpected event, all trades will be cleared at 1.1800 price”.

Your 2000 pips profit becomes a 500 pips loss. Your account gets wiped out.

Real example: Saxo Trades Lawsuits With Clients After Swiss Currency Turmoil

Type 2 – Changing their historical price

After an unexpected large price move, brokers and exchanges might not change the prices that you got filled on your trades.

However, they alter the price on the historical charts and data. Thus, the prices you see in your charts are different (almost always worse) than the prices you get in live trading.

In your backtests, you might have bought Apple shares at $180, but in real life, you would have gotten those shares at $250.


Bias 2 – Survivorship Bias

Survivorship bias, or survival bias, refers to the fact that people overlook entities/processes that failed because they only see successful entities/processes.

Example

We are selecting a bunch of stocks to trade. We create a list of criteria to identify potentially successful stocks.

Next, we filter the universe of stocks listed in the US based on these criteria.

And with that, survivorship bias just got to us. This universe of stocks only includes stocks that survive. There may be stocks that are delisted but fit our criteria.

We need to consider those stocks as well to give us an idea of how sound our strategy is.


Bias 3 – Spreads

The difference between the price we can buy at (bid price) and the price we can sell at (ask price) is called the spread.

Spreads change in real time. It depends on the buyers and sellers on exchanges, or brokers.

During volatile events, spreads usually widen, sometimes by a 100 times.

Without accurate bid and ask data, these spread widening events will make our backtests inaccurate.


Bias 4 – Cost of carry/Holding costs

If you are leveraged (you trade a size larger your capital by borrowing from the broker), shorting or trading a derivative, you might need to pay interest to hold your positions.

This interest represents the fees needed to cover the capital loaned to you, or the costs to hold any underlying assets.

These holding costs might vary without warning during the lifetime of a trade. Hence, it is difficult to estimate these costs in your backtest.

Example

The usual interest cost to short a stock is less than 2% a year.

However, for a period in early 2019, the cost to short Tilray, a cannabis stock shot up to over 800% a year.


Bias 5 – Inaccurate Price Simulation

Not all backtesters replicate the exact historical price movement, some use simulated fake price movements.

This might not be significant if you make a few trades a year and analyze the market using end-of-day data.

However, your backtest results will be greatly skewed if your strategy is related to scalping (price action and movement) and fires many trade per day on lower timeframe data.


Bias 6 – Change in Contract Specifications

An exchange or broker may change the contract specifications (i.e. details) of their products.

For instance, they may increase margin requirements, change the settlement specifications or contract size of their products. These may lead to jumps in market prices.

The main takeaway here is – in such cases, do not take a price change at face value. Your P&L may not change proportionally to a price change.

For instance, increasing the margin requirement for silver may cause silver prices to fall. In your backtest, your short silver position may look like it is doing well. However, if you had traded that move in real-life, you may get a margin call and be forced to close the position.

Real-life examples


Bias 7 – Look-ahead Bias

Look-ahead bias involves having prior knowledge of how the market behaves before running a backtest.

Example

You want to run a strategy that takes advantage of trends. You look for assets that trend and discard those that don’t trend.

You then run a backtest on these assets using a trending strategy. Unsurprisingly, your strategy does well.

These tests are not useful as you have only chosen assets that you know would have done well in your backtests.


Bias 8 – Curve-Fitting and Optimization Bias

Curve fitting is the process of adapting a trading system so closely to the past that it becomes ineffective in the future.

Optimizing strategies too closely to past data will result in inflexibility to adapt to the future. Hence, it leads to poor performance in the future.

We need to adapt our trading strategies to signals in historical data, not noise.

Curve fitting data points

Links to Other Explanations


Related Terms


The post Backtesting Biases and Risks appeared first on AlgoTrading101 Wiki.

]]>
Big Data https://algotrading101.com/wiki/big-data/?utm_source=rss&utm_medium=rss&utm_campaign=big-data Tue, 30 Apr 2019 18:45:37 +0000 http://algotrading101.com/wiki/?p=339 Definition Big data is a field that involves analyzing and managing huge amounts of data. Description Similar to smaller data sets, the usual aim of big data is to derive insights from large data sets. There isn’t a specific size to determine if a data set is big enough to be considered big data. A […]

The post Big Data appeared first on AlgoTrading101 Wiki.

]]>
Definition


Big data is a field that involves analyzing and managing huge amounts of data.

Description


Similar to smaller data sets, the usual aim of big data is to derive insights from large data sets.

There isn’t a specific size to determine if a data set is big enough to be considered big data.

A data set can be considered big data if the organization has difficulty using traditional methods, software and database to manage their data.

Characteristics of Big Data

Volume

This refers to the quantity of data.

Velocity

This refers to the speed at which the data is received and needs processing.

Data from real-time sources usually requires much faster management and processing capabilities, especially when the insights from the data need to be extracted quickly.

Variety

This refers to the type of data. The common types are:

  • Text
  • Numbers
  • Audio
  • Imagery
  • Video

Another way to categorize data is structured vs unstructured data.

Structured data is organised and formatted in a way that is easily searchable, processed and analyzed.

Unstructured data has no pre-defined organization or format. This makes it harder to search, process and analyze.

Veracity

This refers to accuracy of the data.

Value

This refers to how much useful insights can be derived from the data.

Variability

This refers to the consistency of the flow of data. The creation of some data peak during certain times, days or months, but slow down during other times.

Complexity

This refers to how complex it is to clean, match, link and manage the data. This characteristic is especially important when there are multiple data sources.

Big data in Industries

Big data is common in the following industries:

  • Manufacturing
  • Media
  • Government
  • Social Media
  • Finance
  • Healthcare
  • Insurance
  • Technology

Examples of Big Data in Action


  • Millions of surveillance cameras capture videos of the public across the country. Machine learning is then used to identify faces.
  • Spotify tracks the data of its users. It then analyzes this data to recommend the users music they might like.
  • Uber generates and uses a huge amount of data regarding drivers, their vehicles, locations, every trip from every vehicle. These data are analyzed to predict the demand, supply, location of the drivers and decide whether to slap on a surcharge.

Links to Complicated Explanations


Related Terms


The post Big Data appeared first on AlgoTrading101 Wiki.

]]>