50% found this document useful (2 votes)
498 views

Analysis of Stock Market Cycles With Fbprophet Package in Python PDF

This document discusses using the fbprophet package in Python to analyze stock market cycles. It uses Costco stock price data from 2015-2018 as an example. Different cycle lengths from 30 to 300 days are tested to find the optimal length that balances high return per cycle and low error. The analysis finds that a 252 day cycle provides a projected return of $17.12 per cycle with an out-of-sample mean squared error of 15.936, making it the best choice according to the criteria. Fbprophet allows customizing cycles beyond yearly, weekly or daily periods to better model stock market patterns.

Uploaded by

cidsant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
50% found this document useful (2 votes)
498 views

Analysis of Stock Market Cycles With Fbprophet Package in Python PDF

This document discusses using the fbprophet package in Python to analyze stock market cycles. It uses Costco stock price data from 2015-2018 as an example. Different cycle lengths from 30 to 300 days are tested to find the optimal length that balances high return per cycle and low error. The analysis finds that a 252 day cycle provides a projected return of $17.12 per cycle with an out-of-sample mean squared error of 15.936, making it the best choice according to the criteria. Fbprophet allows customizing cycles beyond yearly, weekly or daily periods to better model stock market patterns.

Uploaded by

cidsant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

01/05/2019 Analysis of Stock Market Cycles with fbprophet package in Python

Analysis of Stock Market Cycles with


prophet package in Python
Yin-Ta Pan Follow
Oct 12, 2018 · 6 min read

IMPORTANT: THIS IS NOT INVESTMENT ADVICE.

S tock market cycles are the long-term price patterns of stock markets
and are often associated with general business cycles. They are key to
technical analysis where the approach to investing is based on cycles or
repeating price patterns. If we have better understanding toward the
cycles of stock market, we can always buy with relative low-price and
sell at relative high price in each cycle, and we’ll always have positive
return. What a wonderful world! Of course, there is no superior
strategy in stock market which can make money forever, but
fbprophet package in Python or R can help us look deeper into the
hidden cycles in stock market. In this analysis, we can take a look at
how fbprophet can assist us to make an investment decision, and all
codes are available from here.

. . .

Introduction to fbprophet
F bprophet is an open source released by Facebook in order to provide
some useful guidance for producing forecast at scale. By default, it
would divide a time series into trend and seasonality, which might
contain yearly, weekly and daily. However, analysts can define their
own seasonality. To get better understanding about the package, the
document from Prophet is really helpful.

One of the feature for package is its simplicity and flexibility. Since
cycles in stock market we want to figure out are not limited to yearly,
weekly or daily, we should define our own cycles and find out which
can fit the data better. Besides, we should not use weekly seasonality
since there is no trading on weekend. We can also define our
‘self_define_cycle’ by add_seasonality function. All the settings can
be done with only two lines of code.

https://towardsdatascience.com/analysis-of-stock-market-cycles-with-fbprophet-package-in-python-7c36db32ecd0 1/10
01/05/2019 Analysis of Stock Market Cycles with fbprophet package in Python

