Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Python for Finance Cookbook – Second Edition
Python for Finance Cookbook – Second Edition

Python for Finance Cookbook – Second Edition: Over 80 powerful recipes for effective financial data analysis , Second Edition

eBook
€8.99 €29.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Python for Finance Cookbook – Second Edition

Getting data from CoinGecko

The last data source we cover is dedicated purely to cryptocurrencies. CoinGecko is a popular data vendor and crypto tracking website, on which you can find real-time exchange rates, historical data, information about exchanges, upcoming events, trading volumes, and much more.

We can list a few of the advantages of CoinGecko:

  • completely free, no need to register for an API key
  • aside from prices, they also provide updates and news about crypto
  • it covers many coins, not only the most popular ones

In this recipe, we download Bitcoin's OHLC from the last 14 days.

How to do it…

Execute the following steps to download data from CoinGecko.

  1. Import the libraries:
from pycoingecko import CoinGeckoAPI
from datetime import datetime
  1. Instantiate the CoinGecko API:
cg = CoinGeckoAPI()
  1. Get Bitcoin's OHLC prices from the last 14 days:
ohlc = cg.get_coin_ohlc_by_id(id="bitcoin", vs_currency="usd", days="14")
ohlc_df...

Summary

In this chapter, we have covered a few of the most popular sources of financial data. However, this is just the tip of the iceberg. Below, you can find a list of other interesting data sources that might suit your needs even better.

