Movatterモバイル変換


[0]ホーム

URL:


Packt
Search iconClose icon
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.
Profile icon
Account
Close icon

Change country

Modal Close icon
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timerSALE ENDS IN
0Days
:
00Hours
:
00Minutes
:
00Seconds
Home> Data> Data Analysis> Python for Algorithmic Trading Cookbook
Python for Algorithmic Trading Cookbook
Python for Algorithmic Trading Cookbook

Python for Algorithmic Trading Cookbook: Recipes for designing, building, and deploying algorithmic trading strategies with Python

Arrow left icon
Profile Icon Jason Strimpel
Arrow right icon
Mex$885.99Mex$984.99
Full star iconFull star iconFull star iconFull star iconHalf star icon4.2(20 Ratings)
eBookAug 2024404 pages1st Edition
eBook
Mex$885.99 Mex$984.99
Paperback
Mex$1230.99
Subscription
Free Trial
Arrow left icon
Profile Icon Jason Strimpel
Arrow right icon
Mex$885.99Mex$984.99
Full star iconFull star iconFull star iconFull star iconHalf star icon4.2(20 Ratings)
eBookAug 2024404 pages1st Edition
eBook
Mex$885.99 Mex$984.99
Paperback
Mex$1230.99
Subscription
Free Trial
eBook
Mex$885.99 Mex$984.99
Paperback
Mex$1230.99
Subscription
Free Trial

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Table of content iconView table of contentsPreview book icon Preview Book

Python for Algorithmic Trading Cookbook

Acquire Free Financial Market Data with Cutting-Edge Python Libraries

A May 2017 Economist cover declared data to be the world’s most valuable resource. It’s none truer than in algorithmic trading. As algorithmic traders, it’s our job to acquire and make sense of billions of rows of market data for use in trading algorithms. In this context, it’s crucial to gather high-quality, reliable data that can adequately support trading algorithms and market research. Luckily for us, it’s possible to acquire high-quality data for free (ornearly free).

This chapter offers recipes for a series of different Python libraries—including the cutting-edge OpenBB Platform—to acquire free financial market data using Python. One of the primary challenges most non-professional traders face is getting all the data required for analysis together in one place. The OpenBB Platform addresses this issue. We’ll dive into acquiring data for a variety of assets, including stocks, options, futures (both continuous and individual contracts), andFama-French factors.

One crucial point to remember is that data can vary across different sources. For instance, prices from two sources might differ due to distinct data sourcing methods or different adjustment methods for corporate actions. Some of the libraries we’ll cover might download data for the same asset from the same source. However, libraries vary in how they return that data based on options that help you preprocess the data in preparationfor research.

Lastly, while we’ll focus heavily on mainstream financial data in this chapter, financial data is not limited to prices. The concept of “alternative data,” which includes non-traditional data sources such as satellite images, web traffic data, or customer reviews, can be an important source of information for developing trading strategies. The Python tools to acquire and process this type of data are outside the scope of this book. We’ve intentionally left out the methods of acquiring and processing this type of data since it’s covered in other resources dedicated tothe topic.

In this chapter, we’ll cover thefollowing recipes:

  • Working with stock market data with theOpenBB Platform
  • Fetching historic futures data with theOpenBB Platform
  • Navigating options market data with theOpenBB Platform
  • Harnessing factor datausingpandas_datareader

Technical requirements

This book relies on the Anaconda distribution of Python. We’ll use Jupyter Notebook and Python script files to write the code. Unless specified otherwise, all the code can be written inJupyter Notebooks.

Download and install the Anaconda distribution of Python. You can do this by going tohttps://www.anaconda.com/download. Depending on your operating system, the instructions for downloading and installing will vary. Please refer to the Anaconda documentation fordetailed instructions.

Anaconda ships with a package manager calledconda. Package managers make it easy to install, remove, and update Python packages. There’s a great cheat sheet for theconda package manager that you can downloadfromhttps://docs.conda.io/projects/conda/en/4.6.0/_downloads/52a95608c49671267e40c689e0bc00ca/conda-cheatsheet.pdf.

