Python data analysis and visualization (16) financial quantification (financial tools, financial analysis, installation and use of Tushare, double average analysis)

financial introduction

Finance is to realize the equivalent circulation of value and profit after reintegrating existing resources.
For example, Xiao Ming wants to invest his funds in Xiao Li, and Xiao Li has a good value-added project but lacks funds. If Xiao Li's project is successful, Xiao Ming's funds will increase.

Financial tool

Financial assets that can be traded in the financial market are mainly divided into stocks, futures, gold, foreign exchange, funds, bonds, etc. Investing is essentially buying low and selling high.

futures

Spot refers to existing items. For example, power plants need to purchase a large amount of coal from the coal market for power generation. It is estimated that the price of coal will increase, so power plants will hoard a large amount of coal. On the one hand, it is used to generate electricity by itself, and part of it is sold to other manufacturers who have demand for coal, thereby earning the price difference.
Futures refer to goods with a specified period of time. It is a standardized tradable contract based on certain mass products such as cotton, soybeans, oil, etc. and financial assets such as stocks and bonds . Therefore, the subject matter can be a certain commodity (such as gold, crude oil, agricultural products), or it can be a financial instrument.
Futures are based on the different expectations of the buyer and the seller for the future value of the commodity. The two parties have different expectations for the commodity. One side is bullish and the other side is bearish. Only in this way can a futures contract be reached.
For example, a large amount of corn is planted, and the price of corn before harvest is 2,000 yuan per ton. Farmers expect the price of corn to decrease and sell it to purchasers before harvest. The purchaser expects the price of corn to rise to 2,050 yuan per ton. Sign the acquisition contract for the next phase. If the price rises after harvest, the acquiring firm earns the difference. Buyers are bullish on the value of commodities and stock up; farmers are bearish on the value of commodities and ship ahead of time.

gold

Rare things are more expensive, and gold is scarce, and it has been a hard currency since ancient times, especially in war years. Some people will invest in gold and earn the price difference after gold rises. In the early days, the U.S. dollar was linked to gold. After World War I, the United States accumulated a large amount of gold, accounting for 70% of the global storage capacity. In order to facilitate transactions between both parties, the U.S. dollar was used as the transaction currency. However, the storage capacity of gold was limited. When a large amount of dollars is needed, dollars can no longer be issued out of thin air; if gold mines are discovered again, more dollars can be printed and issued as the amount of gold increases. The discovery of gold mines is not easy, so I thought of another way to link the US dollar to oil. It is like printing and issuing US dollars as much as there is oil. When a war is launched, the oil mines will be occupied first. If there is more oil, US dollars can be printed and issued to buy other products. The physical goods of the country, and the assets of other countries are harvested.

foreign exchange

Foreign exchange is a creditor's right that can be used in the balance of payments deficit held by the monetary administration (central bank, currency management agency, foreign exchange stabilization fund, and Ministry of Finance) in the form of bank deposits, treasury bills of the Ministry of Finance, and long-term and short-term government securities.
Foreign exchange refers to the exchange rate of currency exchange, such as the exchange rate between the US dollar and the renminbi. Someone will take advantage of the changes in the exchange rate to earn funds generated by the exchange rate difference. The fluctuations between exchange rates are very small, and the price difference earned by individuals is very small. Most of them are purchased by trading companies or administrative authorities to offset the impact of foreign exchange fluctuations on the economy and maintain the stability of the domestic economy. As more dollars are printed, more dollars will be circulated in the market, and the exchange rate against the dollar will change.

investment fund

Investment funds are institutions that raise capital through public offering of fund shares and then invest in securities. Investment funds are managed by fund managers and fund custodians, who conduct securities investment activities in the form of asset portfolios and serve the interests of fund share holders.
It is illegal to raise funds privately, and there is no guarantee. Individuals will inevitably keep a large amount of funds for themselves.
The fund manager will constantly adjust the investment combination and investment ratio. For example, 90% of the funds raised will be invested in stocks, 3% in bank deposits, 2% in bonds, and the rest in other investments. Changes in stock prices will affect the income of the fund, and the manager will constantly adjust the proportion and combination of investing in different stocks.

stock

A stock is a certificate issued by a joint-stock company to investors, and stock holders are shareholders of the joint-stock company. Invest in stocks to earn the price difference. For example, if you buy 8 yuan a share, the price rises to 20 shares, and you can earn the price difference when you sell it.
Shares are used as proof of capital contribution, proof of shareholder identity, and shareholders with relatively large shares can express their opinions on the company's operations, and can also participate in company dividends and trade profits.
Listing/IPO: Enterprises publicly issue additional shares to the public through the stock exchange to raise funds.
If the company goes public and other people buy shares, there will be too much inflow of external capital, resulting in the dilution of internal shares, and the company's decision-making will be influenced by outsiders. For example, the domestic Huawei company is not listed, and the popularity of Alipay has reached the normal life of the people. The government has suspended the listing of Ant Financial to prevent the excessive inflow of external funds from affecting the company's decision-making and direction. required.
According to the classification of stocks, it can be divided into blue chip stocks, growth stocks, and ST stocks. Blue chip stocks refer to the relatively stable growth of the company's stock price without much fluctuation, and are suitable for people with conservative investment philosophy to buy; growth stocks refer to the stocks of companies with room for growth in the future and relatively large development potential; Report problems, the company's stock price and funds are abnormal, and the company may be delisted.
Classified according to the listing area:
A shares: listed in mainland China, RMB subscription and trading, Beijing, Shanghai, Shenzhen stock exchanges;
B shares: listed in mainland China, foreign currency subscription and trading;
H shares: listed in Hong Kong, China, trading rules are different;
N shares : Listed in New York, USA;
S-shares:
H-shares, N-shares, and S-shares listed in Singapore are not controlled by the government, and the fluctuations are relatively large, and the growth and decline are relatively large; A-shares are controlled by the government, so there will be no large fluctuations.
The composition of the stock market consists of listed companies (raising funds); the China Securities Regulatory Commission (monitoring and regulating the stock market to avoid malicious and private manipulation of stock prices), the Securities Industry Association (regulating professional qualification certificates issued by the industry), and exchanges (places for buying and selling stocks) ; Securities intermediaries.
The Shanghai Stock Exchange has only one main board (Shanghai Index); the Shenzhen Stock Exchange has a main board: Shenzhen Component Index (Shenzhen Component Index 500, with large and mature companies), small and medium-sized board: small business scale (small and medium-sized version), ChiNext: still Factors affecting stocks of start-up companies in the growth stage (GEM refers to)
: the company's own factors (its own operations, negative news, etc.), industry factors (the impact of related industries, such as the rise of coal, cost increases lead to lower profits ), market factors (the impact of the entire market, the domestic government's macro-control makes little change in the impact), political factors (major premise, support for national policies; national development planning and adjustment), economic factors (economy, financial market) 1. Psychological factors (the only thing investors can control, keep a normal state of mind).
Trading of A-shares:
● Stock trading days: Monday to Friday (non-statutory holidays and exchange closing days), so when analyzing financial and stock data, the time data is not continuous.
● Trading time
○ 9.15-9.25 opening call auction time
○ 9.30-11.30 premarket, continuous auction time
○ 13:00-15:00 aftermarket, continuous auction time
○ 14:57-15:00 Shenzhen Stock Exchange closing call auction time

financial analysis

Fundamental analysis

Industry analysis; company analysis (financial data, performance reports, etc., can only be analyzed at this level); macroeconomic analysis (national fiscal policy, monetary policy, etc.)

technical analysis

K line

Similar to a boxplot. Red means rising, green means falling, and the opposite is true in foreign countries.
insert image description here
The top of the line in the red box chart is the highest point of the stock on that day, the bottom is the lowest point of the stock on the day, the lowest point of the box is the opening price, and the highest point is the closing price; the highest point and the lowest point of the box in the green box chart are The bottom is just the opposite. K-line charts are divided into daily K, weekly K, monthly K, quarterly K, and yearly K, such as Baidu’s K-line charts. There are regional zoom configuration items below, using the Echart component.
insert image description here

MA (average, moving, avg)

The moving average is an arithmetic moving average, and MA5 takes 5 days as an interval. For example, the MA5 value of No. 5 is the sum of the values ​​of No. 1-5 and divided by 5; the MA5 value of No. 6 is the addition of the values ​​of No. 2-6 Divide by 5; No. 7 is the average of No. 3-7.
The most common is the time period. MA5 and 10 respectively refer to the 5-day and 10-day moving averages as short-term moving averages, also known as daily averages; 30-60 days as medium-term moving averages, called quarterly moving averages Index; 120-240 days is the long-term moving average, called the annual average index.

understand the content

MACD: Exponential Smoothing Moving Average; KDJ: Stochastic; RSI; BOLL

Financial Quantitative Investment

Quantitative transactions can improve transaction efficiency by a hundred times compared with traditional transactions. The data for quantitative trading reference can be data from many years ago. When quantitative trading was not popularized in the early days, many traders or people who were good at investing used their brains to analyze the current market situation and changing trends. This required such people to have rich industry experience. Human brain memory is limited, and it is impossible to grasp all the situations. After all analysis, it is necessary to do quantitative transactions at this time. According to the previous data (transaction status), analyze the timing suitable for investment, realize it through code, and perform batch operations. For example, if the setting is 20% lower than the normal price, you can buy directly, and if it is higher than 20%, you can sell directly.

Quantitative trading

