AI For Trading: Returns (8)


The raw return may be referred to simply as the return, or alternatively, as the percentage return, linear return, or simple return. It is defined as




Calculate Returns


Using the formula $ \frac{p{t} - p{t-1}}{p_{t-1}} $, let's apply it to some example prices. For this exercise, we'll calculate the returns for each day using the closing price data in close.

import pandas as pd

close = pd.DataFrame(
        'ABC': [1, 5, 3, 6, 2],
        'EFG': [12, 51, 43, 56, 22],
        'XYZ': [35, 36, 36, 36, 37],},
    pd.date_range('10/01/2018', periods=5, freq='D'))
2018-10-01 1 12 35
2018-10-02 5 51 36
2018-10-03 3 43 36
2018-10-04 6 56 36
2018-10-05 2 22 37

Using the returns formula on the closing prices for the ticker "ABC" should give us [(5-1)/1, (3-5)/5, (6-3)/3, (2-6)/6] or [4, -0.4, 1, -0.66]. To calculate this for the whole DataFrame, we'll use the DataFrame.shift function.

This function allows us to shift the rows of data. For example, the following shifts the rows in close two days back.

2018-10-01 NaN NaN NaN
2018-10-02 NaN NaN NaN
2018-10-03 1.0 12.0 35.0
2018-10-04 5.0 51.0 36.0
2018-10-05 3.0 43.0 36.0

The data for the row "2018-10-03" contains data that is two days in the past. You'll also notice the "NaN" values for "2018-10-01" and "2018-10-02". Since there's not data two days in the past for these dates, it returns a "NaN" value.

Use this function, you can also shift in the future using a negative number. Let's shift one day in the future.

2018-10-01 5.0 51.0 36.0
2018-10-02 3.0 43.0 36.0
2018-10-03 6.0 56.0 36.0
2018-10-04 2.0 22.0 37.0
2018-10-05 NaN NaN NaN


Using what you know about the DataFrame.shift function, implement the function.

Once you successfully implemented the quiz, you can can continue to the next concept in the classroom.

import quiz_tests

def calculate_returns(close):
    Compute returns for each ticker and date in close.

    close : DataFrame
        Close prices for each ticker and date

    returns : DataFrame
        Returns for each ticker and date
    # TODO: Implement Function

    return (close - close.shift(1))/close.shift(1)

Tests Passed


在数学中,对数是对求幂的逆运算,正如除法是乘法的倒数,反之亦然。 这意味着一个数字的对数是必须产生另一个固定数字(基数)的指数。 在简单的情况下,乘数中的对数计数因子。更一般来说,乘幂允许将任何正实数提高到任何实际功率,总是产生正的结果,因此可以对于b不等于1的任何两个正实数b和x计算对数。

如果a的x次方等于N(a>0,且a不等于1),那么数x叫做以a为底N的对数(logarithm),记作x=logaN。其中,a叫做对数的底数,N叫做真数。 [1]

Log Returns



Log Returns and Compounding
Log returns can be convenient for calculations that involve compounding. To explain this idea, let's first discuss compounding.

If you invest $100 in an asset, and the rate of return is 4% per year, and the amount of interest accrued is only calculated after the money has sat in the account for 1 year, how much money do you have after 1 year?


(2)Compounding 复利
he idea of compounding is a simple one. Say you put $100 in a bank account that earns 4% interest per year, compounded annually. After 1 year, you have

$100 + $100*0.04 = $104.

The next year, you have,

$104 + $104*0.04 = $108.16,

so you earned another $4 of interest on the original $100 but also 16 cents on the $4 of interest earned last year.

Compounding is the process by which an asset’s earnings are reinvested to generate additional earnings, that is to say, earning interest on interest.

Let's say you invest $100 in an asset. The annual rate of interest is reported at 4%, but the asset's seller has explained that what this means is that 2% is gained over 6 months, and then interest is calculated on the investment and it's reinvested, and then the process is repeated after the next 6 months. How much money will you have at the end of 1 year?

  • A:104.04
  • B:104.00
  • C:102.00
  • D:102.04


Rates of Compounding

A statement by a bank that the interest rate on one-year deposits is 4% per year sounds straightforward and unambiguous. In fact, its precise meaning depends on the way the interest rate is measured.

For an interest rate statement to be clear, the magnitude and time dependence of the rate of interest, as well as the frequency of compounding, must be clearly stated.

If the interest rate is measured with annual compounding, the bank’s statement that the interest rate is 4% means that $100 grows to \$100\times(1 + .04) = \$104 $100×(1+.04)=$104 at the end of 1 year.

When the interest rate is measured with semiannual compounding, it means that 2% is earned every 6 months, with the interest being reinvested. In this case, $100 grows to \$100\times(1 + .04/2)\times(1 + .04/2) = \$100\times(1 + .04/2)^2 = \$104.04$100×(1+.04/2)×(1+.04/2)=$100×(1+.04/2) 2 =$104.04, at the end of 1 year.

When the interest rate is measured with quarterly compounding, the bank’s statement means that 1% is earned every 3 months, with the interest being reinvested. The $100 then grows to \$100\times(1 + .04/4)^4 = \$104.06$100×(1+.04/4) 4 =$104.06 at the end of 1 year.

Continuous Compounding

Let's compare the amount of money accumulated after 1 year with the same annual rate of interest of 4%, but different rates of compounding:


Looking at the table, you can see that with more frequent compounding, the value at 1 year increases but then seems to level off. If you assumed that the benefit of compounding more and more frequently had a limit, you would be right! How do we calculate this limit? Well, first we write down the formula for compounding,

and then we notice that what we'd like to do is make n bigger and bigger. We want the limit as n goes to infinity. Well, it turns out that this limit is:

Compounding infinitely often is called continuous compounding. So what does this mean? Well, it means that if you wanted to calculate how much money you’d have at the end of the year if you started with $100 and compounded continuously, but at a simple annual rate of 4%, you’d calculate:

You'll notice that the value after 1 year with continuous compounding is pretty close (it's the same if we round to two decimal places) to the value after 1 year with daily compounding.

Continuously Compounded Return

Now, say you were trying to reverse the previous calculation. Say you knew you had $104.08 at the end of the year, and $100 at the beginning of the year, and you wanted to calculate the rate of interest as if it had been compounded continuously. You would simply invert the formula. So you’d calculate:


Then you'd take the natural log of both sides, and then you'd have,

\ln(\$104.08/\$100) = r


.04 = r.04=r

r is the continuously compounded annual return. So the continuously compounded annual return equals \ln(pt/p{t-1})ln(pt/pt−1 ). But what is this quantity? It’s just the log return! This is why you might hear log returns called continuously compounded returns.


Annualized Rate of Return(年化收益率)

We saw above how to calculate the annual rate of continuous compounding from the monthly rate of continuous compounding. If we just had a single monthly rate, but we assumed that the rates for all the months of the year were the same, we could extrapolate the monthly rate to an annual rate by multiplying by 12. This is called annualizing the rate of continuous compounding. Rates of return and other metrics are often converted to a common annual basis in order to make comparisons across contexts and instruments.

Time Additivity of Log Returns

So, as you can see, the rate of continuous compounding is additive over time. Since, mathematically, the rate of continuous compounding is just the log return, this means that log returns are additive over time, and this can be very convenient. As another example,


Numerical Stability

Multiplication of many small numbers can result in the problem that the product is smaller than the smallest number representable in computer memory. Sometimes the computation will incorrectly yield the value 0. This is called arithmetic underflow. The use of logarithms can help with this, since it enables the representation of much smaller (and much larger) numbers. For example: