0% found this document useful (0 votes)
2 views20 pages

Project Sample3

The document discusses a project on quantitative strategies and algorithmic trading focused on the Hang Seng Index, comparing three strategies: a Kelly-inspired strategy, a filter trading rule, and a momentum strategy. Back testing from 2017 to 2022 shows that the Kelly-inspired strategy yielded a cumulative return of 33.25%, while the filter trading rule achieved 38.69%, both outperforming the buy-and-hold strategy. The momentum strategy also demonstrated effectiveness, particularly with a short-term simple moving average, indicating varying performance based on the strategy and market conditions.

Uploaded by

adadsws6
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views20 pages

Project Sample3

The document discusses a project on quantitative strategies and algorithmic trading focused on the Hang Seng Index, comparing three strategies: a Kelly-inspired strategy, a filter trading rule, and a momentum strategy. Back testing from 2017 to 2022 shows that the Kelly-inspired strategy yielded a cumulative return of 33.25%, while the filter trading rule achieved 38.69%, both outperforming the buy-and-hold strategy. The momentum strategy also demonstrated effectiveness, particularly with a short-term simple moving average, indicating varying performance based on the strategy and market conditions.

Uploaded by

adadsws6
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

STAT8020: Quantitative Strategies and Algorithmic Trading

Project title: Kelly-Inspired Strategy, Filter Trading Rule and Momentum

Strategy builded upon Hang Seng Index

Course Instructor: Dr. Eric Li

Group member:

Name UID

1
1. Introduction
Efficient Market Hypothesis of semi-strong form states that the price will be reflected in all publicly available
information fully and immediately, thus no trading strategy can beat the market portfolio as the market is
equilibrium. However, there are various market anomalies and statistical models against it. For instance, a French
mathematician, Bachelier, pointed out a random walk model for stock price in The Theory of Speculation.

It is believed that the only thing that reflects the return is the risk/volatility, as higher risk usually means higher
return. John Larry Kelly in the Bell System Technical Journal published a formula about how to maximize the
return by adjusting the proportion of the existing funds that should be used for the next bet in 1956. Filter trading
rule believes that the current trending of prices would continue in the coming future, using the historical prices
to give a buy and sell signal. Simple moving average concentrate on that the price data is time series and believes
that the daily price should converges to a certain value. As these three strategies have different focuses and
assumptions, we would like to compare with BAH strategy and use back testing to see when we can use them to
earn money and who works best.

We applied the Hang Sheng Index from 2017 to 2022 under these three strategies for back testing. And then,
discuss their performances. The Hang Seng Index is a free-float capitalization-weighted index of a selection of
companies from the Stock Exchange of Hong Kong. The components of the index are divided into four subindices:
Commerce and Industry, Finance, Utilities, and Properties. The index was developed with a base level of 100 as
of July 31, 1964. HSI does not have official ISIN registered. The historical data are collected from Yahoo Finance,
which contains the daily open price, closing price, adjusted price, and volume. We use adjust price for analysis
in the project, as shown in the following plot.

Figure 1.1: Hang Sheng Index from 2017 to 2022

2. Kelly-Inspired Strategy

2.1 Introduction of the strategy


This strategy is inspired by the magical Kelly Formula. We introduce p (an estimate of probability that investment
will win) to help us make judgement. We believe that p is not uniform, and it should be change over time, because
of the economic environment and so forth.

2
The main logic of this strategy is: Firstly, we estimate p, the rate to win, based on the historical performance of
the underlying asset and then set several thresholds to decide R, which is the proportion of capital that we should
invest in the market and is ranging from -1 to 1. If R ranges from -1 to 0, it means we should short sell the
underlying asset by the relative proportion and if it ranges from 0 to 1, it means we should long the underlying
asset by that proportion. We adjust p and R every single day, calculate the cumulative wealth and further adjust
how many units of underlying asset we should hold or short.

2.2 Assumptions
⚫ There is no transaction cost.
⚫ We can trade at the adjusted close price every day.
⚫ We assume we have initial 1 million HKD to invest.

2.3 Methodology
The detail methodology is as follows:
P: Based on the return of BAH, count the number of returns that is positive in the past n trading days divided by
n. For example, in the past 37 trading days, 25 days had a positive return, then p is 25/37=0.6757.
R: R is the proportion of capital we should put in the market. The threshold rules we set is
1, 𝑖𝑓 𝑝 ≥ 0.5
𝑅 = {−0.8, 𝑖𝑓 0.4 ≤ 𝑝 < 0.5
−1, 𝑖𝑓 𝑝 < 0.4
Cumulative wealth: Cumulative wealth=Cumulative wealth last day + Equity0(Today) - Equity1(Last day)
Theoretical wealth: Theoretical wealth=Cumulative wealth*R
Unit0: Units of share of the underlying asset we hold in the past one day, equal to Unit1(last day)
Unit1: Units of share we should adjust to hold in the next day. Unit1=Theoretical wealth/Current price
(Notes: if Unit0 or Unit1 is negative, it means we should short the underlying asset and the ‘-‘ is just a signal.)
Equity0: Equity0=Unit0*Current price of the underlying asset. It can be interpreted as we hold Unit1 yesterday
and today this part of capital we put in the market become value Equity0.
Equity1: Equity1=Unit1*Current price of the underlying asset. (Capital we should put in the market next day)

A flow chart can better illustrate the structure.

Estimate p based Calculate cumulative Adjust the current


on historical return wealth and theoretical position from
of BAH wealth Unit0 to Unit1

Based on p, set Theoretical


threshold and wealth=capital we
decide R should put in market

Figure 2.1: Flow chart of Kelly-Inspired strategy

3
2.4 Back Testing
We apply this strategy on HIS from January 1, 2017, to May 17, 2022. We can customize the method to calculate
p and R, this is also the initial point for us to adjust the parameters and try to find out some possible opportunities
to beat buy and hold strategy.

We adjust how many days we look back and calculate the positive return rate p. We try to look back 20, 30, 37,
40 days and calculate respective p and R, then further calculate the cumulative wealth by excel iteration. We can
have an intuitive comparison with BAH strategy.

Figure 2.2: BAH vs Kelly-Inspired Strategy

Chances exist when past 37 days are considered, we can observe that in the middle of 2021, the cumulative
wealth of Kelly-Inspired is greater than that of BAH.

Figure 2.3: BAH vs Kelly-Inspired (37)


The cumulative return of Kelly-Inspired strategy is 33.25% and the cumulative return for BAH is 3.32%.

4
2.5 Out-Sample Test

Figure 2.4: Out-Sample Test using HSBC on the same period

But, every stock has its characteristic, we can adjust the parameter for HSBC, and surprisingly, we have the
following performance:

Figure 2.5: Adjust parameter for HSBC

It is interesting to find out that for HSI, strategy performs well when we have a far-sight look back period, and
for HSBC, more current sight will perform better. This is probably because HSI reflects market trends more
generally while HSBC performs more individually. It is better to look back a long period on HIS because it is
more stable and for HSBC, short period may reflect its own performance in the future. This difference also
reminds us that algorithm should be changed, or more correctly, adjusted based on different underlying asset.

3. Filter trading rule

3.1 Introduction of the strategy


A filter rule is a trading strategy in which a technical analyst sets rules for when to buy and sell investments,
based on percentage changes from prior prices. The filter rule is generally based on price momentum, or the
belief that rising prices tend to continue to rise and falling prices tend to continue to fall. A certain percentage
rise triggers a buy, while a certain percentage fall triggers a sell.

3.2 Methodology
Based on the filter trading rule, we proposed the following trading strategy.
1) Define recursively

