Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Python for Algorithmic Trading Cookbook
  • Toc
  • feedback
Python for Algorithmic Trading Cookbook

Python for Algorithmic Trading Cookbook

By : Jason Strimpel
4.2 (19)
close
Python for Algorithmic Trading Cookbook

Python for Algorithmic Trading Cookbook

4.2 (19)
By: Jason Strimpel

Overview of this book

Discover how Python has made algorithmic trading accessible to non-professionals with unparalleled expertise and practical insights from Jason Strimpel, founder of PyQuant News and a seasoned professional with global experience in trading and risk management. This book guides you through from the basics of quantitative finance and data acquisition to advanced stages of backtesting and live trading. Detailed recipes will help you leverage the cutting-edge OpenBB SDK to gather freely available data for stocks, options, and futures, and build your own research environment using lightning-fast storage techniques like SQLite, HDF5, and ArcticDB. This book shows you how to use SciPy and statsmodels to identify alpha factors and hedge risk, and construct momentum and mean-reversion factors. You’ll optimize strategy parameters with walk-forward optimization using VectorBT and construct a production-ready backtest using Zipline Reloaded. Implementing all that you’ve learned, you’ll set up and deploy your algorithmic trading strategies in a live trading environment using the Interactive Brokers API, allowing you to stream tick-level data, submit orders, and retrieve portfolio details. By the end of this algorithmic trading book, you'll not only have grasped the essential concepts but also the practical skills needed to implement and execute sophisticated trading strategies using Python.
Table of Contents (16 chapters)
close

Fetching historic futures data with the OpenBB Platform

Traders use continuous futures data for backtesting trading strategies. Futures traders use the roll from one contract to another as a potential opportunity for profit. Some traders simply pick a date before expiration to roll to the next contract, while others use sophisticated techniques involving open interest. This basis trade is persistently one of the most popular trading strategies for futures traders. These traders want control over the data that’s used to compute the basis trade, so acquiring individual contract data is important. This recipe will guide you through the process of using the OpenBB Platform to fetch individual futures contract data.

Getting ready…

By now, you should have the OpenBB Platform installed in your virtual environment. If not, go back to the beginning of this chapter and get it set up.

How to do it…

We’ll use the futures functionality in the OpenBB Platform to download individual futures data for free:

  1. Import pandas and the OpenBB Platform:
    import pandas as pd
    from openbb import obb
    obb.user.preferences.output_type = "dataframe"
  2. Download the current futures curve for the VIX futures contract from the Chicago Board Options Exchange (CBOE):
    data = obb.derivatives.futures.curve(symbol="VX")
  3. Inspect the resulting DataFrame:
    print(data)

    Running the preceding code generates the futures curve for the VIX futures contract:

Figure 1.6: Settlement prices for the forward Eurodollar futures contracts

Figure 1.6: Settlement prices for the forward Eurodollar futures contracts

  1. Update the DataFrame index to the expiration dates and plot the settlement prices:
    data.index = pd.to_datetime(data.expiration)
    data.plot()

    By running the proceeding code, we plot the VIX futures curve:

Figure 1.7: VIX futures curve

Figure 1.7: VIX futures curve

There’s more…

You can use the obb.derivatives.futures.historical method to get historical data for an individual expiration. Stitching together data across a range of years can provide insight into the market’s expectation of supply and demand of the underlying commodity:

  1. First, create a list containing the year and month expirations you’re interested in:
    expirations = [
        "2024-12",
        "2025-12",
        "2026-12",
        "2027-12",
        "2028-12",
        "2029-12",
        "2030-12",
    ]
  2. The preceding code creates a Python list of expiration years and dates in string format. Now, loop through each of the expirations to download the data:
    contracts = []
    for expiration in expirations:
        df = (
            obb
            .derivatives
            .futures
            .historical(
                symbol="CL",
                expiration=expiration,
                start_date="2020-01-01",
                end_date="2022-12-31"
            )
        ).rename(columns={
            "close": expiration
        })
        contracts.append(df[expiration])
  3. For each of the contracts, use the OpenBB Platform to download historical futures data for the CL contract between January 1, 2020, and 31 December 31, 2022. Using the pandas rename method, change the column name from "close" to the expiration date. Finally, append the newly created pandas DataFrame to a list of DataFrames:
    historical = (
        pd
        .DataFrame(contracts)
        .transpose()
        .dropna()
    )
  4. Concatenate the DataFrames together, swap the columns and rows using the transpose method, and drop any records with no data using the dropna method. Inspect the resulting DataFrame:
    print(historical)

    By printing the DataFrame, we will see the historical settlement prices:

Figure 1.8: Historic settlement prices for the December CL futures contract

Figure 1.8: Historic settlement prices for the December CL futures contract

The result is the historical data between January 2020 and December 2022 for each of the December expirations between 2023 and 2030:

  1. To visualize the market’s expectation of the future supply and demand of the December contract, you can plot the last price:
    historical.iloc[-1].plot()

    Here's the output:

Figure 1.9: Futures curve for the December CL contract

Figure 1.9: Futures curve for the December CL contract

See also

For more on the OpenBB Platform futures functionality, you can browse the following documentation:

bookmark search playlist download font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete