How to find stocks worth long-term investment in R language

Written in front

Finally start using the R language to carry out stock investment practices I have been interested in it, it is really exciting, and the heart is awkward. ^ _ ^^ _ ^^ _ ^

Before starting to practice, let me talk about me to talk about the investment of A stock. I have studied stock investment for a while, I insisted that stock investment is a more good financial management method in the domestic financial management method. But the premise is that you must learn to learn and learn, and you have access to this field after you have relevant financial knowledge. You have opened a restaurant, but also to learn business management, and even study the kitchen art; a treasure buy a dress and more than three, and the buying market is buying, only feeling? Of course, there must be financial knowledge and risk awareness. Be sure to build your own trading system, otherwise it will be cautious. This is an advice, and it is my blood lesson.

Refer to the trading system, then say a few words. The so-called own trading system is to choose the way of investment in your own. Select Tencent, Google’s high-growth company, long-term holding stocks is a trading system, which is patience; low buy high sales in the stock market, frequent operation acquisition, and the trading system, dealing with technical indicators Application; research national policies and industry characteristics, analyzes the chance of reform and reorganization in St. State-owned enterprises, and obtain high returns, and the transaction system, relying on the allergic interpretation of macro policies and the unique study of fundamentals; hold traffic; Such a giant Macon, eating dividend and dividend benefits, while doing risk-free, new strategies, is also a trading system, relying on a stable mentality. The benevolent seeing the benevolence, the trading system is not in good condition, only suitable or not. Buffett is known for its value investment, and countless future people are sought after; and Soros is full of pottery, is it wrong?

The stock trading is zero and games are not fake. You earn money is definitely a loss of someone or some people. But it is completely different from gambling, stock trading wants to achieve a profit is to control the risk, continue to do a big probability event, not by luck. From logically analyzing, buying growth companies and long-term holding, big probability will make money, this is unquestionable.
But in the specific operating level, the stock operation is still very testing, can have a decade-in-one funds to put it, can buy the stock price after the purchase of the stock price, can tolerate the buying stock two years The original price is even lower (Buffett also has been bought after a few years) ………. You can ask yourself, when you encounter these situations, you will have the urge to sell. It is better than weight loss, everyone knows less and more exercise, it will be thin, but the proportion of people do in real life is extremely low.

Here I want to say here is that buying growth companies have long been holding, this is the “Tao” level, which is macro guidance; specific investment needs to master fundamental analysis, quantity relationship, left and right sides Different trend transactions, even K-line, etc., “technique”, will develop microactive strategies. “Tao” combined with “surgery”, using strategies such as fixed investment, it is best to invest in US stocks (the policy impact is small, you know). This is my investment experience, and it is also the direction I am working hard. Interest with everyone.

Nonsense, now start my R language practice journey:Analyze the stock fluctuations and long-term income in the R language.

1, select the target

Choose a variety of A shares that can be called value investment in Guizhou Maotai (600159), mechanical leading three heavy workers (600031) and the cultured concept stock Zhengbang Technology (002157). Time span from January 2007 to the end of August 2017, see how the three stock income have been held. At the same time, this decade is also a ten-year in the housing prices, contrast, and see what the results can be.

Description: Zhengbang Technology is listed on August 17, 2007, and time is a little bit a little bit.

2, calculating the 10 years of income holding three stocks

(1) Read the stock data and save the disk

Use the QUANTMOD package to read three stock data in the R language, and download the stock data of course. code show as below:

### Read stock data and store library library library library (quantmod) library (DPLYR) library (stringr) Data1 <- getsymbols ("", src = "yahoo", from = "2007-01-01", To = "2017-08-31", auto.assign = false #ChartSeries (``) DATA2 <- getsymbols (" ", src =" yahoo ", from =" 2007-01-01 ", to =" 2017-08-31 ", auto.assign = false) DATA3 <- getsymbols (" ", src =" yahoo ", from =" 2007-01-01 ", to =" 2017- 08-31 ", auto.assign = false Write.csv (data1, file =" g: / statistical probability learning practice / third level practical job /DATA/600519.csv")write.csv(data1 ,file = " G: / Statistics Probability Learning Practice / Third Off Practice Work / Data/600031.CSV "Write.csv(data1, File =" G: / Statistics Probability Learning Practice / Third Off Practice Work / Data/002157.CSV " )

(2) Holding these stocks 10 years of income

In the stock investment, the calculation formula of the yield is:

Yield = net profit / cost = {(Price – buy price) * Shares – handling fee} / (buy price * shares + buy time)