5
𝑃𝐶𝑆0 = 0, 𝑃𝐶𝑆𝑡 = max (0, 𝑃𝐶𝑆𝑡+1 + 𝑌𝑡 )
𝑁𝐶𝑆0 = 0, 𝑁𝐶𝑆𝑡 = min (0, 𝑁𝐶𝑆𝑡−1 + 𝑌𝑡 )
𝑌𝑡 = 𝐴𝑑𝑗𝑢𝑠𝑡 𝑐𝑙𝑜𝑠𝑒 𝑝𝑟𝑖𝑐𝑒
2) 𝑠𝑖𝑔𝑛𝑎𝑙𝑡 = 1 if 𝑃𝐶𝑆𝑡 > 𝛿 ; 𝑠𝑖𝑔𝑛𝑎𝑙𝑡 = −1 if 𝑁𝐶𝑆𝑡 < −𝛿
𝛿 is the pre-determined price changes percentage. In the following part, we call it delta.
3) Once 𝑠𝑖𝑔𝑛𝑎𝑙𝑡 = 1(𝑜𝑟 − 1), reset PCS, NCS=0 and compute future PCS, NCS as usual, then change signal
to -1(or +1) if 𝑁𝐶𝑆𝑡 < −𝛿 (𝑃𝐶𝑆𝑡 > 𝛿).

3.3 Parameter Selection


The core problem is to find a suitable delta which could help filter trading rule beat the buy-and-hold strategy.
To find the best delta, we change delta from 1% to 12% and calculate the sum return. It is shown as below.

sum strategy return (%)


60.00%

40.00%

20.00%

0.00%
0% 2% 4% 6% 8% 10% 12% 14%
-20.00%

-40.00%

-60.00%

-80.00%

-100.00%

Figure 3.1: Sum strategy return - delta

From the figure above, we could find that the cumulative return reaches its highest when delta is equal to 9%.
Thus, we select 9% as the best delta.

3.4 Back Testing


In this part, we use the price of HSI from January 1, 2017, to May 17, 2022 to do back-test. The result shows
that the sum BAH return is 3.32%, while the sum strategy return is 38.69% which is much higher than 3.32%.
Besides that, from the figure below we could find that during most of the time, filter trading rule is better than
BAH.

In conclusion, it shows that filter trading rule is much more effective than BAH.

6
Cumulated Wealth
1800000
1600000
1400000
1200000
1000000
800000
600000
400000
200000
0
1/4/17 1/4/18 1/4/19 1/4/20 1/4/21 1/4/22

Cumulated Wealth- ( BAH ) Cumulated Wealth ( filter trading rule )

Figure 3.2: Cumulative Wealth of Filter Trading Rule

3.5 Out-Sample Test


In this part, we use the price of HSBC from January 1, 2017, to May 17, 2022 to do out-sample test. The result
shows that the cumulated BAH return is 11.12%, while the cumulated strategy return is 58.00% which is much
higher than 11.32%. Besides that, from the figure below we could find that during most of the time, filter trading
rule is better than BAH. And it’s a very stable strategy.

Cumulated Wealth
2000000
1800000
1600000
1400000
1200000
1000000
800000
600000
400000
200000
0
1/4/17 1/4/18 1/4/19 1/4/20 1/4/21 1/4/22

Cumulated Wealth- ( BAH )


Cumulated Wealth ( filter trading rule )

Figure3.3: Out-sample Test of Filter Trading Rule

7
4. Momentum Back-testing Strategy

4.1 Methodology
Note that we consider the unit transaction cost equal to 0.003.
1) Calculate a Simple Moving Average (SMA) of the adjusted closing price
2) Construct Bollinger band for the simple moving average
3) Determine the trading signal as follow.
a) Buy signal: if the adjusted closing price is greater than upper Bollinger band, we choose to buy
b) Sell signal: if the adjusted closing price is less than lower Bollinger band, we choose to sell

4.2 Rational
This trading algorithm is developed based on the momentum properties existed in Hang Seng index.
To make sure the trading algorithm is stable, we use the following trading rules to identify trading positions.
Firstly, we calculate simple moving average and its corresponding Bollinger band based on different look-back
periods. For example, if the look-back period was 10 days, we calculate simple moving average for recent 10-
days prices and its Bollinger band. When today’s price is greater than the upper Bollinger band, we believe there
is a chance that closing price will continue increase. Similarly, when today’s price is less than the lower Bollinger
band, we believe that there is a potential decrease in the closing price due to momentum trading ideas.

4.3 Back Testing


The back testing is implemented based on the adjusted closing price of Hang Seng Index from January 1, 2017,
to May 17, 2022.

4.4 Parameter Selection


