Next-Level Trading: Mastering Time Series Analysis

Using Facebook Prophet with EODHD API data for technical analysis

Michael Whittle
Level Up Coding

--

Licensed Image from Adobe Stock

This article will introduce trading with time series analysis using market data from EODHD API with Facebook Prophet.

What is a time series?

A time series is a sequence of data points ordered in time. E.g., keeping track of your height on the kitchen wall over the years; only instead of marks on the wall, you’ve got a list of figures that showed how something changed as time ticked by. This could be anything that changes or can be measured as time goes on — like the temperature every day, stock prices, the amount of tea consumed in the UK every month, you name it. People use time series to look back and see how things have changed, or to make a stab at predicting what might happen in the future based on past trends. It’s a bit like trying to guess next week’s weather by looking at what it’s been like for the same week over the past few years.

What is Facebook Prophet?

Facebook Prophet is a forecasting tool developed by the data science team at Facebook. It’s designed to make it easier for experts and non-experts alike to predict future trends based on historical data. The beauty of Prophet is its simplicity and flexibility; it can handle daily, weekly, or yearly seasonality, manage holidays and special events, and it’s robust against missing data and shifts in trend. Essentially, it’s a bit like having a smart assistant to help you see into the future based on past patterns.

Now, when it comes to stock trading, Prophet can be quite handy. Although stock market data is notoriously volatile and influenced by countless factors, Prophet can help identify potential trends and seasonality in stock prices. Here’s how you might use it:

Trend Analysis: By feeding historical stock price data into Prophet, you can get forecasts that highlight potential upward or downward trends. This can be useful for identifying long-term investment opportunities.

Seasonality Insights: If a stock shows regular patterns of behavior (like certain industries might do around specific holidays or events), Prophet can help highlight these seasonal trends. This could inform strategies like buying ahead of anticipated rises or selling before expected dips.

Handling Market Events: You can include information about specific events (such as product launches, regulatory changes, or economic reports) as additional regressors in your model to see how such events historically impact stock prices. This can help in planning around these events.

It’s worth noting, though, that stock markets are complex and influenced by a myriad of unpredictable factors. While Prophet can offer insights and help inform decisions, it’s not a silver bullet. Successful trading requires a mix of tools, judgement, and sometimes a bit of luck. Always remember, investing in the stock market carries risks, and it’s possible to lose money as well as make it. It’s always a good idea to use more than one analysis tool.

What other time series analysis tools are there?

I use a variety of time series analysis tools when it comes to trading analysis, but for the purpose of this article, I wanted to introduce Facebook Prophet. There are several popular time series analysis tools and methods aside from Facebook Prophet, each with its own strengths and suited for different aspects of trading strategy development and market analysis.

Here’s a rundown of some widely-used ones:

  1. ARIMA (AutoRegressive Integrated Moving Average): This method is great for analysing and forecasting time series data when there’s a clear trend or seasonality. ARIMA models are particularly useful for short-term forecasting, and they work by considering past values and errors.
  2. Moving Averages (MA): Simple yet powerful, moving averages smooth out price data to identify trends. Traders often use simple moving averages (SMA) and exponential moving averages (EMA) to spot trend direction and reversals.
  3. GARCH (Generalized Autoregressive Conditional Heteroskedasticity): This model is used to estimate volatility in financial markets. It’s particularly handy for risk management and options pricing because it can model the variance of returns, which is a key aspect of financial market volatility.
  4. Machine Learning Models: Various machine learning techniques, including regression models, decision trees, support vector machines, and neural networks, are increasingly popular for predicting stock prices. These models can handle large datasets and uncover complex patterns that might not be immediately apparent.
  5. Technical Indicators: Tools like the Relative Strength Index (RSI), Bollinger Bands, MACD (Moving Average Convergence Divergence), and Fibonacci retracements are used by traders to analyse market sentiment, identify potential buy or sell signals, and anticipate market movements.
  6. Quantitative Trading Models: These involve developing algorithms based on quantitative analysis to make trading decisions. They can incorporate various statistical, mathematical, and machine learning techniques to optimise trading strategies.
  7. Monte Carlo Simulation: Used to assess the risk and uncertainty in predicting stock prices and market movements. It runs a vast number of simulations to predict the outcome of an investment under different conditions.
  8. Event Study Methodology: This method assesses the impact of specific events (like earnings announcements, mergers, and acquisitions) on stock prices. It’s useful for understanding how different types of news and market developments can affect stock valuation.

Each of these tools and methods has its own set of assumptions, strengths, and weaknesses. Traders and analysts often use a combination of these approaches to develop more robust trading strategies and to mitigate risks associated with the volatile nature of financial markets.

