Python for Finance –初心者向けのアルゴリズム取引チュートリアル

テクノロジーは金融の資産になりました。金融機関は現在、この分野の金融面に専念するだけでなく、テクノロジー企業へと進化しています。

数学的アルゴリズムは革新とスピードをもたらします。彼らは私たちが市場で競争上の優位性を獲得するのを助けることができます。

金融取引の速度と頻度は、大量のデータとともに、すべての大手金融機関からテクノロジーに大きな注目を集めています。

アルゴリズムまたは定量的取引は、数学的および統計的分析に基づいて取引戦略を設計および開発するプロセスです。それは非常に洗練された金融分野です。

このチュートリアルは、Pythonを使用した量的取引の初心者向けガイドとして機能します。次のような場合は、この投稿が非常に役立ちます。

  1. ファンドや銀行でクオンツアナリスト(クオンツ)になることを目指す学生または誰か。
  2. 独自の量的取引事業を始めることを計画している人。

この投稿では、次のトピックについて説明します。

  • 株式と取引の基本
  • QuandlAPIからのデータの抽出
  • 株価データの探索的データ分析
  • 移動平均
  • Pythonで取引戦略を策定する
  • 戦略のパフォーマンスの視覚化

株価データの詳細とダイナミクスを深く掘り下げる前に、まず財務の基本を理解する必要があります。あなたが金融と取引の仕組みに精通している人なら、このセクションをスキップして、ここをクリックして次のセクションに進むことができます。

株式とは何ですか?株取引とは?

株式

株式とは、一定の金額で発行される企業の所有権の株式を表すものです。これは、会社の資産と業績に対するあなたの主張を確立する一種の金融証券です。

組織または会社は、より多くのプロジェクトを拡大して従事するために、より多くの資金/資本を調達するために株式を発行します。その後、これらの株式は公開され、売買されます。

株取引と取引戦略

既存および以前に発行された株式を売買するプロセスは、株式取引と呼ばれます。株式の売買には価格があり、株式市場の需要や供給によって変動し続けます。

会社の業績や行動によっては株価が上下することもありますが、株価の動きは会社の業績だけにとどまりません。

トレーダーは、企業内の所有権と引き換えにお金を支払い、収益性の高い取引を行い、より高い価格で株式を販売することを望んでいます。

トレーダーが従うもう1つの重要なテクニックは、ショートセルです。これには、株式を借りてすぐに売却し、後で低価格で購入し、貸し手に返還し、マージンを確保することが含まれます。

したがって、ほとんどのトレーダーは、取引の計画とモデルに従います。これは取引戦略として知られています。

ヘッジファンドや投資銀行の定量的トレーダーは、これらの取引戦略とフレームワークを設計および開発して、それらをテストします。それには、プログラミングに関する深い専門知識と、独自の戦略を構築するために必要な言語の理解が必要です。

Pythonは、C ++、Java、R、MATLABなどの中で最も人気のあるプログラミング言語の1つです。構文が簡単で、コミュニティが巨大で、サードパーティがサポートしているため、すべてのドメイン、特にデータサイエンスで広く採用されています。

このチュートリアルを最大限に活用するには、Pythonと統計に精通している必要があります。Pythonをブラッシュアップして、統計の基礎を確認してください。

QuandlAPIからのデータの抽出

株価データを抽出するために、QuandlAPIを使用します。その前に、作業環境を整えましょう。方法は次のとおりです。

  1. ターミナルで、プロジェクトの新しいディレクトリを作成します(好きな名前を付けます)。
mkdir 
  1. マシンにPython3とvirtualenvがインストールされていることを確認してください。
  2. を使用して新しいPython3 virtualenvを作成し、を使用virtualenv してアクティブ化しsource /bin/activateます。
  3. ここで、pipを使用してjupyter-notebookをインストールpip install jupyter-notebookし、ターミナルに入力します。
  4. 同様に、インストールpandasquandlおよびnumpyパッケージを。
  5. jupyter-notebookターミナルから実行します。