For the first and second steps listed in trading algorithm, we consider 3 different simple moving average: short-
term, medium-term, and long-term simple moving averages.
Table 4.1 Parameter Selection
Scenarios Description Bollinger band
Short Term 10-day SMA 10 − 𝑑𝑎𝑦 𝑆𝑀𝐴 ± 1.5 𝑆𝑡𝑎𝑛𝑑𝑎𝑟𝑑 𝑑𝑒𝑣𝑖𝑎𝑡𝑖𝑜𝑛
Medium Term 20-day SMA 20 − 𝑑𝑎𝑦 𝑆𝑀𝐴 ± 2 𝑆𝑡𝑎𝑛𝑑𝑎𝑟𝑑 𝑑𝑒𝑣𝑖𝑎𝑡𝑖𝑜𝑛
Long Term 50-day SMA 50 − 𝑑𝑎𝑦 𝑆𝑀𝐴 ± 2.5 𝑆𝑡𝑎𝑛𝑑𝑎𝑟𝑑 𝑑𝑒𝑣𝑖𝑎𝑡𝑖𝑜𝑛
The following plots shows the cumulative returns for trading algorithm with 3 scenarios considered above and
Buy-and-hold Strategy (BAH).

8
Figure 4.1: BAH vs 3 kind of momentum strategies
As we observe, before year 2018, the cumulative returns of short-term scenario and BAH strategy were very
close. After the earlier part of year 2018, short-term scenario firstly stands out and beats BAH strategy. The
cumulative returns of short-term scenarios get further and further away from the cumulative returns of BAH
strategy. In conclusion, short-term SMA (10-day SMA) outperforms all other scenarios, it helps yield the
maximum profit under our designed trading algorithm. Short-term SMA (10-day SMA) is then used for further
back testing analysis.

4.5 Out-sample Test


In this section, we utilize the adjusted closing price of HSBC from January 1, 2017, to May 17, 2022, to do out-
sample testing.

Firstly, the plot below the cumulative returns for trading algorithm with 3 parameter sets considered in previous
section and Buy-and-hold Strategy (BAH).

Figure 4.2: Out sample test for momentum strategy

The usage of short-term scenario in the trading algorithm can be further proved. From this figure, the short-term
scenario yields the highest cumulative returns compared to the other 2 scenarios. Moreover, this figure validates

9
the feasibility of our trading strategy. Start from very earlier stage of year 2017, cumulative returns for short-
term scenario dramatically increasing and it can always beat BAH strategy.

5. Observations and discussions

5.1 Slippages for momentum strategy


This section assesses how the slippage in real life will affect the trading strategy. The momentum trading
algorithm discussed in section 4 is used to exam the influence of slippage on cumulative profit.
The following 5 different slippages are considered: 0.003, 0.005, 0.01, 0.03, 0.05. The table below shows the
cumulative returns versus different slippage.

Table 5.1: Slippage for momentum


Trading Strategy Slippage Cumulative Return (%)
Momentum Trading Algorithm 0.003 3.15576555685012
(developed in Section 4) 0.005 2.423765556850128
0.01 0.5937655568501141
0.03 -6.726234443149891
0.05 -14.04623444314992
BAH Strategy 0.03320628202103437

Moreover, the plot below should the trend of cumulative returns versus different slippage.

Figure 5.1: Trend of cumulative returns versus different slippage


As we observe, when slippage is 0.003 or 0.005, the momentum trading algorithm can outperform BAH strategy
for the almost whole period. However, when slippage is 0.01, momentum trading algorithm only beats BAH
strategy after the middle of year 2021. When slippage is greater than 0.03, the momentum trading algorithm
suffer from large loss and it cannot beat BAH strategy.

5.2 Implementation difficulty and hidden problems


There are implementation difficulties and hidden problems existed in Kelly-Inspired Strategy and Momentum
trading strategy.
10
5.2.1 Kelly-Inspired Strategy
The Kelly-Inspired Strategy mentioned in section 2 is a more subjective strategy and we need to adjust the look-
back period to calculate p based on the characteristic of the specific asset. The characteristics or styles of
performance of specific asset vary among different kind of asset, for example, index performance is more stable
while individual stock may perform in a more aggressive way; stock in different industries may also performs
dissimilarly (eg. Finance and TMT). We have to some overall understanding of asset before we decide the look
back period. What’s more, we assume there is no transaction cost when we apply Kelly-Inspired strategy, and
this is impossible in real life. This may have some hidden lost.