Suppose we hold 10 years after we buy, assume that the shares have not changed, and the calculation formula can be simplified as:

Yield = net profit / cost = (Best – buy price) / buy price

### (1) Calculate the decade with closing price # First transform into weekly data MT <- to.Weekly (data1) SY <- to.Weekly (data2) zB <- to.Weekly (data3) MTClose <- Cl (MT) MTRATE10 <- (As.Numeric (MtClose [1,1]) * 100 / as.numeric (mtclose [1,1]) mtrate10 < - Round (mtrate10, 2) Syclose <- Cl (Sy) Syrate10 <- (as.Numeric (Syclose [546,]) - as.numeric (Syclose [1,])) * 100 / as.numeric (Syclose [1 ,]) Syrate10 <- Round (Syrate10, 2) ZBClose <- Cl (ZB) ZBRATE10 <- (As.Numeric (zbclose [1,]) * 100 / as. Numeric (zbclose [1,]) zbrate10 <- round (ZBRATE 10, 2)

With the collection price of August 31, 2017, three stocks have been calculated for ten years of stocks, respectively: Maotai is 657.76%, three is 180.61%, and Zhengbang is 109.87%.

Special declaration: The above income is just a simple calculation of downloaded data, which may have access to it (This data has no extension). Because Moutai has dividends, ten-year time spans measures the income of the income, the Zhengbang is too high in September 2016, which is equivalent to the total number of stocks will increase, and the actual benefits are also much higher than 109.87%. Three don’t know much, don’t comment.

Overall, in January 2007, investing in these three stocks and holding more than ten years, investment funds will be at least doubled, and the income of Maotai will be more than 6 times. Everyone can compare the housing prices in their city, if the investment in investment in investment in the property is ten years ago? Anyway, the urban house price in the middle is doubled, which is doubled, and it is still very cost-effective from stock investment from the perspective of investment. After all, the house is a big fund, if the staging is still calculated to calculate the interest rate of the bank. In the north, the Guangzhou-Shenzhen housing price increases, and it may investigate the revenue of the property.

(3) Stock price fluctuations tell us investment strategy

Draw three stocks in the closing price fluctuations of three stocks with the Chart_Series () function of the QuantMod package.

### (2) Draw a week-line graphic and analyze fluctuation law Chart_Series (CL (MT), Name = "Guizhou Moutai") Chart_Series (Sy), Name = "three heavy work") Chart_Series (CL) ZB), Name = "Zhengbang Technology")

It can be seen from the figure that from the 10-year investment span, Guizhou Maotai has the highest value, and the Zhengbang Technology is the worst. Simple analysis is because the three heavy workers belong to the engineering infrastructure industry, and the infrastructure investment is very big in relation to the economic cycle of the country. As the economic cycle fluctuates its performance fluctuations, it is reflected in the stock market to fluctuate. . I believe this volatility of colored and coal-based stocks.

The thus thus derived is that if you have an investment for a long time, you should avoid the cycle stock, try to choose the consumer or growth of white horse stocks.

3, analyze the fluctuations of three stocks within 10 years

(1) Draw a month K

Transform three stock day trading data into moon data, using a chartseries () function in the R language to draw the highest, lowest, open, and closed four prices for the month K line map to see their fluctuations.

(2) Analysis by ATR and ADX index

The use of ATR and ADX indicators for analyzing the size of the stock price and the weak trend.

Theatr is “true fluctuation floating mean”. At the time, the ATR volatility is fluctuating around the average line, and the maximum market is sharply increased. It is generally believed that the higher the ATR indicator, the greater the chance of the price trend reversal. As a volatility indicator, ATR only provides volatility inspiration and cannot predict the stock price direction.

adx is an average tendency indicator. It is another common trend metrology. It can’t tell your trend development direction, but ifSecond-hand mobile game transferMapThe trend has a measure of the trend. Baidu-related information is shown so.

Adding an ATR line and the monthly K line diagram of the ADX line. code show as below:

ChartSeries (TO.MONTHLY (DATA1), Name = "Guizhou Maotai", Theme = "White") AddATR () addadx () ChartSeries (to.Monthly (Data2), Name = "Triangle", Theme = " ") adduR () addadx () chartseries (to.monthly (data3), name =" Zhengbang Technology ", Theme =" White ") addATR () addadx ()

​​Three stocks added ATR lines and ADX lines K line diagrams as follows:

The ATR indicator of Maotai, Guizhou Province basically reflects the volatility of the stock. However, in the second half of 2014 to 2015 and 2016, ATR fluctuations were large, distorted.

