Welcome to subscribe to the Python Data Analysis Practical: Building a Quantitative Trading System for Stocks booklet. After you finish this booklet, be sure to use your knowledge to help us analyze stocks!

preface

Believe everybody heard quantitative trade this thing!

Quantitative trading is an emerging systematic financial investment method. It integrates the knowledge of multiple disciplines, uses advanced mathematical models to replace human subjective thinking to formulate trading strategies, and uses the powerful computing power of computers to backtest the profit and loss “probability” of trading strategies from huge historical data such as stocks, bonds and futures. Helps investors make accurate decisions by managing the “probability” of profit and loss.

So, what is the suitable way for ordinary shareholders to open quantitative trading?

This article uses a ground gas stock analysis scenario — Python with PivotTable and heat chart these two data analysis tools tracking industry plate hot switch to share with you, how ordinary shareholders to use quantitative trading!

Industry sector pivottables

Pivot tables are no stranger to the world. They are often used in EXCEL to analyze data statistically.

Pandas is a library that can replace Excel to perform statistical analysis of data. It provides a similar function in Pandas: Pivot_table ().

Before creating a PivotTable, we need to be clear about what we want to solve with the PivotTable. So, let’s first introduce the corresponding stock analysis scenario for this issue.

Usually, when we analyze stocks, we pay attention to the dynamic of the index and the dynamic of the sector. Especially under the premise of market expansion, the selection of plate is especially important.

For example, in my words, I will calculate some overall dynamics of the sector on each trading day, such as the rise and fall, total market value, turnover rate, the number of rising stocks, the number of falling stocks, and the leading stocks… The following is the plate situation on 2020-07-27:

Of course, the daily plate data is static, so we can’t identify the trend of the plate, so we have to link the daily plate data together for analysis. Here we first select the data of the week 2020-07-27 to 2020-07-31 from the plate data of the past month for analysis.

The first step is to load the week’s data from the CSV file into the program as a DataFrame object, as shown below:

df_bk_mon = pd.read_csv('table-bk-2020-07-27.csv', parse_dates=True, index_col=0, encoding='GB18030')
df_bk_tue = pd.read_csv('table-bk-2020-07-28.csv', parse_dates=True, index_col=0, encoding='GB18030')
df_bk_wed = pd.read_csv('table-bk-2020-07-29.csv', parse_dates=True, index_col=0, encoding='GB18030')
df_bk_thu = pd.read_csv('table-bk-2020-07-30.csv', parse_dates=True, index_col=0, encoding='GB18030')
df_bk_fri = pd.read_csv('table-bk-2020-07-31.csv', parse_dates=True, index_col=0, encoding='GB18030')
Copy the code

The second step is to combine the sector data for the week from Monday to Friday into one. Simply concatenate these DataFrame objects, which we use pd.concat() to do. The key parameter axis is 0 to concatenate multiple DataFrame objects together along the column direction. As follows:

df_bk_week.to_csv("table-bk-2020-07-27-31.csv", columns=df_bk_week.columns, index=True, encoding='GB18030')
Copy the code

With that done, let’s move on to how to use Pivot_Table () to complete PivotTable.

The following describes the pivot_table function interfaces:

pandas.pivot_table (data, values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All', observed=False)
Copy the code

The official document explains each parameter as follows:

Make a PivotTable with “sector name” and “trade Date”, with “sector name” in front and “trade date” in the back, so you can see how each sector has changed over the course of the week. As follows:

df_bk_pivot = pd.pivot_table(df_bk_week,index=["Plate Name"."Trading Day"])
Copy the code

In the table above, BK refers to the rise and fall of the sector, and SK refers to the rise and fall of the leading stock. If we do not need to show this column, we can use VALUES to select the value column to be aggregated, as shown below:

df_bk_pivot = pd.pivot_table(df_bk_week, index=["Plate Name"."Trading Day"], values=["BK ups and downs"."Rising numbers"."Falling numbers"."Total Market value"."Turnover rate"])
Copy the code

These are the basic methods for using pivot_table(). For industry sector data, I pay more attention to the “turnover rate” and “the number of ups and downs.”

Let me describe how to use Pivot_table () to look at “ups and downs.”

I observe the number of “ups and downs” data is in a certain hot plate continues to be hot, I observe the duration of the hot plate through the percentage of the number of ups and downs. Usually when a plate is fast flare-up, although some leading stocks are still rising, but the same plate will fall ahead of schedule.

We need to do some processing on the data to calculate the rising percentage value of the sector, as shown below:

df_bk_week["Increase ratio"] = df_bk_week["Rising numbers"] / (df_bk_week["Rising numbers"] + df_bk_week["Falling numbers"])
df_bk_week["Increase ratio"]=df_bk_week["Increase ratio"].round(2)
Copy the code

Let’s do another pivotchart. Columns =[” trading day “], and insert the trading day into the columns parameter.

df_bk_pivot = pd.pivot_table(df_bk_week, index=["Plate Name"], columns=["Trading Day"], values=["Increase ratio"], aggfunc=np.mean)
Copy the code

In addition, the aggfunc parameter is very important. You can use a list or dictionary to set the calculation method of the data column, such as summation, average, maximum or minimum, etc. The default is average. But we don’t need to use it here.

Thermal map visualization

Just having a PivotTable is not very intuitive to me. So I combined the Heatmap of Seaborn library to show the change of the number of ups and downs of plates. The effect is as follows:

According to the change of color shade, the number of stocks rising on 7-28 and 7-29 is relatively high, which can also be consistent with the trend of the Shanghai Composite index. As follows:

According to the change of color depth, 7-27 precious metals and jewelry plate is the hot spot of the day, but only a one-day tour market, the following days are not very powerful.

Of course, HERE I only find one week’s data to give you a demonstration. In actual analysis, we need to analyze daily plate data coherently, so that we can find more accurate signs of rotation of some plates.

conclusion

Through this simple and practical stock quantitative scenario, I hope to give the majority of friends for quantitative trading have an intuitive feeling.

Then, we should upgrade their own way to fry, the stock before their own that set of methods, abstract into a strategic model, with quantitative methods to the whole market back test evaluation, and then let the program to help us monitor the trend of the market.

This is the quantitative trade that ordinary shareholder place suits opens way!

— — — — — — — — — — — — — — — — — — — — — — — —If you want to have a more comprehensive and systematic introduction to the knowledge points involved from 0-1 way, here I recommend my book to youQuant Trading in Python Stocks from Beginning to Practice! Tmall, JINGdong, dangdang fully open for sale!

At the same time, you are welcome to follow my wechat official account [Yuanxiao Master Takes you to quantitative Trading in Python] to learn more about quantitative trading in Python

Routines in the code, uploaded to “play with the stock quantitative trading” knowledge planet (knowledge planet catalog can click [read] view).