5.2.2 Momentum trading strategy


The momentum trading strategy mentioned in section 4 has the trading rules that we need to calculate and
compare the daily closing price with Bollinger band of past 10-day SMA. Hence, the Bollinger band of past 10-
day SMA need to be updated in daily bases. Compared to the strategy where the trading rule is a simple fixed
threshold, momentum trading strategy requires more daily computation tasks.

Moreover, as shown in 5.1, when slippage is too high, momentum strategy might yield a potential loss. Hence,
during the implementation of momentum trading strategy, traders need to pay more attention on the slippage or
transaction cost for trading.

5.3 Risk management feature

5.3.1 Analysis on Momentum trading strategy


The plot below shows the trading position for the whole period. It reveals that the trading frequency is not very
high. It aligned with the trading rule that the trading will only be executed when the closing price is outside of
the Bollinger band. Hence, this trading algorithm is quite conversative and stable. It is more suitable for investors
who are risk-averse or willing to invest for a long-term.

Figure 5.2: Trading position and frequency

11
5.3.2 Analysis on Variance and VaR
Table 5.2 shows the Risk measurement of different strategies.
Table 5.2: Risk Measurement of different strategies
Var Value-at-Risk (99%)
BAH 0.000159892 -0.037120808
Kelly-Inspired 0.000135623 -0.029846102
Filter Trading Rule 0.000158390 -0.033932589
Momentum Strategy 0.000053814 -0.003000000

6. Conclusion
This report developed three trading algorithms based on Hang Seng index mainly from January 1, 2017, to May
17, 2022. The following conclusions can be derived:

Kelly-Inspired strategy:
Based on the risk analysis, the volatility of the strategy return is 0.000135623, slightly smaller than that of BAH
strategy. The VaR of the strategy is -0.029846102, also better than that of BAH. Although compared to other
strategies, the sum strategy return of Kelly-Inspired Strategy (33.25%) is not that attractive, but it seems to be a
steady and conservative strategy for risk aversion.

Filter trading rule:


Based on the result of back testing, The result shows that the sum BAH return is 3.32%, while the sum strategy
return is 38.69% which is much higher than 3.32%. Besides that, based on the result of out-sample test, the sum
BAH return is 11.12%, while the sum strategy return is 58.00% which is much higher than 11.32%. It shows that
this strategy could beat BAH well.

Based on the risk analysis, the volatility of strategy return is 0.000158390 which is nearly equal to the volatility
of BAH. However, the VaR of the strategy is -0.34 which is smaller than that of BAH. Therefore, filter trading
rule is better than BAH under this circumstance.

Momentum trading algorithm:


The plot for the adjusted closing price of Hang Seng index in section 1 reveals strong momentum feature. The
increase in today’s price is always followed by the increase in tomorrow’s price. Similarly, the current price drop
is always followed by another price drop. Hence, there is a strong negative correlation between prices with
respect to time index. The momentum trading algorithm mentioned in section 4 utilizes this momentum feature
to generate trading positions. The trading rules choose to buy and short when there is a strong momentum trend.
As illustrated in section 4, both in-sample and out-sample test successfully beats BAH strategy for almost the
whole period. Moreover, it is notable that when transaction cost is too high, momentum trading algorithm might
yield a loss. Under the normal values of transaction cost, this trading algorithm works well, and it can successfully
beat BAH at most of the time. Furthermore, this trading strategy is conservative, and the trading frequency is not
very high. Since the trading actions will only be executed when the closing price is outside of Bollinger bound
of the fitted SMA model. In conclusion, this trading algorithm can perfectly beat BAH strategy for almost the
whole period and it is stable enough for risk-averse investors and investors who prefer long-term investment.

12
22/05/2022, 23:29 8020 Group project Chunyu

7. Appendix
Excel workings are submitted as Excel files
Python Code is submitted and also shown as follows
In [27]: import pandas as pd
import numpy as np

In [2]: #Import dataset


data_insample=pd.read_csv('/Users/cheryl/Downloads/[Link]')
data_insample.Date = pd.to_datetime(data_insample.Date)
data_insample.set_index('Date', inplace=True)

In [3]: data_insample

Out[3]: Open High Low Close Adj Close Vo


Date
2017- 21993.359375 22189.310547 21883.820313 22150.400391 22150.400391 1.302378
01-03
2017- 22201.080078 22228.060547 22076.630859 22134.470703 22134.470703 1.437672
01-04
2017- 22302.640625 22483.009766 22230.310547 22456.689453 22456.689453 1.830652
01-05
2017- 22583.289063 22605.660156 22445.779297 22503.009766 22503.009766 1.389974
01-06
2017- 22561.109375 22626.429688 22476.349609 22558.689453 22558.689453 1.303533
01-09
... ... ... ... ... ...
2022- 19511.800781 20083.490234 19474.029297 19824.570313 19824.570313 1.958419
05-11
2022- 19556.890625 19731.269531 19342.890625 19380.339844 19380.339844 2.273639
05-12
2022- 19615.990234 19925.439453 19608.259766 19898.769531 19898.769531 2.075261
05-13
2022- 20131.529297 20173.220703 19764.960938 19950.210938 19950.210938 1.796370
05-16
2022- 20193.599609 20626.419922 20169.240234 20602.519531 20602.519531 2.207409
05-17
1323 rows × 6 columns

In [4]: import seaborn as sns


[Link](rc = {'[Link]':(17,8)})
[Link](data=data_insample['Adj Close'])

<AxesSubplot:xlabel='Date', ylabel='Adj Close'>


Out[4]:

[Link] Group project Chunyu (3).html 1/8


22/05/2022, 23:29 8020 Group project Chunyu

In [5]: data_insample = data_insample[['Adj Close']]


data_insample = data_insample.rename({'Adj Close': 'close'}, axis=1)
data_insample

