The stock is valued by DCF model

Keywords: Python Algorithm

The value of a stock is equal to the discounted value of its future cash flow.
——Stock market rules

1, Foreword

DCF(Discounted Cash Flow) is the abbreviation of discounted cash flow method, which can evaluate stocks. At present, most stock API s on the Internet only provide simple daily quotes, which is far from enough for analyzing the fundamentals of stocks. Therefore, this paper uses Tushare's stock interface, which provides detailed financial data (income statement, balance sheet, cash flow statement, etc.) in addition to the commonly used daily / weekly quotes.
Tushare registration link https://tushare.pro/register?reg=458932

2, Encapsulate TushareAPI

  1. To call TushareAPI, you need to pass in four parameters, namely api_name,token,params,fields:
  • api_name is the name of the API to call
  • The token is obtained after registering Tushare and can be found in the personal home page
  • params generally only needs to pass in the stock code as a parameter, and can also obtain the data of a specified date or period with the date.
  • Fields is used to specify the data to be obtained for the same api_name often contains a lot of data, so you can obtain the specified data by specifying fields.
  1. For the valuation of a stock, the stock codes in token and params are fixed, so it is not necessary to pass them into the encapsulated function. At the same time, in order to facilitate modification, set global variables to save these two parameters. Therefore, only api needs to be passed into the encapsulated api_name and fields.
  • Define global variables
token = XXXXX # Replace this with your token
code = '000651.SZ' # Stock code, such as 000651.SZ, is the stock code of Gree company
  • The encapsulation function code is as follows:
def stock_api(api_name, fields, period=''):
    """Get the specified data of the stock"""
    payload = {
    'api_name': api_name,
    'token': token,
    'params': {'ts_code': code},
    'fields': fields
    }
    res = requests.post(url,json.dumps(payload))  # Convert python objects to json strings
    text = json.loads(res.text)  # Convert json string to python object
    value = text['data']['items'][0]
    return value

3, Determine the parameters to be used for valuation

  1. Obtain the price of shares and the total circulating share capital
    Price and total share capital Daily indicators The calling code is as follows
price,number_of_shares = stock_api('daily_basic', 'close,float_share')
  1. Free cash flow from last year
    Free cash flow (FCF), FCF is located in Cash flow statement In, the name get is defined here_ last_year_fcf function is used to obtain the free cash flow in last year's annual report and define the variable last_year_fcf saves cash flow, unit (10000 yuan). The code is as follows:
# Judge the current year and obtain the free cash flow of last year's financial report
def get_last_year_fcf():
    year = time.strftime("%Y", time.localtime())
    last_year = int(year) - 1
    period = str(last_year) + "1231"
    last_year_fcf = stock_api('cashflow', 'free_cashflow', period)[0]
    last_year_fcf /= 10000 # Yuan to 10000 yuan
    return last_year_fcf
last_year_fcf = get_last_year_fcf()
  1. Discount rate R
    The discount rate is usually taken as 10% ~ 15%. For cyclical industries and risk companies, the discount rate should be increased, but this does not apply to each stock. The situation of each company is different. In order to simplify the valuation process, the empirical value is taken as 10.5%. A special article will be written later to introduce how to obtain a more reasonable discount rate through the formula.
    Note: the smaller the discount rate, the higher the valuation.
  2. Growth rate of perpetual annuity g
    The growth rate of perpetual annuity is usually replaced by the 10-year average GDP growth rate, which can be obtained from this https://cn.investing.com/rates-bonds/china-government-bonds Check, 2.889% when writing articles
    Note: the larger the g, the higher the valuation.
  3. Ten year average free cash flow growth rate fcf_growth_rate
    This data needs more data. The detailed calculation process will be calculated separately in the future. Here, 5% is taken directly.

4, Valuation algorithm

  1. Forecast ten-year free cash flow
    The first n n Calculation formula of free cash flow in n years
    F C F n = L Y F C F ∗ ( 1 + R ) n FCF_n=LYFCF*(1+R)^n FCFn​=LYFCF∗(1+R)n
    among F C F n FCFn FCFn is the free cash flow in year n, L Y F C F LYFCF LYFCF is the free cash flow of last year
fcf_item = last_year_fcf
fcf_list = [] # Ten year cash flow
fcf_list = [last_year_fcf*(1+fcf_growth_rate)**x for x in range(1,11)]
y10_fcf = fcf_list[9] # Preserve free cash flow for year 10
  1. Ten year converted cash flow
    Present discounted value (PDV)
    The first n n Discount formula for n years:
    P D V F C F n = F C F n ( 1 + R ) n PDVFCF_n=\frac{FCF_n}{(1+R)^n} PDVFCFn​=(1+R)nFCFn​​
    Among them, P D V F C F n PDVFCF_n PDVFCFn # is the second n n Converted free cash flow in n years
pdv_fcf_list = [] # Ten year converted cash flow
pdv_fcf_sum = 0 # Sum of ten-year converted cash flows
for index in range(0,10):
    pdv_fcf_item = fcf_list[index]/(1+R)**(index+1)
    pdv_fcf_list.append(pdv_fcf_item)
    pdv_fcf_sum += pdv_fcf_item
  1. Value of perpetual annuity pv
    Perpetual annuity value (PV)
    The first n n Calculation formula of n-year perpetual annuity:
    F C F n ∗ ( 1 + g ) R − g \frac{FCF_n*(1+g)}{R-g} R−gFCFn​∗(1+g)​
    Calculate pv in the 10th year
pv = y10_fcf*(1+g)/(R-g)
  1. Calculate the discounted perpetual annuity value pv_pdv
pv_pdv = pv/(1+R)**10
  1. Owner's equity_ equity
    Total owner's equity = sum of converted value of perpetual annuity + 10-year converted cash flow
owner_equity = pv_pdv + pdv_fcf_sum
  1. Value per share
    Value per share = total owner's equity / number of shares. Any valuation may be risky, so it will increase the reduction of the safety margin by 20%.
# Keep two decimal places and output the valuation results
estimate_value = format(owner_equity/number_of_shares, '.2f')
print("Valuation:", format(estimate_value, '.2f'), "element")
value20p = estimate_value * 0.80
print("20%Safety margin of:", format(value20p, '.2f'), "element")

Reference link

Tushare registration link https://tushare.pro/register?reg=458932
Tushare official website https://tushare.pro/
GDP growth rate https://cn.investing.com/rates-bonds/china-government-bonds

Posted by RogerInHawaii on Sat, 23 Oct 2021 20:48:00 -0700