Once you’ve installed the Anaconda distribution, open your Terminal on Mac or Linux or the Anaconda Prompt on Windows. If you’re a Windows user, make sure to use the Command Prompt instead of the Powershell prompt. Then followthese steps:

  1. Update thecondapackage manager:
    conda update -n base conda -y
  2. Create avirtual environment:
    conda create -n my-quant-stack python=3.10 -y
  3. After the installation process is complete, activatethe environment:
    conda activate my-quant-stack
  4. Install Jupyter Notebook using the package manager that ships withPython,pip:
    pip install notebook matplotlib

This will set up a virtual environment using Python 3.10 and installJupyter Notebook.

This chapter will use Two Python libraries to acquire financial market data: the OpenBB Platform andpandas_datareader. The good news is that installing the OpenBB Platform installs many of the libraries you will need to acquire financial market data, includingpandas_datareader. As such, there is no need to install thelibraries separately.

Install the OpenBB Platform with all extensions and providers (both officially supported and community-maintained ones)usingpip:

pip install openbb[all]

This is the easiest way to set up the OpenBB Platform forthis book.

Important note

In a macOS zsh Terminal shell, add quotation marks around the libraryname:"openbb[all]"

To install asingle extension:

pip install openbb[charting]pip install openbb[ta]

Or install asingle provider:

pip install openbb[yfinance]

To install the Nightly distribution (this installs all extrasby default):

pip install openbb-nightly

Important note

At the time of writing, installing the OpenBB Platform usingpip isn’t compatible with environments such as Google Colab and Kaggle since they come with preinstalled packages that can conflict with the ones used with the OpenBB Platform. If you run into trouble installing the OpenBB Platform, please check the online documentation for the mostup-to-date instructions.

Working with stock market data with the OpenBB Platform

You may remember thememe 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 stockmarket 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 outhttps://www.pyquantnews.com/getting-started-with-python-for-quant-finance for information on howto join.

How to do it…

Using the OpenBB Platform involvesone import:

  1. Import theOpenBB Platform:
    from openbb import obbobb.user.preferences.output_type = "dataframe"
  2. Use thehistorical method todownload price data for theSPY ETF:
    data = obb.equity.price.historical("SPY", provider="yfinance")
  3. Inspect theresulting DataFrame:
    print(data)

    Running the preceding code generates a pandas DataFrame and prints the data tothe 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 aremethodsonopenbb.equity.

Thehistorical 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 areas follows:

  • start_date: Start date to get datafrom with
  • interval: Interval (in minutes) to get data—that is, 1, 5, 15, 30, 60,or 1,440
  • end_date: End date to get datafrom with
  • provider: Source ofdata 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 theOpenBB Hub.

Tip

Check out the OpenBB Platform documentation forthe latestfunctionality:https://docs.openbb.co.

Let’s look at some more of the functions of theOpenBB 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 forfurther analysis.

We can use the following code to see the balance sheet metrics fromAAPLandMSFT:

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

