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

Working with stock market data with the OpenBB Platform

You may remember the meme stock hysteria that sent GameStop’s stock up 1,744% in January 2021. One of the good things that came from that episode was the GameStonk terminal, now rebranded as OpenBB. OpenBB is the most popular open-source finance projects on GitHub for good reason: it provides a single interface to access hundreds of data feeds from one place in a standard way. OpenBB has a command-line interface that is great for manual investment research. But when it’s time to get data into Python, you want the OpenBB Platform. This recipe will guide you through the process of using the OpenBB Platform to fetch stock market 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. The OpenBB Platform is free to use and offers a web-based UI to manage your configuration files, store API keys, and get code walkthroughs and examples. Sign up for a free Hub account at https://my.openbb.co/login. The popular course, Getting Started with Python for Quant Finance, uses OpenBB exclusively for all the code. Check out https://www.pyquantnews.com/getting-started-with-python-for-quant-finance for information on how to join.

How to do it…

Using the OpenBB Platform involves one import:

  1. Import the OpenBB Platform:
    from openbb import obb
    obb.user.preferences.output_type = "dataframe"
  2. Use the historical method to download price data for the SPY ETF:
    data = obb.equity.price.historical("SPY", provider="yfinance")
  3. Inspect the resulting DataFrame:
    print(data)

    Running the preceding code generates a pandas DataFrame and prints the data to the screen:

Figure 1.1: Historic price data for SPY

Figure 1.1: Historic price data for SPY

How it works…

The OpenBB Platform follows an easy-to-understand namespace convention. All the methods for acquiring stock price data are methods on openbb.equity.

The historical method accepts a ticker symbol and returns the open, high, low, close, adjusted close, volume, dividend, and split adjustments in a pandas DataFrame. The additional parameters you can specify are as follows:

  • start_date: Start date to get data from with
  • interval: Interval (in minutes) to get data—that is, 1, 5, 15, 30, 60, or 1,440
  • end_date: End date to get data from with
  • provider: Source of data extracted

There’s more…

An important benefit of using the OpenBB Platform is choosing your data source. By default, the OpenBB Platform will attempt to download data from free sources such as Yahoo! Finance. In most OpenBB Platform calls, you can indicate a different source. To use a source that requires an API key (either free or paid), you can configure it in the OpenBB Hub.

Tip

Check out the OpenBB Platform documentation for the latest functionality: https://docs.openbb.co.

Let’s look at some more of the functions of the OpenBB Platform.

Comparison of fundamental data

Not only can the OpenBB Platform download fundamental data in an organized and usable way, but it can also concatenate it in a single Pandas DataFrame for further analysis.

We can use the following code to see the balance sheet metrics from AAPL and MSFT:

obb.equity.fundamental.metrics(
    "AAPL,MSFT",
    provider="yfinance"
)

The output of the preceding snippet is a pandas DataFrame with fundamental data for each ticker that was passed:

Figure 1.2: Balance sheet data for MSFT and AAPL

Figure 1.2: Balance sheet data for MSFT and AAPL

Building stock screeners

One of the most powerful features of the OpenBB Platform is the custom stock screener. It uses the Finviz stock screener under the hood and surfaces metrics across a range of stocks based on either pre-built or custom criteria. See the documentation for more on how to use the OpenBB screener functions (https://docs.openbb.co/platform/reference/equity/screener):

  1. Create an overview screener based on a list of stocks using the default view:
    obb.equity.compare.groups(
        group="industry",
        metric="valuation",
        provider="finviz"
    )

    The output of the preceding snippet is the following pandas DataFrame:

Figure 1.3: Results of a comparison screener between F, GE, and TSLA

Figure 1.3: Results of a comparison screener between F, GE, and TSLA

  1. Create a screener that returns the top gainers from the technology sector based on a preset:
    obb.equity.compare.groups(
        group="technology",
        metric="performance",
        provider="finviz"
    )

    The output of the preceding snippet is the following pandas DataFrame:

Figure 1.4: Results of a screener showing the day’s top-gaining stocks

Figure 1.4: Results of a screener showing the day’s top-gaining stocks

  1. Create a screener that presents an overview grouped by sector:
    obb.equity.compare.groups(
        group="sector",
        metric="overview",
        provider="finviz"
    )

    The output of the preceding snippet is the following pandas DataFrame:

Figure 1.5: Results of a screener grouped by sector

Figure 1.5: Results of a screener grouped by sector

See also

For more on OpenBB and the Finviz stock screener, check out the following resources:

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