1 m = Prophet(weekly_seasonality=False,yearly_seasonality=Fals
2 m.add_seasonality('self_define_cycle',period=8,fourier_order

Stock Market Cycles Analysis — taking


Costco as an example
We can use close prices for Costco from 2015/10/1 to 2018/10/1
as an example to have better understanding about what we are
doing. With pandas_datareader we can access stock price easily. The
documentation is here. In the Figure 1 we can see there is a strong
trend of growing price from 2015. However, there are still a lot of up-
and-down, or cycles, during the journey, and these are what we want to
make money.

Figure 1: Costco stock price from 2015/10/01 to 2018/10/01

For prediction models, one way to evaluate them is out-sample mean


squared error. We can use 2015/10/1 to 2018/3/31 for training and
keep the last 6 months for testing and calculating out-sample mean
squared error. Within each cycle, we can optimized our return by
buying at the lowest price and selling at the highest. To make the
process easier, we use self-define function cycle_analysis. The
output is a list containing projected return per cycle and out-sample
mean squared error. Inputs for the function require:

• data: Pandas dataframe with time index

• split_date: the date to split training and testing data

• cycle: periods (days) per cycle

https://towardsdatascience.com/analysis-of-stock-market-cycles-with-fbprophet-package-in-python-7c36db32ecd0 2/10
01/05/2019 Analysis of Stock Market Cycles with fbprophet package in Python

• mode: additive or multiplicative for seasonality (optional, default


additive)

• forecast_plot: whether to print the forecast plot or not (optional,


default False)

• print_ind: whether to print the projected return per cycle and out-
sample mean squared error or not (optional, default False)

1 def cycle_analysis(data,split_date,cycle,mode='additive',fo
2 training = data[:split_date].iloc[:-1,]
3 testing = data[split_date:]
4 predict_period = len(pd.date_range(split_date,max(data.
5 df = training.reset_index()
6 df.columns = ['ds','y']
7 m = Prophet(weekly_seasonality=False,yearly_seasonality
8 m.add_seasonality('self_define_cycle',period=cycle,four
9 m.fit(df)
10 future = m.make_future_dataframe(periods=predict_period
11 forecast = m.predict(future)
12 if forecast_plot:
13 m.plot(forecast)
14 plt.plot(testing.index,testing.values,'.',color='#f
15 plt.xlabel('Date',fontsize=12,fontweight='bold',col
16 plt.ylabel('Price',fontsize=12,fontweight='bold',co
17 plt.show()
18 ret = max(forecast.self_define_cycle)-min(forecast.self
19 model_tb = forecast['yhat']

In the Figure 2 and Figure 3, we applied the function with two different
lengths of cycle, 30 and 300 respectively, on Costco stock price and
took 2018/4/1 as the split date for training and testing. As we can see,
if we pick a length that is too short (e.g 30 days,) the return within one
cycle is small and we need to make transaction frequently(Figure 2;) in
contrast, if we pick a length which is too long (e.g 300 days,) it would
distort our prediction (Figure 3.)

https://towardsdatascience.com/analysis-of-stock-market-cycles-with-fbprophet-package-in-python-7c36db32ecd0 3/10
01/05/2019 Analysis of Stock Market Cycles with fbprophet package in Python

Figure 2: Prediction with cycle equal to 30 days

Figure 3: Prediction with cycle equal to 300 days

We can apply a loop over our cycle_analysis function to calculate


projected return and out-sample mean squared error for different
length of cycle, and we displayed the outcome in Figure 4. As we can
see, the longer the length, both projected return per cycle and out-
sample mean square error would increase. In consideration of the cost
of transaction, the projected return within per cycle should be greater
than $10. Under this constrain, we can choose the cycle that leads to
minimum out-sample mean squared error, and it is 252 days. The
projected return per cycle is $17.12 and out-sample mean squared
error is 15.936. Both are pretty good!

https://towardsdatascience.com/analysis-of-stock-market-cycles-with-fbprophet-package-in-python-7c36db32ecd0 4/10
01/05/2019 Analysis of Stock Market Cycles with fbprophet package in Python

Figure 4: Projected Return and Out-Sample Mean Squared Error for di erent length of cycle

Figure 5: Prediction with cycle equal to 252 days

To further illustrate the investment strategy, we can see the buying and
selling dates between 2015/10/1 and 2018/10/1. The Return_Dates

function could return all buy and sell dates as output, with input:

• forecast: fbprophet forecast object

https://towardsdatascience.com/analysis-of-stock-market-cycles-with-fbprophet-package-in-python-7c36db32ecd0 5/10
01/05/2019 Analysis of Stock Market Cycles with fbprophet package in Python

• stock_data: Pandas dataframe with time index

• cycle: length of cycle

• cycle_name: name for the cycle column in forecast object

• time_name: name for the time column in forecast object

1 def Return_Dates(forecast,stock_data,cycle,cycle_name = 'se


2 # find out the highest and lowest dates in the first cy
3 # We cannot simply search for all highest and lowest po
4 high = forecast.iloc[:cycle,]
5 high = high[high[cycle_name]==max(high[cycle_name])][ti
6 high = datetime.strptime(str(high.values[0])[:10],"%Y-%
7 low = forecast.iloc[:cycle,]
8 low = low[low[cycle_name]==min(low[cycle_name])][time_n
9 low = datetime.strptime(str(low.values[0])[:10],"%Y-%m-
10 end_dt = datetime.strptime(stock_data.index[-1],"%Y-%m-
11 find_list = stock_data.index.map(lambda x:datetime.strp
12 # Finding selling and buying dates with loop
13 sell_dt = []
14 sell_dt.append(high)
15 # Looking for new cycle until it goes beyond the last d
16 while high<end_dt:
17 high = high+timedelta(days=cycle)
18 dif = (find_list-high).days
19 high = find_list[abs(dif)==min(abs(dif))][0] # In o
20 sell_dt.append(high)
21 buy_dt = []
22 buy dt.append(low)

During 2015/10/1 and 2018/10/1, we would buy and sell Costco four
times. In summary, we would spend $604.56 on buying and get
$744.78 in return when we sold them on those specific dates. For a
simplified return rate (without considering reinvestment, time value
and so on,) it is 23.2% for 3 years. Probably not very attractive, but at
least it is positive return.

https://towardsdatascience.com/analysis-of-stock-market-cycles-with-fbprophet-package-in-python-7c36db32ecd0 6/10
01/05/2019 Analysis of Stock Market Cycles with fbprophet package in Python

Applying to more stocks


D efinitely, this method could be applied to as many stocks as
possible. We listed average buy price, average sell price, length of
cycle, out-sample mean squared error, number of buying, number of
selling and projected return within each cycle for Costco, Apple,
Microsoft, Home Depot and Nike.

https://towardsdatascience.com/analysis-of-stock-market-cycles-with-fbprophet-package-in-python-7c36db32ecd0 7/10
01/05/2019 Analysis of Stock Market Cycles with fbprophet package in Python

1 # Setting for analysis


2 Analysis_ticks = ['COST','AAPL','MSFT','HD','NKE']
3 start_date = '2015-10-01'
4 end_date = '2018-10-01'
5 opt_cycle = []
6 prot_return = []
7 MSE = []
8 buy_times = []
9 sell_times = []
10 avg_buy_price = []
11 avg_sell_price = []
12 # Loop over each stock
13 for ticker in Analysis_ticks:
14 stock_data = data.DataReader(ticker, 'iex', start_date,
15 testing_box = range(50,301)
16 return_box = []
17 mse_box = []
18 for cc in testing_box:
19 f = cycle_analysis(stock_data['close'],'2018-04-01'
20 return_box.append(f[0])
21 mse_box.append(f[1])
22 report = pd.DataFrame({'cycle':testing_box,'return':ret
23 possible_choice = report[report['return'] >10]
24 # If we cannot find a cycle with return greater than 10
25 if possible_choice.shape[0]>0:
26 c = possible_choice[possible_choice['mse']==min(pos
27 rp = possible_choice[possible_choice['mse']==min(po
28 mse = possible_choice[possible_choice['mse']==min(p
29 df = stock_data[:'2018-04-01'].iloc[:-1,]['close'].
30 df.columns = ['ds','y']
31 predict_period = len(pd.date_range('2018-04-01','20
32 m = Prophet(weekly_seasonality=False,yearly_seasona
33 m.add_seasonality('self_define_cycle',period=c,four
34 m.fit(df)
35 future = m.make_future_dataframe(periods=predict_pe
36 forecast = m.predict(future)
37 dt_list = Return_Dates(forecast,stock_data,c)
38 buy price = stock data loc[map(lambda x: x strftime

For Microsoft and Nike we cannot find any cycle matched to our
requirement of more than $10 return per cycle. For Costco, Apple and
Home Depot, we can find a cycle around 250 days and make a good
prediction and decent return.

https://towardsdatascience.com/analysis-of-stock-market-cycles-with-fbprophet-package-in-python-7c36db32ecd0 8/10
01/05/2019 Analysis of Stock Market Cycles with fbprophet package in Python

. . .

Summary
With the help of Python and fbprophet package, we can have better
understanding toward the stock market. Taking Costco as an example,
we can find a cycle with 252 days so that it can generate enough return
and have a good fit of data. According to the cycle we found, we can
have about 23% return for 3 years. Perhaps this investment strategy
cannot satisfy what you want, but you can always set your own
approaches based on your knowledge and experience. Powerful
fbprophet package can make your analysis on stock market much
deeper and easier.

https://towardsdatascience.com/analysis-of-stock-market-cycles-with-fbprophet-package-in-python-7c36db32ecd0 9/10
01/05/2019 Analysis of Stock Market Cycles with fbprophet package in Python

https://towardsdatascience.com/analysis-of-stock-market-cycles-with-fbprophet-package-in-python-7c36db32ecd0 10/10

You might also like