ADX indicator reflects the trend of Maotai stocks in Guizhou, but in 2010 ~ 2012 and 2014 to 2015, the two time period stock prices were similar, but the tendency of two time before and after two days ago.

The ATR index of the three heavy workers is very energetic with the share price fluctuation. However, the ADX indicators have distorted in the first half of 2015, and the intensity of the indicator size is far from the actual share price.

The ATR indicators of Zhengbang Technology and the ADX indicators are consistent with the stock price.

Thick conclusion is: Longline investment, the ATR and ADX indicators are just a reference role, not suitable as actual operation basis. The long line is simple to settle.

In addition, addMA, AddMACD, etc. can also be added, which can be viewed for use. After the general investor understands these technical indicators, it is possible to judge the fund and other financial products. If you choose a better product, it is not necessary to entangle itself. Many wealth management products have a corresponding portfolio of the data extraction and linear planning. As long as we “know it,” it is, we don’t have to pursue “it haira”.

4, three stocks and correlation analysis with the endorsement index

Investment in the stock market, although there will be different plates, the market is falling in the market, and there is still a phenomenon of rise against the market. However, from the decade of time span, there is no correlation between the rise and fall between the three stocks and their and their comparison index?

10 (August 31, 2007 to August 31, 2017) Time adjustment data for three stocks and admix index (000001) with R language. Analysis of the relationship between the Corr.Test () function using the psych package.

### (3) Analyze the correlation between three stocks and admissions index to adjust the price of the price SS <- getsymbols (C ("000001.SS", "", "", " "), src =" yahoo ", from =" 2007-08-31 ", to =" 2017-08-31 ") Ad <- cbind (AD (``), ad (`` ), Ad (`600031.S`), ad (``)) Ad <- (ad) library (psych) Corr.test (ad)

It can be seen by the results: Compared with the previous card index, the relationship between Guizhou Maotai and Zhengbang Science and Technology is 0.22 and 0.25, and there is a certain correlation; while the three heavy workers follow the relevant coefficients of 0.06, it is basically no correlation.

Compared with Guizhou Maotai, Zhengbang Technology’s correlation coefficient is 0.76, and it is better correlation; the three heavy workers have no correlation with them. The reason, Although Guizhou Maotai and Zhengbang Technology does not belong to the same sector, it is shares related to people’s live consumption, and its performance is related to consumption, and the growth logic has a certain similarity. And the performance of the three heavy workers is different from the logic of them.

Rough conclusionFrom the long-term, not all stocks are related to the previous index index. The key to long-term investment is the selected standard, the preferred growth, the company has a performance support, must have a logic to support its share price long-term rising. This is also my new feelings when I practice.

Some descriptions and thinking

(1) The data used in the analysis is not extension, only as programming practices. In fact, if Guizhou Maotai’s dividend income has been far over the cost of share price, the stock price of the initial stock price has been negative.

(2) Stock Case Analysis is focusing on R language programming practice, and does not act as investment advice. The investment concept is a reference.

(3) QuantMod package is mainly technical analysis such as data and graphic display. If you just use these technical indicators as an investment reference, it is recommended to use big broker software, fully functional, accurate data. After all, I want to drink milk, I don’t have to have my own raise cattle.

(4) If you want to build your own investment quantization model or optimize your portfolio, the QuantMod package is far less than enough, and you need to cooperate with different bags. It feels that this is a category knowledge in the financial sector.

(5) The application of another door after the QUANTMOD is applied, and the field of quantization transactions. But I can’t forget to look up, don’t enter the misunderstanding of blind learning. In order to learn, not to learn. This is also true of the financial package QUANTMOD. After understanding its function, you can use the tool.Because of the value investment, technical analysis, quantitative transactions are divided into different martial arts, and it has been controversible for a hundred years, and the key to the key is not necessarily to earn money..

(6) Investment must pay attention to the logic behind, and then stick to your logic and constantly correct. And reality is that most people do not have their own logic.

This practice is most gratified, and the biggest gain is: The financial package QUANTMOD links large data programming and stock investment, two I originally feel that the field is not related to, the middle door is open. Two different dimensions have found intersections, very happy, very happy! ! !

a:hover, a:visited, a:link, a:active { text-decoration: none !important; -webkit-box-shadow: none !important; box-shadow: none !important }a:hover, a:visited, a:link, a:active { text-decoration: none !important; -webkit-box-shadow: none !important; box-shadow: none !important }