これで、ノートブックは以下のスクリーンショットのようにローカルホストで実行されているはずです。

New右側のドロップダウンをクリックすると、最初のノートブックを作成できます。Quandlでアカウントを作成したことを確認してください。ここに記載されている手順に従って、APIキーを作成します。

すべての設定が完了したら、次の項目に飛び込みましょう。

# importing required packages
import pandas as pd import quandl as q

多くのデータ操作とプロットを行うため、このチュートリアルではPandasが最も厳密に使用されるパッケージになります。

パッケージがインポートされた後、Quandlパッケージを使用してQuandlAPIにリクエストを送信します。

# set the API key q.ApiConfig.api_key = "”
#send a get request to query Microsoft's end of day stock prices from 1st #Jan, 2010 to 1st Jan, 2019 msft_data = q.get("EOD/MSFT", start_date="2010-01-01", end_date="2019-01-01")
# look at the first 5 rows of the dataframe msft_data.head()

Here we have Microsoft’s EOD stock pricing data for the last 9 years. All you had to do was call the get method from the Quandl package and supply the stock symbol, MSFT, and the timeframe for the data you need.

This was really simple, right? Let’s move ahead to understand and explore this data further.

Exploratory Data Analysis on Stock Pricing Data

With the data in our hands, the first thing we should do is understand what it represents and what kind of information it encapsulates.

Printing the DataFrame’s info, we can see all that it contains:

As seen in the screenshot above, the DataFrame contains DatetimeIndex, which means we’re dealing with time-series data.

An index can be thought of as a data structure that helps us modify or reference the data. Time-series data is a sequence of snapshots of prices taken at consecutive, equally spaced intervals of time.

In trading, EOD stock pricing data captures the movement of certain parameters about a stock, such as the stock price, over a specified period of time with data points recorded at regular intervals.

Important Terminology

Looking at other columns, let’s try to understand what each column represents:

  • Open/Close — Captures the opening/closing price of the stock
  • Adj_Open/Adj_Close — An adjusted opening/closing price is a stock’s price on any given day of trading that has been revised to include any dividend distributions, stock splits, and other corporate actions that occurred at any time before the next day’s open.
  • Volume — It records the number of shares that are being traded on any given day of trading.
  • High/Low — It tracks the highest and the lowest price of the stock during a particular day of trading.

These are the important columns that we will focus on at this point in time.

We can learn about the summary statistics of the data, which shows us the number of rows, mean, max, standard deviations, and so on. Try running the following line of code in the Ipython cell:

msft_data.describe()

resample()

Pandas’ resample() method is used to facilitate control and flexibility on the frequency conversion of the time series data. We can specify the time intervals to resample the data to monthly, quarterly, or yearly, and perform the required operation over it.

msft_data.resample('M').mean()

This is an interesting way to analyze stock performance in different timeframes.

Calculating returns

金銭的見返りは、単に投資で稼いだり失ったりしたお金です。リターンは、名目上、時間の経過に伴う投資額の変化として表すことができます。これは、投資に対する利益の比率から導き出されたパーセンテージとして計算できます。

この目的のために、pct_change()を自由に使用できます。収益を計算する方法は次のとおりです。

# Import numpy package import numpy as np
# assign `Adj Close` to `daily_close` daily_close = msft_data[['Adj_Close']]
# returns as fractional change daily_return = daily_close.pct_change()
# replacing NA values with 0 daily_return.fillna(0, inplace=True)
print(daily_return)

これにより、株式が毎日生成しているリターンが印刷されます。数値に100を掛けると、変化率が得られます。

pct_change()で使用される式は次のとおりです。

Return = {(tでの価格)—(t-1での価格)} / {t-1での価格}

さて、毎月の収益を計算するためにあなたがする必要があるのは:

mdata = msft_data.resample('M').apply(lambda x: x[-1]) monthly_return = mdata.pct_change()

データを月(営業日)にリサンプリングした後、apply()関数を使用してその月の取引の最終日を取得できます。