The output of the preceding snippet is a pandas DataFrame with fundamental data for each ticker thatwas 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 ofthe OpenBB Platform is the custom stock screener. It uses theFinviz 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 screenerfunctions (https://docs.openbb.co/platform/reference/equity/screener):

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

    The output of the preceding snippet is the followingpandas 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 ona preset:
    obb.equity.compare.groups(    group="technology",    metric="performance",    provider="finviz")

    The output of the preceding snippet is the followingpandas 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 groupedby sector:
    obb.equity.compare.groups(    group="sector",    metric="overview",    provider="finviz")

    The output of the preceding snippet is the followingpandas 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 theFinviz stock screener, check out thefollowing resources:

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 beforeexpiration to roll to the next contract, while others use sophisticated techniques involving open interest. Thisbasis trade is persistently one of the most popular trading strategies for futures traders. These traders wantcontrol 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 futurescontract 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 itset up.

How to do it…

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

  1. Import pandas and theOpenBB Platform:
    import pandas as pdfrom openbb import obbobb.user.preferences.output_type = "dataframe"
  2. Download thecurrent futures curve for the VIX futures contract from theChicago Board OptionsExchange (CBOE):
    data = obb.derivatives.futures.curve(symbol="VX")
  3. Inspect theresulting DataFrame:
    print(data)

    Running the preceding code generates the futures curve for the VIXfutures 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 thesettlement prices:
    data.index = pd.to_datetime(data.expiration)data.plot()

    By running theproceeding code, we plot the VIXfutures curve:

Figure 1.7: VIX futures curve

Figure 1.7: VIX futures curve

There’s more…

You can use theobb.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 anddemand of theunderlying commodity:

  1. First, create a list containing the year and month expirations you’reinterested in:
    expirations = [    "2024-12",    "2025-12",    "2026-12",    "2027-12",    "2028-12",    "2029-12",    "2030-12",]
  2. The preceding code createsa Python list of expiration years and dates in string format. Now, loop through each of theexpirations to downloadthe 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 pandasrename method, change the column name from"close" to the expiration date. Finally, append the newly created pandas DataFrame to a listof DataFrames:
    historical = (    pd    .DataFrame(contracts)    .transpose()    .dropna())
  4. Concatenate the DataFrames together, swap the columns and rows using thetranspose method, and drop any recordswith no data using thedropna method. Inspect theresulting DataFrame:
    print(historical)

    By printing the DataFrame, we will see the historicalsettlement 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 historicaldata between January 2020 and December 2022 for each of the December expirationsbetween 2023and 2030:

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

    Here'sthe 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 OpenBBPlatform futures functionality, youcan browse thefollowing documentation:

Navigating options market data with the OpenBB Platform

Options are exchange-listed derivative contracts that convey the right (but not the obligation) to buy or sell the underlying stock at a certain price on or before a certain expiration date. Options are among the mostversatile financial instruments in the market. They allow traders to define their risk profiles before entering trades andexpress market views not only on the direction of the underlying but the volatility. While options offer a high degree of flexibility for trading, this feature complicates data collection for researchand backtesting.

A single underlying stock can have an array of options contracts with different combinations of strike prices and expiration dates. Collecting and manipulating this data is a challenge. The combination of options contracts for all strikes and expiration dates is commonly referred to as an options chain. There can be thousands of individual options contracts at a given time for a single underlying stock. Not only does the number of individual contracts pose a challenge, but getting price data has historically been expensive. With the introduction of the OpenBB Platform, it is now only a few lines of Python code to download options chains into a pandas DataFrame. This recipe will walk you through acquiring options data using theOpenBB Platform.

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 itset up.

How to do it…

Similar to how we used the OpenBB Platform for futures data, we can use it for optionsdata too:

  1. Import the OpenBB Platform and Matplotlibfor visualization:
    from openbb import obbobb.user.preferences.output_type = "dataframe"
  2. Use thechains method to download the entireoptions chain:
    chains = obb.derivatives.options.chains(symbol="SPY")
  3. Inspect theresulting DataFrame:
    chains.info()

    By running the precedingcode, we’ll see the details of the optionschains data:

Figure 1.10: Preview of the data downloaded for the SPY options chains

Figure 1.10: Preview of the data downloaded for the SPY options chains

Note that there are 8,518 options contracts for theSPY Exchange Traded Fund (ETF) that can be downloaded from CBOE (for free).

How it works…

Theobb.derivatives.options.chains method downloads the entire options chain and stores it in a pandas DataFrame. Theobb.derivatives.options.chains has an additionaloptional parameter:

  • provider: The source from which the data should be downloaded. The default is CBOE. You can also select Tradier, Intrinio, or TMX. Note that for Tradier, Intrinio, and TMX, you need to provide your API key, which can be configured in theOpenBB Hub.

There’s more…

You can use the OpenBB Platform to download historical options data for a single contract. To do this, you need theoption symbol.

We’ll use theobb.equity.price.historical method to get the historical options data for an SPY call option with a strike price of $550 expiring on December20, 2024:

data = obb.equity.price.historical(    symbol="SPY241220C00550000",    provider="yfinance")[["close", "volume"]]

The result is a pandas DataFrame with the closing price and volume of theoptions contract.

Figure 1.11: Closing prices and volume of the SPY options contract

Figure 1.11: Closing prices and volume of the SPY options contract

Options Greeks

Options Greeks measure how options prices change given a change in one of the inputs to an options pricing model. For example,delta measures how an options pricechanges given a change in the underlyingstock price.

Usingobb.derivatives.options.chains, the OpenBB Platform returns the most used Greeks including Delta, Gamma, Theta, Vega,and Rho.

See also

Options are a fascinating and deep topic that is rich with opportunities for trading. You can learn more about options, volatility, and how to analyze both via theOpenBB Platform:

Harnessing factor data using pandas_datareader

Diversification is great until the entire market declines in value. That’s because the overall market influences all assets. Factors can offset some of these risks by targeting drivers of return not influenced by the market. Common factors are size (large-cap versus small-cap) and style (value versus growth). If you think small-cap stocks will outperform large-cap stocks, then you might want exposure to small-cap stocks. If you think value stocks will outperform growth stocks, then you might want exposure to value stocks. In either case, you want to measure the risk contribution of the factor. Eugene Fama and Kenneth French built the Fama-French three-factor model in 1992. The three Fama-French factors are constructed using six value-weight portfolios formed on capitalizationand book-to-market.

The three factors areas follows:

  • Small Minus Big, which represents the differential between the average returns of three small-cap portfolios and threelarge-cap portfolios.
  • High Minus Low, which quantifies the difference in average returns between two value-oriented portfolios and twogrowth-oriented portfolios.
  • Rm-Rf, which denotes themarket’s excess return over therisk-free rate.

We’ll explore how to measure and isolate alpha inChapter 5,Build Alpha Factors for Stock Portfolios. This recipe will guide you through the process of usingpandas_datareader to fetch historic factor data for use inyour analysis.

Getting ready…

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

How to do it…

Using thepandas_datareader library, we have access to dozens of investmentresearch factors:

  1. Importpandas_datareader:
    import pandas_datareader as pdr
  2. Download the monthly factor data starting inJanuary 2000:
    factors = pdr.get_data_famafrench("F-F_Research_Data_Factors")
  3. Get a description of the researchdata factors:
    print(factors[“DESCR”])

    The result is an explanation of the data included inthe DataFrame:

Figure 1.12: Preview of the description that is downloaded with factor data

Figure 1.12: Preview of the description that is downloaded with factor data

  1. Inspect the monthlyfactor data:
    print(factors[0].head())

    By running the preceding code, we get a DataFrame containing monthlyfactor data:

Figure 1.13: Preview of the monthly data downloaded from the Fama-French Data Library

Figure 1.13: Preview of the monthly data downloaded from the Fama-French Data Library

  1. Inspect the annualfactor data:
    print(factors[1].head())

    By running the preceding code, we get a DataFrame containing annualfactor data:

Figure 1.14: Preview of the annual data downloaded from the Fama-French Data Library

Figure 1.14: Preview of the annual data downloaded from the Fama-French Data Library

How it works…

Under the hood,pandas_datareader fetches data from the Fama-French Data Library by downloading a compressed CSV file, uncompressing it, and creating apandas DataFrame.

There are 297 different datasets with different factor data available from the Fama-French Data Library. Here are some popular versions of the Fama-French 3-factor model fordifferent regions:

  • Developed_3_Factors
  • Developed_ex_US_3_Factors
  • Europe_3_Factors
  • Japan_3_Factors
  • Asia_Pacific_ex_Japan_3_Factors

You can use these in theget_data_famafrench method, justlikeF-F_Research_Data_Factors.

Some datasets return a dictionary with more than one DataFrame representing data for different time frames, portfolio weighting methodologies, and aggregate statistics. Data for these portfolios can be accessed using numerical keys. For example, the5_Industry_Portfolios dataset returns eight DataFrames in the dictionary. The first can be accessed using the0 key, the second using the1 key, and so on. Each dictionary includes a descriptionof the dataset, which can be accessed using theDESCR key.

There’s more…

pandas_datareader can be used to access data from many remote online sources. These include Tiingo, IEX, Alpha Vantage, FRED, Eurostat, and many more. Review the full list of data sources on the documentationpage:https://pandas-datareader.readthedocs.io/en/latest/remote_data.html.

See also

For more details on the factors available in the investment factor research library, take a look at the following resources. For another example of using the Fama-French 3-factor model, see the resources on the PyQuantNews website:

Left arrow icon

Page1 of 6

Right arrow icon
Download code iconDownload Code

Key benefits

  • Follow practical Python recipes to acquire, visualize, and store market data for market research
  • Design, backtest, and evaluate the performance of trading strategies using professional techniques
  • Deploy trading strategies built in Python to a live trading environment with API connectivity
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

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.

Who is this book for?

Python for Algorithmic Trading Cookbook equips traders, investors, and Python developers with code to design, backtest, and deploy algorithmic trading strategies. You should have experience investing in the stock market, knowledge of Python data structures, and a basic understanding of using Python libraries like pandas. This book is also ideal for individuals with Python experience who are already active in the market or are aspiring to be.

What you will learn

  • Acquire and process freely available market data with the OpenBB Platform
  • Build a research environment and populate it with financial market data
  • Use machine learning to identify alpha factors and engineer them into signals
  • Use VectorBT to find strategy parameters using walk-forward optimization
  • Build production-ready backtests with Zipline Reloaded and evaluate factor performance
  • Set up the code framework to connect and send an order to Interactive Brokers

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date :Aug 16, 2024
Length:404 pages
Edition :1st
Language :English
ISBN-13 :9781835087763
Category :
Languages :
Concepts :

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Product Details

Publication date :Aug 16, 2024
Length:404 pages
Edition :1st
Language :English
ISBN-13 :9781835087763
Category :
Languages :
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99billed monthly
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconSimple pricing, no contract
$199.99billed annually
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick iconExclusive print discounts
$279.99billed in 18 months
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick iconExclusive print discounts

Frequently bought together


Python for Algorithmic Trading Cookbook
Python for Algorithmic Trading Cookbook
Read more
Aug 2024404 pages
Full star icon4.2 (20)
eBook
eBook
Mex$885.99Mex$984.99
Mex$1230.99
Python Feature Engineering Cookbook
Python Feature Engineering Cookbook
Read more
Aug 2024396 pages
eBook
eBook
Mex$664.99Mex$738.99
Mex$922.99
Modern Time Series Forecasting with Python
Modern Time Series Forecasting with Python
Read more
Nov 2022552 pages
Full star icon4.2 (30)
eBook
eBook
Mex$782.98Mex$869.99
Mex$1086.99
Stars icon
TotalMex$3,240.97
Python for Algorithmic Trading Cookbook
Mex$1230.99
Python Feature Engineering Cookbook
Mex$922.99
Modern Time Series Forecasting with Python
Mex$1086.99
TotalMex$3,240.97Stars icon

Table of Contents

15 Chapters
Chapter 1: Acquire Free Financial Market Data with Cutting-Edge Python LibrariesChevron down iconChevron up icon
Chapter 1: Acquire Free Financial Market Data with Cutting-Edge Python Libraries
Technical requirements
Working with stock market data with the OpenBB Platform
Fetching historic futures data with the OpenBB Platform
Navigating options market data with the OpenBB Platform
Harnessing factor data using pandas_datareader
Chapter 2: Analyze and Transform Financial Market Data with pandasChevron down iconChevron up icon
Chapter 2: Analyze and Transform Financial Market Data with pandas
Diving into pandas index types
Building pandas Series and DataFrames
Manipulating and transforming DataFrames
Examining and selecting data from DataFrames
Calculating asset returns using pandas
Measuring the volatility of a return series
Generating a cumulative return series
Resampling data for different time frames
Addressing missing data issues
Applying custom functions to analyze time series data
Chapter 3: Visualize Financial Market Data with Matplotlib, Seaborn, and Plotly DashChevron down iconChevron up icon
Chapter 3: Visualize Financial Market Data with Matplotlib, Seaborn, and Plotly Dash
Quickly visualizing data using pandas
Animating the evolution of the yield curve with Matplotlib
Plotting options implied volatility surfaces with Matplotlib
Visualizing statistical relationships with Seaborn
Creating an interactive PCA analytics dashboard with Plotly Dash
Chapter 4: Store Financial Market Data on Your ComputerChevron down iconChevron up icon
Chapter 4: Store Financial Market Data on Your Computer
Storing data on disk in CSV format
Storing data on disk with SQLite
Storing data in a PostgreSQL database server
Storing data in ultra-fast HDF5 format
Chapter 5: Build Alpha Factors for Stock PortfoliosChevron down iconChevron up icon
Chapter 5: Build Alpha Factors for Stock Portfolios
Identifying latent return drivers using principal component analysis
Finding and hedging portfolio beta using linear regression
Analyzing portfolio sensitivities to the Fama-French factors
Assessing market inefficiency based on volatility
Preparing a factor ranking model using Zipline Pipelines
Chapter 6: Vector-Based Backtesting with VectorBTChevron down iconChevron up icon
Chapter 6: Vector-Based Backtesting with VectorBT
Building technical strategies with VectorBT
Conducting walk-forward optimization with VectorBT
Optimizing the SuperTrend strategy with VectorBT Pro
Chapter 7: Event-Based Backtesting Factor Portfolios with Zipline ReloadedChevron down iconChevron up icon
Chapter 7: Event-Based Backtesting Factor Portfolios with Zipline Reloaded
Technical Requirements
Backtesting a momentum factor strategy with Zipline Reloaded
Exploring a mean reversion strategy with Zipline Reloaded
Chapter 8: Evaluate Factor Risk and Performance with Alphalens ReloadedChevron down iconChevron up icon
Chapter 8: Evaluate Factor Risk and Performance with Alphalens Reloaded
Preparing backtest results
Evaluating the information coefficient
Examining factor return performance
Evaluating factor turnover
Chapter 9: Assess Backtest Risk and Performance Metrics with PyfolioChevron down iconChevron up icon
Chapter 9: Assess Backtest Risk and Performance Metrics with Pyfolio
Preparing Zipline backtest results for Pyfolio Reloaded
Generating strategy performance and return analytics
Building a drawdown and rolling risk analysis
Analyzing strategy holdings, leverage, exposure, and sector allocations
Breaking Down Strategy Performance to Trade Level
Chapter 10: Set Up the Interactive Brokers Python APIChevron down iconChevron up icon
Chapter 10: Set Up the Interactive Brokers Python API
Building an algorithmic trading app
Creating a Contract object with the IB API
Creating an Order object with the IB API
Fetching historical market data
Getting a market data snapshot
Streaming live market data
Storing live tick data in a local SQL database
Chapter 11: Manage Orders, Positions, and Portfolios with the IB APIChevron down iconChevron up icon
Chapter 11: Manage Orders, Positions, and Portfolios with the IB API
Executing orders with the IB API
Managing orders once they’re placed
Getting details about your portfolio
Inspecting positions and position details
Computing portfolio profit and loss
Chapter 12: Deploy Strategies to a Live EnvironmentChevron down iconChevron up icon
Chapter 12: Deploy Strategies to a Live Environment
Calculating real-time key performance and risk indicators
Sending orders based on portfolio targets
Deploying a monthly factor portfolio strategy
Deploying an options combo strategy
Deploying an intraday multi-asset mean reversion strategy
Chapter 13: Advanced Recipes for Market Data and Strategy ManagementChevron down iconChevron up icon
Chapter 13: Advanced Recipes for Market Data and Strategy Management
Streaming real-time options data with ThetaData
Using the ArcticDB DataFrame database for tick storage
Triggering real-time risk limit alerts
Storing trade execution details in a SQL database
IndexChevron down iconChevron up icon
Index
Why subscribe?
Other Books You May EnjoyChevron down iconChevron up icon
Other Books You May Enjoy
Packt is searching for authors like you
Share Your Thoughts
Download a free PDF copy of this book

Recommendations for you

Left arrow icon
LLM Engineer's Handbook
LLM Engineer's Handbook
Read more
Oct 2024522 pages
Full star icon4.9 (28)
eBook
eBook
Mex$984.99
Mex$1230.99
Getting Started with Tableau 2018.x
Getting Started with Tableau 2018.x
Read more
Sep 2018396 pages
Full star icon4 (3)
eBook
eBook
Mex$811.99Mex$902.99
Mex$1128.99
Python for Algorithmic Trading Cookbook
Python for Algorithmic Trading Cookbook
Read more
Aug 2024404 pages
Full star icon4.2 (20)
eBook
eBook
Mex$885.99Mex$984.99
Mex$1230.99
RAG-Driven Generative AI
RAG-Driven Generative AI
Read more
Sep 2024338 pages
Full star icon4.3 (18)
eBook
eBook
Mex$648.99Mex$721.99
Mex$902.99
Machine Learning with PyTorch and Scikit-Learn
Machine Learning with PyTorch and Scikit-Learn
Read more
Feb 2022774 pages
Full star icon4.4 (96)
eBook
eBook
Mex$811.99Mex$902.99
Mex$1128.99
Mex$1640.99
Building LLM Powered  Applications
Building LLM Powered Applications
Read more
May 2024342 pages
Full star icon4.2 (22)
eBook
eBook
Mex$737.99Mex$820.99
Mex$1025.99
Python Machine Learning By Example
Python Machine Learning By Example
Read more
Jul 2024518 pages
Full star icon4.9 (9)
eBook
eBook
Mex$678.99Mex$754.99
Mex$943.99
AI Product Manager's Handbook
AI Product Manager's Handbook
Read more
Nov 2024484 pages
eBook
eBook
Mex$664.99Mex$738.99
Mex$922.99
Right arrow icon

Customer reviews

Top Reviews
Rating distribution
Full star iconFull star iconFull star iconFull star iconHalf star icon4.2
(20 Ratings)
5 star70%
4 star10%
3 star5%
2 star0%
1 star15%
Filter icon Filter
Top Reviews

Filter reviews by




LucasAug 17, 2024
Full star iconFull star iconFull star iconFull star iconFull star icon5
Subscriber reviewPackt
kasidit asavakittikawinSep 09, 2024
Full star iconFull star iconFull star iconFull star iconFull star icon5
"Python for Algorithmic Trading Cookbook" stands out as a practical and accessible guide for those seeking to enhance their algorithmic trading knowledge. The author's hands-on experience and understanding of the needs of beginners shine through in this well-structured book.Practical Approach: The book is filled with actionable Python recipes for acquiring, visualizing, storing, and analyzing market data. It walks readers through the entire process of designing, backtesting, and deploying trading strategies, making the complex world of algo trading manageable.Updated Data Sources: The book provides free and updated data sources, a valuable resource for those looking to apply the concepts in a real-world setting.
Amazon Verified reviewAmazon
Didier LopesSep 15, 2024
Full star iconFull star iconFull star iconFull star iconFull star icon5
If you are starting using Python to do algorithmic trading - you should get this book. I recommend the paperback version personally, particularly to have it by your desk in a way that you can access it easily.The book is packed with clear, hands-on examples that make complex topics feel easy - Jason is one of the best people I know at doing this. That's why he has hundreds of thousands of followers and has had over 1000 students attending his cohorts.I also love how practical the book is. All theory has real-world examples that myself, as the reader, can use to better understand the topic at hand.It goes from basic technical analysis to more advanced strategies like machine learning, so there's a lot of room to grow your skills.If you're like me and appreciate learning by doing, this book is perfect. The code examples are super clear, and you can quickly get a strategy up and running or modify it to fit your own ideas.PS: I also particularly love that the book features OpenBB!
Amazon Verified reviewAmazon
Roger A. StrimpelAug 29, 2024
Full star iconFull star iconFull star iconFull star iconFull star icon5
Excellent book!!
Amazon Verified reviewAmazon
Amazon CustomerAug 24, 2024
Full star iconFull star iconFull star iconFull star iconFull star icon5
I thought this book was very insightful and excellent source for information. The charts were understandable!
Amazon Verified reviewAmazon
  • Arrow left icon Previous
  • 1
  • 2
  • 3
  • 4
  • Arrow right icon Next

About the author

Profile icon Jason Strimpel
Jason Strimpel
LinkedIn iconGithub icon
Jason Strimpel is the founder of PyQuant News and co-founder of Trade Blotter, with a career spanning over 20 years in trading, risk management, and data science. He previously traded for a Chicago-based hedge fund, served as a risk manager at JPMorgan, and managed production risk technology for an energy derivatives trading firm in London. In Singapore, Jason served as the APAC CIO for an agricultural trading firm and built the data science team for a global metals trading firm. He holds degrees in finance and economics and a Master's in quantitative finance from the Illinois Institute of Technology. His career has taken him across America, Europe, and Asia. Jason shares his expertise through the PyQuant Newsletter, social media, and teaches the course "Getting Started With Python for Quant Finance."
Read more
See other products by Jason Strimpel
Getfree access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook?Chevron down iconChevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website?Chevron down iconChevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook?Chevron down iconChevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support?Chevron down iconChevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks?Chevron down iconChevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook?Chevron down iconChevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.


[8]ページ先頭

©2009-2025 Movatter.jp