Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Python for Algorithmic Trading Cookbook

You're reading from   Python for Algorithmic Trading Cookbook Recipes for designing, building, and deploying algorithmic trading strategies with Python

Arrow left icon
Product type Paperback
Published in Aug 2024
Publisher Packt
ISBN-13 9781835084700
Length 406 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Jason Strimpel Jason Strimpel
Author Profile Icon Jason Strimpel
Jason Strimpel
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Chapter 1: Acquire Free Financial Market Data with Cutting-Edge Python Libraries FREE CHAPTER 2. Chapter 2: Analyze and Transform Financial Market Data with pandas 3. Chapter 3: Visualize Financial Market Data with Matplotlib, Seaborn, and Plotly Dash 4. Chapter 4: Store Financial Market Data on Your Computer 5. Chapter 5: Build Alpha Factors for Stock Portfolios 6. Chapter 6: Vector-Based Backtesting with VectorBT 7. Chapter 7: Event-Based Backtesting Factor Portfolios with Zipline Reloaded 8. Chapter 8: Evaluate Factor Risk and Performance with Alphalens Reloaded 9. Chapter 9: Assess Backtest Risk and Performance Metrics with Pyfolio 10. Chapter 10: Set Up the Interactive Brokers Python API 11. Chapter 11: Manage Orders, Positions, and Portfolios with the IB API 12. Chapter 12: Deploy Strategies to a Live Environment 13. Chapter 13: Advanced Recipes for Market Data and Strategy Management 14. Index 15. Other Books You May Enjoy

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

Quick tip: Need to see a high-resolution version of this image? Open this book in the next-gen Packt Reader or view it in the PDF/ePub copy.

The next-gen Packt Reader and a free PDF/ePub copy of this book are included with your purchase. Unlock them by scanning the QR code below or visiting https://www.packtpub.com/unlock/9781835084700.

  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:

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Python for Algorithmic Trading Cookbook
You have been reading a chapter from
Python for Algorithmic Trading Cookbook
Published in: Aug 2024
Publisher: Packt
ISBN-13: 9781835084700
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime
Modal Close icon
Modal Close icon