apply() takes in a function and applies it to each and every row of the Pandas series. The lambda function is an anonymous function in Python which can be defined without a name, and only takes expressions in the following format:

Lambda: expression

For example, lambda x: x * 2 is a lambda function. Here, x is the argument and x * 2 is the expression that gets evaluated and returned.

Moving Averages in Trading

The concept of moving averages is going to build the base for our momentum-based trading strategy.

In finance, analysts often have to evaluate statistical metrics continually over a sliding window of time, which is called moving window calculations.

Let’s see how we can calculate the rolling mean over a window of 50 days, and slide the window by 1 day.

rolling()

This is the magical function which does the tricks for us:

# assigning adjusted closing prices to adj_pricesadj_price = msft_data['Adj_Close']
# calculate the moving average mav = adj_price.rolling(window=50).mean()
# print the resultprint(mav[-10:])

You’ll see the rolling mean over a window of 50 days (approx. 2 months). Moving averages help smooth out any fluctuations or spikes in the data, and give you a smoother curve for the performance of the company.

We can plot and see the difference:

# import the matplotlib package to see the plot import matplotlib.pyplot as plt adj_price.plot()

You can now plot the rolling mean():

mav.plot()

And you can see the difference for yourself, how the spikes in the data are consumed to give a general sentiment around the performance of the stock.

Formulating a Trading Strategy

Here comes the final and most interesting part: designing and making the trading strategy. This will be a step-by-step guide to developing a momentum-based Simple Moving Average Crossover (SMAC) strategy.

Momentum-based strategies are based on a technical indicator that capitalizes on the continuance of the market trend. We purchase securities that show an upwards trend and short-sell securities which show a downward trend.

The SMAC strategy is a well-known schematic momentum strategy. It is a long-only strategy. Momentum, here, is the total return of stock including the dividends over the last n months. This period of n months is called the lookback period.

There are 3 main types of lookback periods: short term, intermediate-term, and long term. We need to define 2 different lookback periods of a particular time series.

A buy signal is generated when the shorter lookback rolling mean (or moving average) overshoots the longer lookback moving average. A sell signal occurs when the shorter lookback moving average dips below the longer moving average.

Now, let’s see how the code for this strategy will look:

# step1: initialize the short and long lookback periods short_lb = 50long_lb = 120
# step2: initialize a new DataFrame called signal_df with a signal column signal_df = pd.DataFrame(index=msft_data.index)signal_df['signal'] = 0.0
# step3: create a short simple moving average over the short lookback period signal_df['short_mav'] = msft_data['Adj_Close'].rolling(window=short_lb, min_periods=1, center=False).mean()
# step4: create long simple moving average over the long lookback period signal_df['long_mav'] = msft_data['Adj_Close'].rolling(window=long_lb, min_periods=1, center=False).mean()
# step5: generate the signals based on the conditional statement signal_df['signal'][short_lb:] = np.where(signal_df['short_mav'][short_lb:] > signal_df['long_mav'][short_lb:], 1.0, 0.0) 
# step6: create the trading orders based on the positions column signal_df['positions'] = signal_df['signal'].diff()signal_df[signal_df['positions'] == -1.0]

Let’s see what’s happening here. We have created 2 lookback periods. The short lookback period short_lb is 50 days, and the longer lookback period for the long moving average is defined as a long_lb of 120 days.

We have created a new DataFrame which is designed to capture the signals. These signals are being generated whenever the short moving average crosses the long moving average using the np.where. It assigns 1.0 for true and 0.0 if the condition comes out to be false.

The positions columns in the DataFrame tells us if there is a buy signal or a sell signal, or to stay put. We're basically calculating the difference in the signals column from the previous row using diff.

And there we have our strategy implemented in just 6 steps using Pandas. Easy, wasn't it?

Now, let’s try to visualize this using Matplotlib. All we need to do is initialize a plot figure, add the adjusted closing prices, short, and long moving averages to the plot, and then plot the buy and sell signals using the positions column in the signal_df above:

# initialize the plot using plt fig = plt.figure()
# Add a subplot and label for y-axis plt1 = fig.add_subplot(111, ylabel="Price in $")
msft_data['Adj_Close'].plot(ax=plt1,, lw=2.)
# plot the short and long lookback moving averages signal_df[['short_mav', 'long_mav']].plot(ax=plt1, lw=2., figsize=(12,8))
# plotting the sell signals plt1.plot(signal_df.loc[signal_df.positions == -1.0].index, signal_df.short_mav[signal_df.positions == -1.0],'v', markersize=10,)
# plotting the buy signals plt1.plot(signal_df.loc[signal_df.positions == 1.0].index, signal_df.short_mav[signal_df.positions == 1.0], '^', markersize=10,) # Show the plotplt.show()

Running the above cell in the Jupyter notebook would yield a plot like the one below:

Now, you can clearly see that whenever the blue line (short moving average) goes up and beyond the orange line (long moving average), there is a pink upward marker indicating a buy signal.

A sell signal is denoted by a black downward marker where there’s a fall of the short_mav below long_mav.

Visualize the Performance of the Strategy on Quantopian

Quantopian is a Zipline-powered platform that has manifold use cases. You can write your own algorithms, access free data, backtest your strategy, contribute to the community, and collaborate with Quantopian if you need capital.

We have written an algorithm to backtest our SMA strategy, and here are the results:

Here is an explanation of the above metrics:

  • Total return: The total percentage return of the portfolio from the start to the end of the backtest.
  • Specific return: The difference between the portfolio’s total returns and common returns.
  • Common return: Returns that are attributable to common risk factors. There are 11 sector and 5 style risk factors that make up these returns. The Sector Exposure and Style Exposure charts in the Risk section provide more detail on these factors.
  • Sharpe: The 6-month rolling Sharpe ratio. It is a measure of risk-adjusted investment. It is calculated by dividing the portfolio’s excess returns over the risk-free rate by the portfolio’s standard deviation.
  • Max Drawdown: The largest drop of all the peak-to-trough movement in the portfolio’s history.
  • Volatility: Standard deviation of the portfolio’s returns.

Pat yourself on the back as you have successfully implemented your quantitative trading strategy!

Where to go From Here?

Now that your algorithm is ready, you’ll need to backtest the results and assess the metrics mapping the risk involved in the strategy and the stock. Again, you can use BlueShift and Quantopian to learn more about backtesting and trading strategies.

Further Resources

Quantra is a brainchild of QuantInsti. With a range of free and paid courses by experts in the field, Quantra offers a thorough guide on a bunch of basic and advanced trading strategies.

  • Data Science Course — They have rolled out an introductory course on Data Science that helps you build a strong foundation for projects in Data Science.
  • Trading Courses for Beginners — From momentum trading to machine and deep learning-based trading strategies, researchers in the trading world like Dr. Ernest P. Chan are the authors of these niche courses.

Free Resources

To learn more about trading algorithms, check out these blogs:

  • Quantstart — they cover a wide range of backtesting algorithms, beginner guides, and more.
  • Investopedia — everything you want to know about investment and finance.
  • Quantivity — detailed mathematical explanations of algorithms and their pros and cons.

Warren Buffet says he reads about 500 pages a day, which should tell you that reading is essential in order to succeed in the field of finance.

Embark upon this journey of trading and you can lead a life full of excitement, passion, and mathematics.

Data Science with Harshit

With this channel, I am planning to roll out a couple of series covering the entire data science space. Here is why you should be subscribing to the channel:

  • These series would cover all the required/demanded quality tutorials on each of the topics and subtopics like Python fundamentals for Data Science.
  • Explained Mathematics and derivations of why we do what we do in ML and Deep Learning.
  • Podcasts with Data Scientists and Engineers at Google, Microsoft, Amazon, etc, and CEOs of big data-driven companies.
  • Projects and instructions to implement the topics learned so far. Learn about new certifications, Bootcamp, and resources to crack those certifications like this TensorFlow Developer Certificate Exam by Google.

Further on, you can connect with me on Twitter or LinkedIn.