Project Sample3
Project Sample3
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.
2. Kelly-Inspired Strategy
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)
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.
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.
4
2.5 Out-Sample Test
But, every stock has its characteristic, we can adjust the parameter for HSBC, and surprisingly, we have the
following performance:
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.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 𝑁𝐶𝑆𝑡 < −𝛿 (𝑃𝐶𝑆𝑡 > 𝛿).
40.00%
20.00%
0.00%
0% 2% 4% 6% 8% 10% 12% 14%
-20.00%
-40.00%
-60.00%
-80.00%
-100.00%
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.
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
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
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.
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.
Firstly, the plot below the cumulative returns for trading algorithm with 3 parameter sets considered in previous
section and Buy-and-hold Strategy (BAH).
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.
Moreover, the plot below should the trend of cumulative returns versus different slippage.
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.
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.
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.
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 [3]: 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
In [7]: insample_test1=data_insample.copy()
insample_test2=data_insample.copy()
insample_test3=data_insample.copy()
<AxesSubplot:xlabel='Date', ylabel='profit_pct'>
Out[9]:
5.381399024687035e-05
Out[10]:
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]:
<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
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()
data_frame=[outsample_test1,outsample_test2,outsample_test3]
for i in range(len(period_sma)):
backtesting(data_frame[i],period_sma[i],multiplier[i])
<AxesSubplot:xlabel='Date', ylabel='profit_pct'>
Out[18]:
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]:
<AxesSubplot:xlabel='Date', ylabel='profit_pct'>
Out[20]:
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[