Book Image

Python for Finance Cookbook

By : Eryk Lewinson
Book Image

Python for Finance Cookbook

By: Eryk Lewinson

Overview of this book

Python is one of the most popular programming languages used in the financial industry, with a huge set of accompanying libraries. In this book, you'll cover different ways of downloading financial data and preparing it for modeling. You'll calculate popular indicators used in technical analysis, such as Bollinger Bands, MACD, RSI, and backtest automatic trading strategies. Next, you'll cover time series analysis and models, such as exponential smoothing, ARIMA, and GARCH (including multivariate specifications), before exploring the popular CAPM and the Fama-French three-factor model. You'll then discover how to optimize asset allocation and use Monte Carlo simulations for tasks such as calculating the price of American options and estimating the Value at Risk (VaR). In later chapters, you'll work through an entire data science project in the financial domain. You'll also learn how to solve the credit card fraud and default problems using advanced classifiers such as random forest, XGBoost, LightGBM, and stacked models. You'll then be able to tune the hyperparameters of the models and handle class imbalance. Finally, you'll focus on learning how to use deep learning (PyTorch) for approaching financial tasks. By the end of this book, you’ll have learned how to effectively analyze financial data using a recipe-based approach.
Table of Contents (12 chapters)

Creating a candlestick chart

A candlestick chart is a type of financial graph, used to describe a given security's price movements. A single candlestick (typically corresponding to one day, but a higher frequency is possible) combines the open, high, low, and close prices (OHLC). The elements of a bullish candlestick (where the close price in a given time period is higher than the open price) are presented in the following image (for a bearish one, we should swap the positions of the open and close prices):

In comparison to the plots introduced in the previous chapter, candlestick charts convey much more information than a simple line plot of the adjusted close price. That is why they are often used in real trading platforms, and traders use them for identifying patterns and making trading decisions.

In this recipe, we also add moving average lines (which are one of the most basic technical indicators), as well as bar charts representing volume.

Getting ready

In this recipe, we download Twitter's (adjusted) stock prices for the year 2018. We use Yahoo Finance to download the data, as described in the Getting data from Yahoo Finance recipe, found in Chapter 1, Financial Data and Preprocessing. Follow these steps:

  1. Import the libraries:
import pandas as pd 
import yfinance as yf
  1. Download the adjusted prices:
df_twtr = yf.download('TWTR', 
start='2018-01-01',
end='2018-12-31',
progress=False,
auto_adjust=True)

For creating the plot, we use the plotly and cufflinks libraries. For more details, please refer to the Visualizing time series data recipe, found in Chapter 1, Financial Data and Preprocessing.

How to do it...

Execute the following steps to create an interactive candlestick chart.

  1. Import the libraries:
import cufflinks as cf
from plotly.offline import iplot, init_notebook_mode

init_notebook_mode()
  1. Create the candlestick chart, using Twitter's stock prices:
qf = cf.QuantFig(df_twtr, title="Twitter's Stock Price", 
                 legend='top', name='TWTR')
  1. Add volume and moving averages to the figure:
qf.add_volume()
qf.add_sma(periods=20, column='Close', color='red')
qf.add_ema(periods=20, color='green')

  1. Display the plot:
qf.iplot()

We can observe the following plot (it is interactive in the notebook):

In the plot, we can see that the exponential moving average (EMA) adapts to the changes in prices much faster than the SMA. Some discontinuities in the chart are caused by the fact that we are using daily data, and there is no data for weekends/bank holidays.

How it works...

In Step 2, we created a QuantFig object by passing a DataFrame containing the input data, as well as some arguments for the title and legend's position. We could have created a simple candlestick chart by running the iplot method of QuantFig immediately afterward.

However, in Step 3, we also added two moving average lines by using the add_sma/add_ema methods. We decided to consider 20 periods (days, in this case). By default, the averages are calculated using the close column, however, we can change this by providing the column argument.

The difference between the two moving averages is that the exponential one puts more weight on recent prices. By doing so, it is more responsive to new information and reacts faster to any changes in the general trend.

See also