What is EODHD API?

EOD Historical Data (EODHD) is a company that provides financial market data and APIs (Application Programming Interfaces) designed for analysing market trends, building financial tools, or developing investment strategies. Their offerings are quite comprehensive and include historical stock prices, fundamentals, financial statements, dividend data, and more, covering a wide range of assets like stocks, ETFs, mutual funds, forex, and commodities across various global exchanges.

The EODHD API is particularly useful for developers, quantitative analysts, and financial technology companies because it allows easy access to a vast amount of financial data. This can be integrated into applications for purposes like backtesting trading strategies, performing stock market analysis, or even powering personal finance tools. The API is designed to be straightforward to use, providing data in various formats (like JSON and CSV) that can be easily consumed by different software and applications.

In essence, EOD Historical Data offers a toolkit for anyone looking to dive deep into financial market analysis, providing the data backbone for investment decision-making or financial application development.

I’ve been a customer of theirs for years, and they provide the majority of the data I use for trading analysis. I initially developed the official “eodhd” Python library for them. For me personally, I find this the easiest way to access the data, but they have many addons.

Retrieving our data

For the purpose of this article, I’m going to retrieve daily S&P 500 index data from EODHD API.

I’ll be using the “eodhd” Python library.

python3 -m pip install eodhd -U
from eodhd import APIClient

API_KEY = "<YOUR_KEY>"

api = APIClient(API_KEY)
df = api.get_historical_data("GSPC.INDX", "d")

print(df)
Screenshot by Author

We now have a dataframe with 205 days of data to work with.

Using Facebook Prophet

The next step is to install the Facebook Prophet Python API.

python3 -m pip install prophet -U
from prophet import Prophet

The library only requires two columns of data. The date/time, and the value. The library requires the date/time to be represented as “ds” and the value to be represented as “y”. Let’s make that adjustment now.

df["date"] = df.index
df_prophet = df[["date", "adjusted_close"]].rename(columns={"date": "ds", "adjusted_close": "y"})

print(df_prophet)
Screenshot by Author

Initialise and Fit the Model

We have our data ready in the correct format, and now we need to intialise and fit our model.

m = Prophet(daily_seasonality=True)
m.fit(df_prophet)

You will notice that I set “daily_seasonality” to True. In Prophet, the “daily_seasonality” parameter is used to model daily patterns in time series data, crucial for forecasting accuracy, especially in trading. This feature captures patterns related to market opening/closing times, intraday trends, and liquidity variations. It’s particularly useful for data with multiple intraday points, enabling more precise forecasts by accounting for the daily fluctuations inherent in financial markets. If you want to apply this to crypto markets where they are always open, you probably don’t need to enable this.

Creating our “future” dataframe

future = m.make_future_dataframe(periods=30)

print(future)

The “periods” of 30 will create a placeholder for the next 30 days into the future as we are dealing with daily data.

Screenshot by Author

Making the Forecast

forecast = m.predict(future)

print(forecast)
Screenshot by Author

In a Prophet forecast, several key columns are particularly important for interpreting the results:

  • yhat: This is the forecasted value. It represents the model’s prediction for the target variable at a specific time. It’s the primary outcome of interest as it provides the predicted value based on the model’s understanding of underlying trends and seasonalities.
  • yhat_lower and yhat_upper: These columns provide the lower and upper bounds of the forecast’s confidence interval, respectively. They offer a range within which the actual value is expected to fall, giving an idea of the prediction’s uncertainty. Wider intervals suggest greater uncertainty, while narrower intervals suggest more confidence in the prediction.
  • trend: This column shows the long-term trend component of the data. It indicates the general direction in which the data is moving, abstracted from seasonal fluctuations or other cyclical patterns.
  • ds: Although not a forecast output per se, the “ds” column is crucial as it contains the date-time stamps for each prediction, indicating when each forecasted value (yhat) applies.

Plotting the Forecast

Prophet actually comes with some really impressive graphing functionality, most likely based on Matplotlib.

fig1 = m.plot(forecast)
Screenshot by Author
fig2 = m.plot_components(forecast)
Screenshot by Author

I hope you found this article interesting and useful. If you would like to be kept informed, please don’t forget to follow me and sign up to my email notifications.

If you liked this article, I recommend checking out EODHD APIs on Medium. They have some interesting articles.

Michael Whittle

--

--

Solution Architect — CCIE R&S #24223 | Full-Stack / Blockchain / Web3 Developer | Security Specialist | PyCryptoBot Creator