Financial quantitative analysis mainly refers to replacing human subjective judgments with advanced mathematical models, and using computer technology to select a variety of "high probability" events that can bring excess returns from huge historical data to designate strategies.
The main steps are as follows:
● A flash of inspiration, sudden thinking
● Refinement of strategies, input in batches
● Transformation of strategies into programs, formulation of number strategies, automatic implementation of conversion into programs
● Test of strategy results
○ Backtest, re-test the effect of strategies
○ Simulated trading, how much profit can the investment strategy bring during the backtesting process
? For real trading, run it under ideal conditions. If the effect is good, then conduct real trading

Quantify the value of the transaction

● Avoid subjective emotions, human weaknesses and cognitive biases, choose more objectively and not be affected by subjective consciousness, if you buy something, you want to sell it quickly, and if you don't know enough about things, there will be one-sided deviation.
● It can include multi-angle observations and multi-level models at the same time, depending on the company's financial report revenue in recent years.
● Track market changes in a timely manner, constantly discover new statistical models, and look for trading opportunities.
● After deciding on an investment strategy, it can verify its effect through backtesting.

Tushare

Tushare pro is a python financial data interface package. It mainly realizes the process of financial data such as stocks from data collection, cleaning and processing to data storage (there is actually a crawler behind it), which can provide financial analysts with fast, clean, and diverse data that is easy to analyze, and provide them with great data acquisition. The workload is greatly reduced, allowing them to focus more on the research and implementation of strategies and models. Considering the advantages of the Python pandas package in financial quantitative analysis, most of the data format returned by Tushare is pandas DataFrame type, which is very convenient for data analysis and visualization with pandas/NumPy/Matplotlib.

Tushare installation

1.pip install tushare
2.访问https://pypi.org/project/tushare/   进行下载安装

Learning document: https://tushare.pro/, register in the document, use the interface TOKEN of the personal homepage, and obtain and call data when writing code.

Tushare use

Obtain Wuliangye stock historical market data

To analyze the data of the stock, first establish the interface, copy the data of the interface TOKEN from the learning document, and establish a link to obtain the stock data. The suffix of the Shanghai Stock Exchange is .SH, the suffix of the Shenzhen Stock Exchange is .SZ, and the suffix of the Beijing Stock Exchange is .SZ. The suffix of the stock exchange is .BJ, and the suffix of the Hong Kong Stock Exchange is .HK.
Obtain the historical market data of Wuliangye stock, if you do not write the start_date parameter, it will be all dates.
insert image description here
No need to write a crawler program anymore, you can directly use the financial data interface package to obtain data. January 1-3 is a holiday and the market does not open, so the data starts from January 4, 2010. parse_dates means setting a column as a time type, where trade_date is not only an index, but also a time type.
insert image description here
Only keep the required opening, closing, highest, lowest value columns.
insert image description here
Output the date that the stock closed more than 3% higher than its open.
insert image description here
Output the date when the stock's opening price fell more than 2% from the closing price; output the date when the stock's opening price fell more than 2% from yesterday's closing price.
insert image description here

Buy on the 1st of each month, sell on the last trading day at the end of the year, and calculate the income

Starting from January 1, 2010, buy 1 lot (100 shares) of stock on the first trading day of each month, sell all stocks on the last trading day of each year, and calculate the income by the end of 2021.
insert image description here
Resample the data, adjust the collection frequency to once a month, and calculate the cost of selling stocks.
insert image description here
Resample the data, take the last day of each year, calculate the selling price of the stock
insert image description here
and calculate the income value.

Double moving average analysis

For each trading day, the moving average of the previous N days can be calculated, and then these moving averages can be connected to form a line, which is called the N-day moving average. Commonly used moving averages: 5-day, 10-day, 30-day, 60-day, 120-day and 240-day indicators, namely MA5, MA10, etc.
● 5-day and 10-day reference indicators for short-term operations, called daily moving average indicators;
● 30-day and 60-day moving average indicators, called quarterly moving average indicators;
● 120-day and 240-day long-term moving average indicators, It is called the annual average index.

golden cross

When the short-term moving average crosses the long-term moving average, it is a buy signal, and the corresponding date should be bought. Generally compare the values ​​of MA5 and MA30. The comparison in the figure is that MA10 is long-term relative to MA5.
insert image description here

death cross

The short-term moving average crosses the long-term moving average, which is a sell signal, and the corresponding date will be sold.
insert image description here
Find the intersection of the two lines to buy and sell.

Double moving average analysis exercise

  1. Use the tushare package to get the historical market data of a stock
  2. Use the tushare package to calculate the 5-day moving average and the 30-day moving average of the stock's historical data
  3. Use the matplotlib package to visualize the closing price and two moving averages of historical data
  4. Analyze and output all golden cross dates and dead cross dates
  5. If I start on January 1, 2010, with an initial capital of 10W, buy as much as possible of golden crosses, and sell all dead crosses, it will end today. What is my stock yield?

The implementation steps are as follows:
insert image description here
After obtaining the data, save it in time to avoid data changes.
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/hwwaizs/article/details/127876429