Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Stock return Analysis based on Python

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "how to achieve stock return analysis based on Python", so the editor summarizes the following contents, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to achieve stock return analysis based on Python" article.

Case detail

Company An is a public offering fund management company headquartered in Beijing. Among all the fund products issued by the company, one is called "New Financial Equity Fund". In terms of investment strategy, the fund is a selection of A-share market financial stocks with core competitive advantages, sustained growth potential and relatively reasonable valuation.

By the end of September 2019, the heavy positions of the fund included six stocks, namely, Pudong Development Bank, China Merchants Bank, CITIC Securities, Haitong Securities, Ping an of China and China Pacific Insurance. Table 7-2 shows some of the daily closing prices of the six stocks from January 2014 to the end of September 2019, and all the data are stored in the Excel file.

Part of the daily closing price of six financial institutions in the A-share market between January 2014 and September 2019.

Data source: Shanghai Stock Exchange. (unit: yuan / share)

Suppose you are an assistant fund manager in Company A, and your daily job is to assist the fund manager of the "new financial equity fund" to track and analyze the stocks that have been invested. According to the requirements of the fund manager, you need to use Python to complete three programming tasks.

Programming task

[task 1] Import the Excel file of the daily closing price of these stocks in Table 7-2 from January 2014 to September 2019, and calculate the daily return, annualized average rate of return and annualized return volatility of each stock. Natural logarithm is needed to calculate the daily return.

[task 2] for the portfolio constructed by these six stocks, an array containing the allocation weight of each stock is randomly generated (the total weight is equal to 1), and the annualized average rate of return and annualized return volatility of the portfolio with this weight are calculated.

[task 3] an array containing 2000 groups of different stock allocation weights is randomly generated to calculate the corresponding 2000 different portfolio annualized average rate of return and annualized return volatility. And the scatter chart is drawn in the coordinate axis of the Abscissa as the annualized return volatility and the ordinate as the annualized average rate of return.

Programming hint

For Task 2, assuming that the portfolio consists of N stocks, wi represents the weight of the first stock in the portfolio (the proportion of the market value of the stock to the overall market value of the portfolio), and E (Ri) represents the expected return of the first stock in the portfolio (replaced by the average of the past return of the stock). The expression of the expected return E (RP) of the portfolio is as follows:

At the same time, assuming that σ I represents the return volatility of the first stock, and Cov (Ri,Rj) represents the covariance between the return of the first stock and the return of the first stock, the σ p expression of portfolio return volatility is as follows:

Refer to the code In [1] of Code Task 1: import numpy as np.: import pandas as pd.: import matplotlib.pyplot as plt.: from pylab import mpl.: mpl.rcParams ['font.sans-serif'] = [' KaiTi'].: mpl.rcParams ['axes.unicode_minus'] = FalseIn [2]: stock_price=pd.read_excel (' C:/Desktop/ Financial stocks (2014-September 2019). Xlsx' Sheet_name= "Sheet1", header=0,index_col=0) # Import external data...: stock_price=stock_price.dropna () # Delete rows of missing values In [3]: (stock_price/stock_price.iloc [0]) .plot (figsize= (9) 6) Grid=True) # normalize the stock price according to the first trading day of 2014 and visualize Out [3]: In [4]: stock_return=np.log (stock_price/stock_price.shift (1)) # calculate the daily return of the stock.: stock_return=stock_return.dropna () # delete the line where the missing value is located: In [5]: return_mean=stock_return.mean ( ) * 252 # calculate the average annualized return on stocks.: print ('average annualized return from 2014 to September 2019\ n' Return_mean.round (6)) # keep 6 decimal places annualized average return from 2014 to September 2019 Pudong Development Bank 0.042824 China Merchants Bank 0.211223 Haitong Securities 0.043759 Huatai Securities 0.138177 Ping an 0.134000 China Pacific Insurance 0.117563dtype: float64In: return_volatility=stock_return.std () * np.sqrt (252) # calculated stocks Annualized earnings volatility.: print ('annualized earnings volatility from 2014 to September 2019\ n' Return_volatility.round (6) annualized earnings volatility from 2014 to September 2019 Pudong Development Bank 0.282428 China Merchants Bank 0.296238 Haitong Securities 0.396386 Huatai Securities 0.449228 Ping an 0.465064 China Pacific Insurance 0.359268dtype: float64

From the chart below, it is not difficult to see that because the six stocks are all financial stocks, there is some convergence in the overall trend. However, the average annualized return of each stock is quite different, among which the average return of China Merchants Bank is the highest and that of Pudong Development Bank is the lowest. At the same time, in terms of average annualized volatility, bank stocks are the lowest and Ping an of China is the highest.

Stock price chart of 6 financial stocks from January 2014 to September 2019 (the stock price will be treated as one on the first trading day of 2014)

Task 2 code In [7]: x=np.random.random (len (return_mean.index)) # randomly selects 6 random numbers from 0 to 1 from uniform distribution In [8]: w=x/np.sum (x) # generates an array of random weights.: W # View the generated random weight array Out [8]: array ([0.24372614, 0.03925093, 0.20889395, 0.20843467, 0.23808734) 0.06160696])

It is important to note that because it is a randomly generated array, the random weight array is different each time, but the total number of weights is equal to 1.

In [9]: return_cov=stock_return.cov () * 252 # calculate the covariance between the returns of each stock.: return_covOut [9]: Pudong Development Bank China Merchants Bank Haitong Securities Huatai Securities China Ping an China Pacific Insurance Pudong Development Bank 0.079765 0.054347 0.055693 0.065324 0.062048 0.056216 Bank 0.054347 0.087757 0.058148 0.066847 0.078228 0.072074 Haitong Securities 0.055693 0.058148 0.157122 0.147365 0.092994 0.086569 Huatai Securities 0.065324 0.066847 0.147365 0.201806 0.102020 0.09885 Ping an of China 0.062048 0.078228 0.092994 0.102020 0.216285 0.110579 China Pacific Insurance 0.056216 0.072074 0.086569 0.06885 0.110579 0.129074In [10]: _ return.corr () # calculate the correlation coefficient between the returns of each stock.: return_corrOut [10]: Pudong Development Bank China Merchants Bank Haitong Securities Huatai Securities Ping an China Pacific Pudong Development Bank 1.000000 0.649575 0.497483 0.514872 0.472398 0.554035 China Merchants Bank 0.649575 1.000000 0.495191 0.502310 0.567816 0.677201 Haitong Securities 0.497483 0.495191 1.000000 0.827580 0.504459 0.607889 Huatai Securities 0.514872 0.502310 0.827580 1.000000 0.488321 0.600306 Ping an of China 0.472398 0.567816 0.504459 0.488321 1.000000 0.661823 China Pacific Insurance 0.554035 0.677201 0.607889 0.600306 0.661823 1.000000In [11]: Rp=np.dot (return_mean W) # calculate the annualized return of the portfolio.: Vp=np.sqrt (np.dot (wjournal np.dot (return_cov,w.T) # calculate the annualized return volatility of the portfolio.: print ('calculate the annualized rate of return of the portfolio using randomly generated weights', round (Rp) 6): print ('calculate the annualized return volatility of the portfolio using randomly generated weights', round (Vp,6)) use randomly generated weights to calculate the annualized return of the portfolio 0.095816 and use the randomly generated weights to calculate the annualized return volatility of the portfolio 0.315454

From the above correlation coefficient output results, it is not difficult to see that because they are all financial stocks, the correlation coefficient between different stocks is relatively high, and the diversification effect of the portfolio may not be ideal. In addition, according to the randomly generated weights, the annualized return on the portfolio is 9.581 per cent and the volatility is as high as 31.545 per cent.

The code for task 3 In [12]: x_2000=np.random.random ((len (return_mean.index), 2000)) # randomly selects random numbers from 0 to 1 with 6 rows and 2000 columns from a uniform distribution. In [13]: w_2000=x_2000/np.sum (X-ray 2000) generates an array containing 2000 random weights.: w_2000Out [13]: array ([0.19250103, 0.01845509, 0.01765565,... 0.33889512, 0.0463229, 0.26199306], [0.07263106, 0.00973181, 0.13055863,..., 0.03118864, 0.20474944, 0.06271757], [0.09534805, 0.30004746, 0.18353861,..., 0.13704764, 0.22151316, 0.12965449], [0.09386134, 0.16068824, 0.212781,... 0.02455051, 0.13288678, 0.03435049], [0.25893945, 0.31725497, 0.14183784,..., 0.00825204, 0.03630956, 0.14306535], [0.28671907, 0.19382242, 0.31362827,..., 0.46006606,0.35821817,0.36821904]) In [14]: Rp_2000=np.dot (return_mean) Whist2000) # calculate 2000 returns for different portfolios.: Vp_2000=np.zeros_like (Rp_2000) # generates an initial array In [15]: for i in range (len (Rp_2000)): # quickly calculates 2000 different return volatility of a portfolio with a for statement. : Vp_2000 [I] = np.sqrt (np.dot ((walled 2000.T) [I] Np.dot (return_cov,w_2000 [:, I])) In [16]: plt.figure (figsize= (9))...: plt.scatter (Vp_2000,Rp_2000)...: plt.xlabel (u 'volatility', fontsize=13)...: plt.ylabel (u 'yield', fontsize=13) Rotation=90): plt.xticks (fontsize=13)...: plt.yticks (fontsize=13)...: plt.title (u 'portfolio yield versus volatility', fontsize=13)...: plt.grid ('True')...: plt.show ()

The scattered points in the following figure are the portfolio returns and volatility corresponding to the random generation of 2000 sets of different investment weights. Through the value mapped to the ordinate, it can be visually measured that the highest annualized return of the portfolio is more than 16%, and the lowest annualized rate of return is slightly less than 7%. The highest volatility of the portfolio is close to 37% and the lowest volatility is close to 26%.

The relationship between return and volatility of portfolio under the condition of randomly generated 2000 groups of different investment weights

The above is about the content of this article on "how to achieve stock return analysis based on Python". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more related knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report