[PYTHON] Analyze stocks to understand a company's performance

I wrote the first part in previous, so I thought it was the second part, but I left that story a little more and this time it reflected the business performance of the company. It is a story about stock prices, which can be said to be an index.

Get stock price data and calculate the weighted average, the previous day's comparison, and draw charts. I think there is a great need for various processing. In such a situation, the Python that was actually created in the field of financial transactions by the hands of the front line quants and others The library pandas is very practical, powerful and convenient because it has a lot of features and is fast to develop. However, I've used pandas itself a lot in the previous articles, so I don't need to explain it anymore.

In this article, stock price data is processed in chronological order with pandas and delivered to Gmail. (Thankfully, some articles in this series are also quoted. Thank you.) It is useful as one of the applications of pandas.

Now, let's say you want to analyze various information related to other companies. Here, no matter what is used as an explanatory variable in investigating what, in many cases, performance (= stock price) is considered to be a pillar of the evaluation index. So, this time, I would like to summarize the basics of investigating the general condition of stocks.

Technical analysis and random walk

Last year, in 2014, the performance of hedge funds managed in the Japanese market was 5.4%, which was higher than the world average of 4.4%.

Japan's hedge fund results 5.4%, surpassing the world average-good stock selection (1) http://www.bloomberg.co.jp/news/123-NIGU486JIJUT01.html

On the other hand, the average annual performance of US funds and hedge funds in Hong Kong and Singapore is said to be 15% to 20% per year. There are also asset management companies that are independent funds in Japan that generate more annual returns.

