You've successfully subscribed to Alpaca Resources
Great! Next, complete checkout for full access to Alpaca Resources
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.
  • Home
  • We're hiring
  • Support
  • Forum
  • Docs
  • Log in
  • Sign up
Market Data

Creating a Market Regime Filter with FRED & Alpaca - Part Two

Leo Smigel
Leo Smigel

Welcome to the conclusion of this two-part series on how to incorporate economic data into a trading strategy. In part one, we discussed how to connect to FRED and query unemployment data.

How to Use Unemployment Figures to Build a Trading Algorithm - Part 1
This article shows you how to get to the economic data to build a trading algorithm. Here we use monthly unemployment figures.

In this post, we'll be building on this knowledge by creating a regime filter in Backtrader that will use both price and fundamental data.

If you're new here, my name is Leo Smigel. I discuss making more money in the markets using algorithmic trading at Analyzing Alpha. With hello's out of the way, let's get back to creating that indicator in Backtrader.

And as always, you can find the code on the Analyzing Alpha Github.


The Market Regime Strategy

Backtrader is a trading platform. This is great for experienced traders who need flexibility, but it can be daunting for newer algorithmic traders. Because of this, we’ll keep this post simple as a proof-of-concept and a starting point for you to continue your algorithmic journey. I’ll also provide guidance on how to improve both the code and the algorithm later in this post.

Backtrader: Getting Started Backtesting
Backtrader is an open-source python framework for trading and backtesting. Backtrader allows you to focus on writing reusable trading strategies, indicators, and analyzers instead of having to spend time building infrastructure.

We'll query the FRED data and check it for each day. If we were doing something more substantial, I would add the data to the feed as it's a cleaner solution and allows us to preprocess. For a production system, you would likely want to build out an economic and fundamental database in PostgreSQL.

We'll add a zero or a one depending upon if the unemployment rate is increasing or decreasing. True (1.0) values will turn our hedge on; however, we will only hedge if both the unemployment rate is rising while the benchmark price is decreasing.

Let's build out the basic framework referencing the first article in the backtrader/alpaca series.

Alpaca & Backtrader: Tools of the Trade (Part 1)
RSI stack strategy w/ Alpaca and Backtrader. In #1, we’ll cover connecting the Backtrader backtesting to Alpaca to load in data for multiple time frames.

A Basic Backtrader/Alpaca Framework

We first grab our imports and our API keys. You'll want to create a local_settings file that includes your data and add this to your .gitignore file so you don't accidentally upload your credentials. We've covered this before, so please review the previous backtrader articles if you need a refresher.

import alpaca_backtrader_api as alpaca
import backtrader as bt
import pytz
from datetime import datetime, date
from fredapi import Fred
from local_settings import alpaca_paper_settings, fred_settings

ALPACA_KEY_ID = alpaca_paper_settings['api_key']
ALPACA_SECRET_KEY = alpaca_paper_settings['api_secret']
ALPACA_PAPER = True
FRED_API_KEY = fred_settings['api_key']

We'll then add the start and end dates. We'll use the S&P 500 index as our benchmark. We use an index because it's less volatile than individual equities and helps prevent us from being whipsawed. This is also why trend following typically works better on indices than on individual equities.

fromdate = datetime(2020,6,1)
todate = datetime(2020,10,31)
tickers = ['SPY']

Next up, we grab the federal reserve data from our article one. We compare this month's unemployment rate with last month's unemployment rate. We set it to true (1.0) if the unemployment rate is increasing.

Since we're using sandbox data, we'll only compare it with the previous month. In a production algorithm, you'll likely want to use multiple longer timeframes.

fred = Fred(api_key=FRED_API_KEY)
unrate = fred.get_series('unrate', observation_start=fromdate, observation_end=todate)
monthly_unrate_increasing = (unrate > unrate.shift(1)).dropna().astype(float)

Next up, we create our strategy class. We'll define our technical_hedge completely within __init__. Defining your indicators in __init__ is preferred due to preprocessing and makes your code cleaner overall.

We'll loop through each day, checking for both the fundamental_hedge and the technical_hedge to return true. If they do, we'll hedge. If they don't, we'll be long the market.

def next(self):      
		day = self.data0.datetime.date(ago=0)
        month = date.strftime(day, "%Y-%m")
        fundamental_hedge = monthly_unrate_increasing.loc[month][0]

        if self.technical_hedge[0] and fundamental_hedge:
            print(f"{day}: Hedging:\n**Negative price action: {self.technical_hedge[0]}. Unemployment increasing: {fundamental_hedge}")
        else:
            print(f"{day}: Not hedging:\n**Negative price action: {self.technical_hedge[0]}. Unemployment increasing: {fundamental_hedge}")

It'll be up to you to determine your hedging strategy based on your goals.

If you're trading within a tax-advantaged account, you probably can't short individual equities. In this instance, you'll likely want to purchase inverse ETF(s) such as the ProShares Ultrashort S&P 500, and volatility weigh the position to be near market neutral.

If you have margin enabled, you can up your short book to a level where you feel comfortable.

Additionally, when thinking about hedging, you'll likely want to cover three scenarios:

  1. A long down-trending market (2008)
  2. A sharply downward market (2020)
  3. And temporarily overextended markets (Frequent)

The Takeaway

We developed a simple framework showing how to incorporate fundamental data with price action to create a better regime filter. While this is nowhere near a stopping point, it's a great place to start. We also discussed a few ways to implement a hedging strategy.

Again all of the code from this tutorial series can be found on the following GitHub repository:

leosmigel/analyzingalpha
Contribute to leosmigel/analyzingalpha development by creating an account on GitHub.

If you’re like me and can’t get enough of this stuff, please make sure to continue learning from Alpaca and check out my website at Analyzing Alpha.

Analyzing Alpha
Analyzing what works in trading and investing using data science.

Technology and services are offered by AlpacaDB, Inc. Brokerage services are provided by Alpaca Securities LLC (alpaca.markets), member FINRA/SIPC. Alpaca Securities LLC is a wholly-owned subsidiary of AlpacaDB, Inc.

You can find us @AlpacaHQ, if you use twitter.

Market DataCode Examples

Leo Smigel

Former tech entrepreneur turned algorithmic trader. I analyze what works in trading and investing using data science.