Additional data sources:

  • IEX Cloud (https://iexcloud.io/) - a platform providing a vast trove of different financial data. A notable feature that is unique to the platform is a daily and minutely sentiment score based on the activity on Stocktwits - an online community for investors and traders. However, that API is only available in the paid plan. You can access the IEX Cloud data using pyex, the official Python library.
  • Tiingo (https://www.tiingo.com/) and the tiingo library.
  • CryptoCompare (https://www.cryptocompare.com/) - the platform offers a wide range of crypto-related data via their API. What stands out about this data vendor is that they provide order book data.
  • twelvedata (https://twelvedata.com/)
  • polygon.io (https://polygon.io/) - a trusted...

Adjusting the returns for inflation

When doing different kinds of analyses, especially long-term ones, we might want to consider inflation. Inflation is the general rise of the price level of an economy over time. Or to phrase it differently, the reduction of the purchasing power of money. That is why we might want to decouple the inflation from the increase of the stock prices caused by, for example, the companies’ growth or development.

We can naturally adjust the prices of stocks directly, but in this recipe, we will focus on adjusting the returns and calculating the real returns. We can do so using the following formula:

where Rrt is the real return, Rt is the time t simple return, and stands for the inflation rate.

For this example, we use Apple’s stock prices from the years 2010 to 2020 (downloaded as in the previous recipe).

How to do it…

Execute the following steps to adjust the returns for inflation:

  1. Import libraries...

Changing the frequency of time series data

When working with time series, and especially financial ones, we often need to change the frequency (periodicity) of the data. For example, we receive daily OHLC prices, but our algorithm works with weekly data. Or we have daily alternative data, and we want to match it with our live feed of intraday data.

The general rule of thumb for changing frequency can be broken down into the following:

  • Multiply/divide the log returns by the number of time periods.
  • Multiply/divide the volatility by the square root of the number of time periods.

For any process with independent increments (for example, the geometric Brownian motion), the variance of the logarithmic returns is proportional to time. For example, the variance of rt3 - rt1 is going to be the sum of the following two variances: rt2−rt1 and rt3−rt2, assuming t1t2t3. In such a case, when we also assume that the parameters of...

Different ways of imputing missing data

While working with any time series, it can happen that some data is missing, due to many possible reasons (someone forgot to input the data, a random issue with the database, and so on). One of the available solutions would be to discard observations with missing values. However, imagine a scenario in which we are analyzing multiple time series at once, and only one of the series is missing a value due to some random mistake. Do we still want to remove all the other potentially valuable pieces of information because of this single missing value? Probably not. And there are many other potential scenarios in which we would rather treat the missing values somehow, rather than discarding those observations.

Two of the simplest approaches to imputing missing time series data are:

  • Backward filling—fill the missing value with the next known value
  • Forward filling—fill the missing value with the previous known value...

Converting currencies

Another quite common preprocessing step you might encounter while working on financial tasks is converting currencies. Imagine you have a portfolio of multiple assets, priced in different currencies and you would like to arrive at a total portfolio’s worth. The simplest example might be American and European stocks.

In this recipe, we show how to easily convert stock prices from USD to EUR. However, the very same steps can be used to convert any pair of currencies.

How to do it…

Execute the following steps to convert stock prices from USD to EUR:

  1. Import the libraries:
    import pandas as pd
    import yfinance as yf
    from forex_python.converter import CurrencyRates
    
  2. Download Apple’s OHLC prices from January 2020:
    df = yf.download("AAPL",
                     start="2020-01-01",
                     end="2020-01-31",
                     progress=False)
    df = df.drop(columns=[&quot...

Different ways of aggregating trade data

Before diving into building a machine learning model or designing a trading strategy, we not only need reliable data, but we also need to aggregate it into a format that is convenient for further analysis and appropriate for the models we choose. The term bars refers to a data representation that contains basic information about the price movements of any financial asset. We have already seen one form of bars in Chapter 1, Acquiring Financial Data, in which we explored how to download financial data from a variety of sources.

There, we downloaded OHLCV data sampled by some time period, be it a month, day, or intraday frequencies. This is the most common way of aggregating financial time series data and is known as the time bars.

There are some drawbacks of sampling financial time series by time:

  • Time bars disguise the actual rate of activity in the market—they tend to oversample low activity periods (for example,...

Summary

In this chapter, we have learned how to preprocess financial time series data. We started by showing how to calculate returns and potentially adjust them for inflation. Then, we covered a few of the popular methods for imputing missing values. Lastly, we explained the different approaches to aggregating trade data and why choosing the correct one matters.

We should always pay significant attention to this step, as we not only want to enhance our model’s performance but also to ensure the validity of any analysis. In the next chapter, we will continue working with the preprocessed data and learn how to create time series visualization.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore unique recipes for financial data processing and analysis with Python
  • Apply classical and machine learning approaches to financial time series analysis
  • Calculate various technical analysis indicators and backtest trading strategies

Description

Python is one of the most popular programming languages in the financial industry, with a huge collection of accompanying libraries. In this new edition of the Python for Finance Cookbook, you will explore classical quantitative finance approaches to data modeling, such as GARCH, CAPM, factor models, as well as modern machine learning and deep learning solutions. You will use popular Python libraries that, in a few lines of code, provide the means to quickly process, analyze, and draw conclusions from financial data. In this new edition, more emphasis was put on exploratory data analysis to help you visualize and better understand financial data. While doing so, you will also learn how to use Streamlit to create elegant, interactive web applications to present the results of technical analyses. Using the recipes in this book, you will become proficient in financial data analysis, be it for personal or professional projects. You will also understand which potential issues to expect with such analyses and, more importantly, how to overcome them.

Who is this book for?

This book is intended for financial analysts, data analysts and scientists, and Python developers with a familiarity with financial concepts. You’ll learn how to correctly use advanced approaches for analysis, avoid potential pitfalls and common mistakes, and reach correct conclusions for a broad range of finance problems. Working knowledge of the Python programming language (particularly libraries such as pandas and NumPy) is necessary.

What you will learn

  • Preprocess, analyze, and visualize financial data
  • Explore time series modeling with statistical (exponential smoothing, ARIMA) and machine learning models
  • Uncover advanced time series forecasting algorithms such as Meta's Prophet
  • Use Monte Carlo simulations for derivatives valuation and risk assessment
  • Explore volatility modeling using univariate and multivariate GARCH models
  • Investigate various approaches to asset allocation
  • Learn how to approach ML-projects using an example of default prediction
  • Explore modern deep learning models such as Google's TabNet, Amazon's DeepAR and NeuralProphet

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 30, 2022
Length: 740 pages
Edition : 2nd
Language : English
ISBN-13 : 9781803238838
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 30, 2022
Length: 740 pages
Edition : 2nd
Language : English
ISBN-13 : 9781803238838
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 121.97
Machine Learning for Algorithmic Trading
€43.99
Python for Finance Cookbook – Second Edition
€37.99
Modern Time Series Forecasting with Python
€39.99
Total 121.97 Stars icon
Banner background image

Table of Contents

17 Chapters
Acquiring Financial Data Chevron down icon Chevron up icon
Data Preprocessing Chevron down icon Chevron up icon
Visualizing Financial Time Series Chevron down icon Chevron up icon
Exploring Financial Time Series Data Chevron down icon Chevron up icon
Technical Analysis and Building Interactive Dashboards Chevron down icon Chevron up icon
Time Series Analysis and Forecasting Chevron down icon Chevron up icon
Machine Learning-Based Approaches to Time Series Forecasting Chevron down icon Chevron up icon
Multi-Factor Models Chevron down icon Chevron up icon
Modeling Volatility with GARCH Class Models Chevron down icon Chevron up icon
Monte Carlo Simulations in Finance Chevron down icon Chevron up icon
Asset Allocation Chevron down icon Chevron up icon
Backtesting Trading Strategies Chevron down icon Chevron up icon
Applied Machine Learning: Identifying Credit Default Chevron down icon Chevron up icon
Advanced Concepts for Machine Learning Projects Chevron down icon Chevron up icon
Deep Learning in Finance Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.9
(37 Ratings)
5 star 86.5%
4 star 13.5%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




bin Sep 11, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is very comprehensive, with useful knowledge points. It is really a highly recommended book!
Subscriber review Packt
Rubens C. Machado Jun 07, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
David Zhang May 01, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Die 2. Version ist nochmal viel kompakter als die erste von vor 3 Jahren. Grundlegende als auch tiefgreifende Prozesse der Statistik und Programmierung werden gut erklärt dargestellt. Die fast 800 Seiten des Buches decken theoretisch mehr als nur einen ganzen Semester ab.
Amazon Verified review Amazon
Ram Seshadri Feb 08, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was recently given the Python for Finance cookbook to review by Packt based on my experience with Finance and ML. I have to say that this is one hell of a book!! It is one of the most comprehensive and sweeping write-ups of Python in Finance I have read. Just for starters: it’s 720 pages long.Second, it has over 15 chapters covering everything from downloading and processing Time series data to EDA to modeling and finally explaining and evaluating results.The book provides over 80 recipes for everything from ARIMA to Garch to ML to Monte Carlo. The subjects range from derivatives evaluation to asset management and Bitcoin forecasting.The book has tons and tons of code. Every page is filled with step by step instructions with code and charts and graphs. I can go and on. If there is only one book that you plan to buy for learning to apply Python to financial problems, this is probably the book to buy. Highly recommended!
Amazon Verified review Amazon
Asha Jan 19, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Having just started as a Junior Data Scientist this book was really helpful for time series analysis and forecasting. It's not for beginners you need to have some basic understanding of Python and data analysis to get the most out of this book. I don't work in the Finance industry but it was nice to learn more about financial data.
Amazon Verified review Amazon
Get free 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 icon Chevron 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 icon Chevron 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 icon Chevron 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 icon Chevron 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 icon Chevron 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 icon Chevron 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.