Of course, these have different amounts of investment funding, and [leverage](http://en.wikipedia.org/wiki/%E3%83%AC%E3%83%90%E3%83%AC%E3% 83% 83% E3% 82% B8) is also different. Leverage means that by depositing your own money as margin, you will be able to make large transactions using working capital that is several to several hundred times as much as the margin. Recently, forex, which is popular among individual investors, can be leveraged about 400 times. Hopefully this will give you a high return, but the risk is high and you may run out of margin due to slight exchange rate fluctuations. Of course, you can get a good deal by 2 to 3 times, or even 1 times, so it's better until you get used to it.

Daily data on public stocks can be checked on pages like Yahoo! Finance. For example, the stock price of DTS Corporation is like this.

[System Trading](http://en.wikipedia.org/wiki/%E3%82%B7%E3%82%B9%E3%83%86%E3%83%A0%E3%83%88%E3% 83% AC% E3% 83% BC% E3% 83% 89) may give you the impression that you buy and sell automatically on your computer, but the numbers and indicators that can be verified in the past. It refers to consistent trading by creating a model by combining such as, after repeating verification by backtesting, and buying and selling when it reaches a certain value.

It has the advantage of eliminating the emotional investment decisions inherent in investors and making decisions based on objective indicators. On the contrary, because it is systematic, it is vulnerable to unforeseen circumstances, and it also has the disadvantage that it is not possible to pick up trends based on the individual circumstances of the market due to excessive rule creation.

[Technical Analysis](http://en.wikipedia.org/wiki/%E3%83%86%E3%82%AF%E3%83%8B%E3%82%AB%E3%83%AB%E5% 88% 86% E6% 9E% 90) is a method of analysis by chart and analysis by computer by mathematical calculation. It seems that you are making full use of difficult technology by combining difficult mathematical formulas when you write it like this, but you can use the basic methods of data analysis that you have written so far to find trends in transaction prices by human visual judgment. It can be said that it is a technical analysis just to calculate the fluctuation price range.

[Random Walk Theory](http://ja.wikipedia.org/wiki/%E3%83%A9%E3%83%B3%E3%83%80%E3%83%A0%E3%83%BB% E3% 82% A6% E3% 82% A9% E3% 83% BC% E3% 82% AF% E7% 90% 86% E8% AB% 96) in a sense negates the scientific significance of this technical analysis head-on. It's a theory. In short, it doesn't matter if the monkey throws darts at random or chooses a transaction chosen by a professional, so it's a good place to turn back.

However, in reality, there is an argument that it is possible to make an accurate loss cut, which is the most rudimentary of investors, and to surely suppress a big trend and bring a positive profit and loss, and the author is also generally It's the same idea. In addition, technical analysis has the significance of preventing losses from transactions due to temporary emotions and aiming for differentiation that goes one step ahead of classical fundamental analysis by defining it according to specific rules and building a trading model. I think there is also.

Meaning of basic indicator terms

I've posted the Yahoo! Finance link above, but first you have to understand the basic terms. The main terms that appear on most sites and trading software are the same, so I will briefly summarize them below.

PER (Price Earnings Ratio) Price Earnings Ratio

\frac {Stock price} {Net income per share}

Shows how many times the stock price is the net income per share. A high price-earnings ratio means that the stock price is higher than the profit.

PBR (Price Book-Value Ratio) Price Book-value Ratio

\frac {Stock price} {Net assets per share}

Shows how many times the stock price is the net assets per share. PER shows the relationship with shareholders' equity with respect to profit. The point to note is that the capital adequacy ratio and other figures are included. Be careful when the capital adequacy ratio is low.

ROA (Return on Asset) Return On Asset

\frac {Net income} {Average shareholders' equity for the previous term and the current term}

It is an index to measure the management efficiency of how much profit you made in one year from your own capital.

BPS (Net Assets Per Share) Book-value Per Share

\frac {Total amount of retained earnings} {Number of issued shares}

Shareholders' equity per share. This is a financial index obtained by dividing the total amount of retained earnings such as legal reserves by the number of issued shares. It is a typical index to see the stability of a company in financial analysis, and a typical index to see the bargain of stock prices in stock investment.

How to analyze

I mentioned regression analysis before, but then can the regression equation be obtained from the price range of the stock price? In a word, I can't find it. You can easily understand the article that I tried to predict horse racing by regression analysis at here. Even if the explanatory variables are picked up, the multiple correlation coefficient does not increase, and if the explanatory variables are selected so that the multiple correlation is high, the model is arbitrary and does not accurately represent the reality.

This article summarizes an example of drawing a candlestick chart by acquiring Japanese stock price information from Yahoo! Finance. I am. Thankfully, the articles in this series are also quoted here. (Thank you) Of course, each site and smartphone app are also substantial now, so I think that it is enough if you just look at the chart. However, I think that the first step is to apply an original analysis model to the numerical values and perform an analysis that differentiates them from other investors.

Since it is a big deal, I will try to get the data of the stocks posted in my own stock information stock.txt based on the code of the linked article and plot it. For classes and methods, use the linked ones.

def read_data(stock):
    plotting._all_kinds.append('ohlc')
    plotting._common_kinds.append('ohlc')
    plotting._plot_klass['ohlc'] = OhlcPlot

    start = sys.argv[1]
    # start = '2014-10-01'

    try:
        stock_tse = get_quote_yahoojp(stock, start=start)
        stock_tse = stock_tse[-90:]
        stock_tse.to_csv("".join(["stockjp_", str(stock), ".csv"]))
        plt.figure()
        stock_tse.asfreq('B').plot(kind='ohlc')
        plt.subplots_adjust(bottom=0.25)
        plt.xlabel('Stock of ' + str(stock))
        plt.show()
        plt.savefig("".join(["stockjp_", str(stock), ".png "]))
        plt.close()

    except ValueError:
        print("Value Error occured in", stock)

def main():
    stocks = pd.read_csv('stocks.txt', header=None)
    for s in stocks.values:
        read_data(int(s[0]))

Let me give you some examples. Here are some companies that are similar to us (DTS). The chart is as of the time of writing.

IT Holdings (3626)

stockjp_3626.png

NTT DATA (9613)

stockjp_9613.png

Systena (2317)

stockjp_2317.png

Infocom (4348)

stockjp_4348.png

DTS (9682) stockjp_9682.png

Even when it comes to technical analysis, it is important to firmly control the basic trends from the chart. In addition to this, if you capture the moving average, it will be the basis first. You can calculate the moving average yourself or rely on stock software or sites.

SMA (Simple Moving Average) Simple Moving Average

Use it like SMA5 or SMA25. It is a simple moving average with each number as the number of days. There are various types of moving averages, but the differences are shown below. If you change the range of days, the trend may sound in the opposite direction, so I think it is an index that needs to be determined from the investor's perspective as to what to consider as a standard.

Simple moving average

SMA(n) = \frac {\sum_{i=0}^{n-1}(CLOSE_i)} {n}

Weighted Moving Average (WMA)

WMA(n) = \frac {\sum_{i=0}^{n-1}(n-i)(CLOSE_i)} {\sum_{i=1}^{n}n}

Exponential Smoothing Moving Average (EMA)

EMA(n) = EMA(n)_1 + \frac {2} {n+1}(CLOSE - EMA(n)_1)

It should be noted that n = average days or exponent i = i day ago indicator It will be.

Moving averages are widely used to judge trends and to signal buying and selling as resistance lines and support lines. It is a typical technical index.

Investment points

First of all, it is better to calculate the ideal stock price from PER. For example, simply take this.

Theoretical stock price= \frac {Expected annual net income} {Number of issued shares x PER}

You need to pay attention to corporate financial results. Specifically, if you are forecasting operating profit upwards, it is worth calculating the theoretical stock price. The theory is to calculate the theoretical stock price and judge that if the current stock price is cheaper than that, it is a buy. The PER value varies depending on the field of the brand, so pay attention to the unit when referring to the quarterly report.

Stop order

[Stop order](https://www.sbisec.co.jp/ETGate/WPLETmgR001Control?OutSide=on&getFlg=on&burl=search_domestic&cat1=domestic&cat2=none&dir=", not to mention forex trading in kind. Remembering info & file = domestic_stoporder.html) is the basic of the basics. There are various ways to stop, but I think there are three types if you divide them very roughly.

  1. Stop loss order

The most basic. This is to minimize the spread of loss when the market price of the stock or credit open interest held is contrary to expectations.

After purchasing stocks, it is best to place an order with a stop loss order and specify the conditions for loss cut. I think this technique is essential for beginners as well as advanced users.

  1. Trend following

It is a stop price method that reads the sign that the stock price is likely to rise, places a stop order, and gets on the rise momentum. I will place an order to buy when it exceeds the set value. This is useful when you want to control stocks that have an upward trend.

  1. Profit taking

It is a stop order that automatically sells when the stock price reaches a certain level and confirms the profit. This is also easy to understand.

If you actually make an investment like this, it is highly recommended to master the stop price. In particular, it is very important to prevent the spread of loss in 1. It is no exaggeration to say that becoming a full-fledged investor is only possible if you can cut losses firmly.

Even if you have an unrealized loss, the loss may not be fixed until you sell it, but there is no doubt that it is a bad move to keep the unrealized loss. If you are going to invest, you can rest assured that you will not lose a lot of money if you first decide the rules and start with what percentage of the loss cut.

Summary

In order to grasp the trends of other companies, it is important to first learn basic knowledge about stocks, which can be said to be an indicator of corporate performance, which is the basis.

Knowing the basic mechanism of the economy and analyzing it from various angles will lead to further thinking and consideration.

Recommended Posts

Analyze stocks to understand a company's performance
A way to understand Python duck typing
Use a cool graph to analyze PES data!
A memo to visually understand the axis of pandas.Panel
I started to analyze
[Introduction to Tensorflow] Understand Tensorflow properly and try to make a model