Out[5]: close
Date
2017-01-03 22150.400391
2017-01-04 22134.470703
2017-01-05 22456.689453
2017-01-06 22503.009766
2017-01-09 22558.689453
... ...
2022-05-11 19824.570313
2022-05-12 19380.339844
2022-05-13 19898.769531
2022-05-16 19950.210938
2022-05-17 20602.519531
1323 rows × 1 columns
In [6]: def backtesting(data,period_sma,multiplier):
#Part 1
#Calculate simple moving average and corresponding standard deviation
data['sma_mean']=data['close'].rolling(period_sma).mean()
data['sma_std']=data['close'].rolling(period_sma).std()
#Calculate Bollinger Bands for simple moving average
data['upper_bound']=data['sma_mean']+(multiplier*data['sma_std'])
data['lower_bound']=data['sma_mean']-(multiplier*data['sma_std'])
#Part 2: Identify signals
data['signal']=[Link]
data['signal']=[Link](data['close']>data['upper_bound'],1,[Link])
data['signal']=[Link](data['close']<data['lower_bound'],-1,data['signa
data['signal']=data['signal'].fillna(0)
#Calculate transcation cost
data['transcation_cost']=0.003*[Link](data['signal'].diff(1))
#Calculate returns for BHA and Our Strategy

[Link] Group project Chunyu (3).html 2/8


22/05/2022, 23:29 8020 Group project Chunyu
data['return'] = data['close'].pct_change(1)
data['profit_pct'] = data['return'] * data['signal']-data['transcation_c

In [7]: insample_test1=data_insample.copy()
insample_test2=data_insample.copy()
insample_test3=data_insample.copy()

In [8]: #Consider following 3 cases


#Short term: 10 day moving average, bands at 1.5 standard deviations. (1.5 t
#Medium term: 20 day moving average, bands at 2 standard deviations.
#Long term: 50 day moving average, bands at 2.5 standard deviations.
period_sma=[10,20,50]
multiplier=[1.5,2,2.5]
data_frame=[insample_test1,insample_test2,insample_test3]
for i in range(len(period_sma)):
backtesting(data_frame[i],period_sma[i],multiplier[i])

In [9]: import seaborn as sns


[Link](rc = {'[Link]':(15,8)})
[Link](data=insample_test1['profit_pct'].cumsum(),label='Strategy unde
[Link](data=insample_test2['profit_pct'].cumsum(),label='Strategy unde
[Link](data=insample_test3['profit_pct'].cumsum(),label='Strategy unde
[Link](data=insample_test1['return'].cumsum(), label='Buy and Hold Str

<AxesSubplot:xlabel='Date', ylabel='profit_pct'>
Out[9]:

In [10]: #Risk management: Part 1


[Link](insample_test1['profit_pct'])

5.381399024687035e-05
Out[10]:

In [11]: #Risk management: Part 2


sorted1=insample_test1['profit_pct'].sort_values(ascending=False)

In [12]: sorted1[1308]

-0.003
Out[12]:

In [13]: #Hence, using 10-day simple moving average gives the best result
[Link](data=insample_test1['profit_pct'].cumsum(),label='Strategy unde
[Link](data=insample_test1['return'].cumsum(), label='Buy and Hold')
[Link] Group project Chunyu (3).html 3/8
22/05/2022, 23:29 8020 Group project Chunyu

<AxesSubplot:xlabel='Date', ylabel='profit_pct'>
Out[13]:

In [14]: #Risk management: Part 3


[Link](data=insample_test1['signal'],label='Momentum Trading Strate

<AxesSubplot:xlabel='Date', ylabel='signal'>
Out[14]:

In [15]: data_outsample=pd.read_csv('/Users/cheryl/Downloads/[Link](2017-2022).csv')
data_outsample.Date = pd.to_datetime(data_outsample.Date)
data_outsample.set_index('Date', inplace=True)
data_outsample = data_outsample[['Adj Close']]
data_outsample = data_outsample.rename({'Adj Close': 'close'}, axis=1)
data_outsample

[Link] Group project Chunyu (3).html 4/8


22/05/2022, 23:29 8020 Group project Chunyu

Out[15]: close
Date
2017-01-03 49.355785
2017-01-04 49.708344
2017-01-05 50.060875
2017-01-06 49.943356
2017-01-09 49.904186
... ...
2022-05-11 48.400002
2022-05-12 46.750000
2022-05-13 47.750000
2022-05-16 47.900002
2022-05-17 48.599998
1323 rows × 1 columns
In [16]: outsample_test1=data_outsample.copy()
outsample_test2=data_outsample.copy()
outsample_test3=data_outsample.copy()

In [17]: #Consider following 3 cases


#Short term: 10 day moving average, bands at 1.5 standard deviations. (1.5 t
#Medium term: 20 day moving average, bands at 2 standard deviations.
#Long term: 50 day moving average, bands at 2.5 standard deviations.
period_sma=[10,20,50]
multiplier=[1.5,2,2.5]

data_frame=[outsample_test1,outsample_test2,outsample_test3]
for i in range(len(period_sma)):
backtesting(data_frame[i],period_sma[i],multiplier[i])

In [18]: import seaborn as sns


[Link](data=outsample_test1['profit_pct'].cumsum(),label='Strategy und
[Link](data=outsample_test2['profit_pct'].cumsum(),label='Strategy und
[Link](data=outsample_test3['profit_pct'].cumsum(),label='Strategy und
[Link](data=outsample_test1['return'].cumsum(), label='Buy and Hold')

<AxesSubplot:xlabel='Date', ylabel='profit_pct'>
Out[18]:

[Link] Group project Chunyu (3).html 5/8


22/05/2022, 23:29 8020 Group project Chunyu

In [19]: #Hence, using 10-day simple moving average also gives the best result in out
[Link](data=outsample_test1['profit_pct'].cumsum(),label='Strategy und
[Link](data=outsample_test1['return'].cumsum(), label='Buy and Hold')

<AxesSubplot:xlabel='Date', ylabel='profit_pct'>
Out[19]:

In [20]: [Link](data=insample_test1['profit_pct'].cumsum(),label='Strategy unde


[Link](data=insample_test1['return'].cumsum(), label='Buy and Hold')
[Link](data=outsample_test1['profit_pct'].cumsum(), label='Strategy Ou

<AxesSubplot:xlabel='Date', ylabel='profit_pct'>
Out[20]:

[Link] Group project Chunyu (3).html 6/8


22/05/2022, 23:29 8020 Group project Chunyu

In [21]: #Consider different slippage


def backtesting_slippage(data,period_sma,multiplier,slippage):
#Part 1
#Calculate simple moving average and corresponding standard deviation
data['sma_mean']=data['close'].rolling(period_sma).mean()
data['sma_std']=data['close'].rolling(period_sma).std()
#Calculate Bollinger Bands for simple moving average
data['upper_bound']=data['sma_mean']+(multiplier*data['sma_std'])
data['lower_bound']=data['sma_mean']-(multiplier*data['sma_std'])
#Part 2: Identify signals
data['signal']=[Link]
data['signal']=[Link](data['close']>data['upper_bound'],1,[Link])
data['signal']=[Link](data['close']<data['lower_bound'],-1,data['signa
data['signal']=data['signal'].fillna(0)
#Calculate transcation cost
data['transcation_cost']=slippage*[Link](data['signal'].diff(1))
#Calculate returns for BHA and Our Strategy
data['return'] = data['close'].pct_change(1)
data['profit_pct'] = data['return'] * data['signal']-data['transcation_c

In [22]: slippage_test1=data_insample.copy()
slippage_test2=data_insample.copy()
slippage_test3=data_insample.copy()
slippage_test4=data_insample.copy()
slippage_test5=data_insample.copy()

In [23]: period_sma=[10,10,10,10,10]
multiplier=[1.5,1.5,1.5,1.5,1.5]
slippage=[0.003,0.005,0.01,0.03,0.05]
data_frame=[slippage_test1,slippage_test2,slippage_test3,slippage_test4,slip
for i in range(len(period_sma)):
backtesting_slippage(data_frame[i],period_sma[i],multiplier[i],slippage[

In [24]: import seaborn as sns


[Link](data=slippage_test1['profit_pct'].cumsum(),label='Strategy with
[Link](data=slippage_test2['profit_pct'].cumsum(),label='Strategy with
[Link](data=slippage_test3['profit_pct'].cumsum(),label='Strategy with
[Link](data=slippage_test4['profit_pct'].cumsum(),label='Strategy with
[Link](data=slippage_test5['profit_pct'].cumsum(),label='Strategy with
[Link](data=slippage_test1['return'].cumsum(), label='Buy and Hold')

[Link] Group project Chunyu (3).html 7/8


22/05/2022, 23:29 8020 Group project Chunyu
<AxesSubplot:xlabel='Date', ylabel='profit_pct'>
Out[24]:

In [25]: #Cumulative Return


cum_retun_slippage1=slippage_test1['profit_pct'].cumsum()
cum_retun_slippage2=slippage_test2['profit_pct'].cumsum()
cum_retun_slippage3=slippage_test3['profit_pct'].cumsum()
cum_retun_slippage4=slippage_test4['profit_pct'].cumsum()
cum_retun_slippage5=slippage_test5['profit_pct'].cumsum()
cum_retun_BAH=slippage_test1['return'].cumsum()

In [26]: print('Cumulative return for Strategy with slippage=0.003:',cum_retun_slippa


print('Cumulative return for Strategy with slippage=0.005:',cum_retun_slippa
print('Cumulative return for Strategy with slippage=0.01:',cum_retun_slippag
print('Cumulative return for Strategy with slippage=0.03:',cum_retun_slippag
print('Cumulative return for Strategy with slippage=0.05:',cum_retun_slippag
print('Cumulative return for BAH Strategy:',cum_retun_BAH[1322])

Cumulative return for Strategy with slippage=0.003: 3.15576555685012


Cumulative return for Strategy with slippage=0.005: 2.423765556850128
Cumulative return for Strategy with slippage=0.01: 0.5937655568501141
Cumulative return for Strategy with slippage=0.03: -6.726234443149891
Cumulative return for Strategy with slippage=0.05: -14.04623444314992
Cumulative return for BAH Strategy: 0.03320628202103437

[Link] Group project Chunyu (3).html 8/8

You might also like