python期权价格计算器_使用Python构建内在价值计算器
python期權(quán)價(jià)格計(jì)算器
The following passages shortly describe how to build a Python program that can calculate the fair value of a company, using data from Yahoo Finance. Before jumping into the Python technicalities, it makes sense to have a quick look at the factors that impact the fair value of a company.
噸他下面的段落簡短描述了如何構(gòu)建一個(gè)Python程序,可以計(jì)算出公司的合理價(jià)值,利用雅虎財(cái)經(jīng)的數(shù)據(jù)。 在開始使用Python技術(shù)之前,先快速了解影響公司公允價(jià)值的因素是有意義的。
一,理論背景 (I. Theoretical Background)
Financial theory posits that the fair value of a firm is equal to the sum of all future cash flows generated by the business, discounted using a risk-adjusted rate. In other words the current value of any company is equal to the cash that the company will generate, adjusted to account for the risk-profile of that company. This essentially boils down to the following equation:
財(cái)務(wù)理論認(rèn)為,企業(yè)的公允價(jià)值等于該企業(yè)產(chǎn)生的所有未來現(xiàn)金流量的總和,并使用風(fēng)險(xiǎn)調(diào)整率對其進(jìn)行折現(xiàn)。 換句話說,任何公司的現(xiàn)值等于該公司將產(chǎn)生的現(xiàn)金,并經(jīng)過調(diào)整以考慮該公司的風(fēng)險(xiǎn)狀況。 這實(shí)質(zhì)上可以歸結(jié)為以下等式:
where PV is the present value of the company, FCF are the free cash flows generated in year i, and r is the risk-adjusted discount rate. As it gets difficult to forecast cash flows with any reasonable degree of accuracy for more than 5 years into the future, it makes sense to calculate a terminal company value after this time span. Here, we can treat the company as a growing perpetuity, which can be valued with the following formula:
其中PV是公司的現(xiàn)值,FCF是第i年產(chǎn)生的自由現(xiàn)金流量,而r是風(fēng)險(xiǎn)調(diào)整后的折現(xiàn)率。 由于未來5年以上很難以任何合理的準(zhǔn)確度預(yù)測現(xiàn)金流量,因此在此時(shí)間段之后計(jì)算終端公司的價(jià)值是有意義的。 在這里,我們可以將公司視為永續(xù)經(jīng)營,可以通過以下公式對其進(jìn)行估值:
where FCF are the free cash flows generated by the company in year 6, r is the discount rate, and g is the long-term growth rate of the company. This terminal value of the company also needs to be discounted subsequently to get its present value.
其中FCF是公司在第6年產(chǎn)生的自由現(xiàn)金流量,r是折現(xiàn)率,g是公司的長期增長率。 公司的最終價(jià)值也需要隨后折價(jià)才能獲得其現(xiàn)值。
二。 金融理論的涵義 (II. Implications of Financial Theory)
To get a general structure for the Python program, we can basically just take the PV formula from above and split it into its main components.
要獲得Python程序的一般結(jié)構(gòu),我們基本上可以僅從上方獲取PV公式并將其拆分為其主要組成部分。
II.1自由現(xiàn)金流量 (II.1 Free Cash Flows)
The free cash flows generated by the company in year i are usually calculated by taking the cash flows generated by the firm’s operations and deducting capital expenditures. The resulting number is the amount of cash that debt and equity holders of the business could take out of the company in year i. Forecasting these cash flows can get pretty complicated and you usually need to build extensive Excel models to get to a reasonable estimate for these values. It is possible to get around this by using several (over)simplifying assumptions, which are outlined in a bit.
公司在第一年產(chǎn)生的自由現(xiàn)金流量通常是通過計(jì)算公司運(yùn)營產(chǎn)生的現(xiàn)金流量并減去資本支出來計(jì)算的。 結(jié)果數(shù)字是該業(yè)務(wù)的債務(wù)和股權(quán)持有人在第一年可以從公司中提取的現(xiàn)金量。 預(yù)測這些現(xiàn)金流量可能會(huì)變得非常復(fù)雜,通常需要構(gòu)建廣泛的Excel模型以對這些值進(jìn)行合理的估算。 可以通過使用幾個(gè)(過度)簡化的假設(shè)來解決此問題,這些假設(shè)在下文中進(jìn)行了概述。
II.2折現(xiàn)率 (II.2 Discount Rate)
The second major component that is needed to calculate the enterprise value of a company is an adequate risk-adjusted discount rate. The appropriate rate to use here is the weighted average cost of capital (WACC), which is the average cost of capital to the firm (that is for both debt and equity financing combined). The formula looks as follows:
計(jì)算公司的企業(yè)價(jià)值所需的第二個(gè)主要組成部分是適當(dāng)?shù)娘L(fēng)險(xiǎn)調(diào)整后的折現(xiàn)率。 此處使用的適當(dāng)比率是加權(quán)平均資本成本(WACC),即公司的平均資本成本(即債務(wù)和股權(quán)融資的總和)。 該公式如下所示:
where E is the market value of the company’s equity, D is the value of the company’s debt, r denotes the return required by equity and debt holders, respectively, and tau denotes the company’s tax rate.
其中E是公司股權(quán)的市場價(jià)值,D是公司債務(wù)的價(jià)值,r分別表示權(quán)益和債務(wù)持有人所需的收益,tau表示公司的稅率。
II.3簡化假設(shè) (II.3 Simplifying Assumptions)
As mentioned earlier, getting these two major components can take weeks of calculations and model building. As this is more of a sparing exercise, rather than a full-blown quant project, several simplifying assumptions are made to keep the complexity of the program to a reasonable level.
如前所述,獲得這兩個(gè)主要組成部分可能需要數(shù)周的計(jì)算和模型構(gòu)建。 由于這只是一個(gè)有限的練習(xí),而不是一個(gè)成熟的量化項(xiàng)目,因此,我們進(jìn)行了一些簡化的假設(shè),以將程序的復(fù)雜性保持在合理的水平。
Firstly, the task of obtaining future free cash flows can be simplified by assuming the company earnings before interest and taxes (EBIT) are an adequate proxy for free cash flows generated by a company. This is reasonable especially for companies in later stages that no longer have large growth CapEx but rather maintenance CapEx that is approximately on the level of the company’s depreciation of fixed assets.
首先,假設(shè)公司的息稅前利潤(EBIT)足以代替公司產(chǎn)生的自由現(xiàn)金流,可以簡化獲取未來自由現(xiàn)金流的任務(wù)。 這對于那些不再具有較大增長資本支出,但維持資本支出大約與公司固定資產(chǎn)折舊水平相當(dāng)?shù)墓径?#xff0c;是合理的。
Secondly, we will assume that the average revenue growth rate and the average EBIT margin of the company in the past three years will continue to apply for the next five years. Using this approach, generating EBIT forecasts is pretty straightforward.
其次,我們假設(shè)過去三年中公司的平均收入增長率和平均息稅前利潤率將在未來五年中繼續(xù)適用。 使用這種方法,生成EBIT預(yù)測非常簡單。
Finally, to calculate the WACC, we will assume that company debt is adequately priced by the market, making the yield on outstanding debt the return required by debt holders. Calculating the required equity return is a bit more tricky. Here the capital asset pricing model (CAPM) is used to get to the equity rate of return:
最后,為了計(jì)算WACC,我們將假定公司債務(wù)已由市場充分定價(jià),從而使未償債務(wù)的收益成為債務(wù)持有人所需的回報(bào)。 計(jì)算所需的股本回報(bào)會(huì)比較棘手。 在這里,資本資產(chǎn)定價(jià)模型(CAPM)用于獲得股本收益率:
where the equity beta is essentially the co-movement of the stock return and the general market return, which can be proxied using the S&P500. The equity beta is calculated as the covariance of stock and market returns divided by the variance of the market returns.
其中,權(quán)益beta實(shí)質(zhì)上是股票收益和一般市場收益的共同變動(dòng),可以使用S&P500進(jìn)行代理。 權(quán)益beta的計(jì)算方法是:股票和市場收益的協(xié)方差除以市場收益的方差。
三, 用Python實(shí)現(xiàn) (III. Implementation with Python)
I used Apple Inc. (AAPL) as the company being valued in the subsequent code, however, the program works with the ticker of any large publicly traded company.
我使用Apple Inc.(AAPL)作為后續(xù)代碼中被評估的公司,但是,該程序可與任何大型上市公司的股票一起使用。
For the program to work, several modules need to be imported to pull financial information from Yahoo Finance and store it appropriately.
為了使程序正常運(yùn)行,需要導(dǎo)入幾個(gè)模塊以從Yahoo Finance中提取財(cái)務(wù)信息并適當(dāng)?shù)卮鎯λ?
from bs4 import BeautifulSoup as bsimport pandas as pd
import requests
import pandas_datareader as dr
import datetime
As discussed subsequently, certain values that are tedious to obtain or simply not available via Yahoo Finance are hard coded initially.
如隨后討論的那樣,最初很難對某些難以獲得或根本無法通過Yahoo Finance獲得的值進(jìn)行編碼。
company_ticker = 'AAPL'timespan = 100 #timespan for the equity beta calculation
market_risk_premium = 0.0523
long_term_growth = 0.01
debt_return = 0.01
tax_rate = 0.3
III.1從Yahoo Finance提取財(cái)務(wù)數(shù)據(jù) (III.1 Pulling Financial Data from Yahoo Finance)
Yahoo Finance has an API that provides a lot of information, however, web-scraping is needed on top to get the specific income statement and balance sheet financials. For this, BeautifulSoup and the requests module are great tools.
Yahoo Finance有一個(gè)提供大量信息的API,但是,首先需要進(jìn)行網(wǎng)絡(luò)爬網(wǎng)以獲得特定的損益表和資產(chǎn)負(fù)債表財(cái)務(wù)狀況。 為此,BeautifulSoup和請求模塊是出色的工具。
income_statement_url = '<https://finance.yahoo.com/quote/>' + company_ticker + '/financials?p=' + company_tickerincome_statement_html = requests.get(income_statement_url)income_statement_soup = bs(income_statement_html.text, 'html.parser')
After creating the BeautifulSoup object, we have to navigate the website to get the correct pieces of information and store them in one pandas dataframe that contains the required information. To that end, we first create a dataframe with the correct dates as column names.
創(chuàng)建BeautifulSoup對象后,我們必須瀏覽網(wǎng)站以獲取正確的信息并將其存儲在包含所需信息的一個(gè)熊貓數(shù)據(jù)框中。 為此,我們首先創(chuàng)建一個(gè)以正確日期作為列名的數(shù)據(jù)框。
income_statement_table = income_statement_soup.find('div', class_='M(0) Whs(n) BdEnd Bdc($seperatorColor) D(itb)')income_statement_header = income_statement_table.find('div', class_='D(tbr) C($primaryColor)')
header_lst = []
for i in income_statement_header.find_all('div'):
if len(i) != 0:
header_lst.append(i.text)
header_lst = header_lst[::-1]
del header_lst[len(header_lst)-1]
header_lst.insert(0,'Breakdown')
income_statement_df = pd.DataFrame(columns = header_lst)
After that, the revenue and EBIT figures provided by Yahoo Finance can be appended for the respective year.
之后,可以附加相應(yīng)年份的Yahoo Finance提供的收入和EBIT數(shù)據(jù)。
revenue_row = income_statement_table.find('div', class_='D(tbr) fi-row Bgc($hoverBgColor):h')revenue_lst = []
for i in revenue_row.find_all('div', attrs={'data-test':'fin-col'}):
i = i.text
i = i.replace(",","")
revenue_lst.append(int(i))
revenue_lst = revenue_lst[::-1]
revenue_lst.insert(0,'Total Revenue')
income_statement_df.loc[0] = revenue_lstEBIT_row = income_statement_table.find('div', attrs={'title':'EBIT'}).parent.parent
EBIT_lst = []
for i in EBIT_row.find_all('div', attrs={'data-test':'fin-col'}):
i = i.text
i = i.replace(",","")
EBIT_lst.append(int(i))
EBIT_lst = EBIT_lst[::-1]
EBIT_lst.insert(0,'EBIT')
income_statement_df.loc[1] = EBIT_lstincome_statement_df = income_statement_df.drop('ttm', axis=1)
When exporting the Pandas dataframe to a csv-file, we get the following:
將Pandas數(shù)據(jù)框?qū)С龅絚sv文件時(shí),我們得到以下信息:
III.2預(yù)測收入和息稅前利潤 (III.2 Forecasting Revenues and EBIT)
As mentioned earlier, revenues and EBIT are forecasted for the coming five years by extrapolating from past sales and EBIT data. To do this, we calculate the revenue compound annual growth rate (CAGR) and EBIT margin for the past years.
如前所述,根據(jù)過去的銷售和EBIT數(shù)據(jù)推斷出未來五年的收入和EBIT。 為此,我們計(jì)算了過去幾年的收入復(fù)合年增長率(CAGR)和EBIT利潤率。
latest_rev = income_statement_df.iloc[0,len(income_statement_df.columns)-1]earliest_rev = income_statement_df.iloc[0,1]
rev_CAGR = (latest_rev/earliest_rev)**(float(1/(len(income_statement_df.columns)-2)))-1EBIT_margin_lst = []
for year in range(1,len(income_statement_df.columns)):
EBIT_margin = income_statement_df.iloc[1,year]/income_statement_df.iloc[0,year]
EBIT_margin_lst.append(EBIT_margin)
avg_EBIT_margin = sum(EBIT_margin_lst)/len(EBIT_margin_lst)
Using these figures, it is possible to forecast revenues and EBIT.
使用這些數(shù)字,可以預(yù)測收入和息稅前收益。
forecast_df = pd.DataFrame(columns=['Year ' + str(i) for i in range(1,7)])rev_forecast_lst = []for i in range(1,7):
if i != 6:
rev_forecast = latest_rev*(1+rev_CAGR)**i
else:
rev_forecast = latest_rev*(1+rev_CAGR)**(i-1)*(1+long_term_growth)
rev_forecast_lst.append(int(rev_forecast))
forecast_df.loc[0] = rev_forecast_lstEBIT_forecast_lst = []
for i in range(0,6):
EBIT_forecast = rev_forecast_lst[i]*avg_EBIT_margin
EBIT_forecast_lst.append(int(EBIT_forecast))
forecast_df.loc[1] = EBIT_forecast_lst
The resulting csv file of the forecast dataframe looks as follows, where the rows indexed as 0 and 1 provide the forecasted revenue and EBIT figures, respectively.
預(yù)測數(shù)據(jù)幀的結(jié)果csv文件如下所示,其中索引為0和1的行分別提供了預(yù)測收入和EBIT數(shù)字。
III.3計(jì)算WACC (III.3 Calculating the WACC)
To calculate the WACC, we first need to find the rate of return demanded by equity holders. This requires finding the risk-free rate (proxied here by the yield of the 10-year US Treasury note) and determining the market risk premium.
要計(jì)算WACC,我們首先需要找到股權(quán)持有人要求的回報(bào)率。 這要求找到無風(fēng)險(xiǎn)利率(此處附有10年期美國國庫券的收益率)并確定市場風(fēng)險(xiǎn)溢價(jià)。
Determining the risk-free rate is relatively straightforward, as we only need the current yield on the 10-year US treasury note.
確定無風(fēng)險(xiǎn)利率相對簡單,因?yàn)槲覀冎恍枰?0年期美國國債的當(dāng)前收益率即可。
current_date = datetime.date.today()past_date = current_date-datetime.timedelta(days=timespan)risk_free_rate_df = dr.DataReader('^TNX', 'yahoo', past_date, current_date)
risk_free_rate_float = (risk_free_rate_df.iloc[len(risk_free_rate_df)-1,5])/100
Instead of calculating an adequate estimate of the market risk premium myself, I used the rate provided by NYU finance professor Aswath Damodaran, who also publishes a lot of other very interesting financial statistics. Currently he estimates the market premium to be 5.23% annually for the US market.
我沒有自己計(jì)算出足夠的市場風(fēng)險(xiǎn)溢價(jià)估算,而是使用紐約大學(xué)金融學(xué)教授阿斯瓦斯·達(dá)莫達(dá)蘭 ( Aswath Damodaran)提供的費(fèi)率,他還發(fā)布了許多其他非常有趣的金融統(tǒng)計(jì)數(shù)據(jù)。 目前,他估計(jì)美國市場的市場溢價(jià)每年為5.23%。
Calculating the equity beta of the company requires several inputs. First, we have to access the API of Yahoo Finance to get price information on the company stock and the market. These prices are stored in a pandas dataframe and the values are used to calculate daily returns for both sets of prices. Subsequently, the covariance of the stock and the market returns is divided by the variance of the market returns.
計(jì)算公司的權(quán)益貝塔系數(shù)需要幾個(gè)輸入。 首先,我們必須訪問Yahoo Finance的API,以獲取有關(guān)公司股票和市場的價(jià)格信息。 這些價(jià)格存儲在熊貓數(shù)據(jù)框中,并且這些值用于計(jì)算兩組價(jià)格的每日收益。 隨后,將股票和市場收益的協(xié)方差除以市場收益的方差。
price_information_df = pd.DataFrame(columns=['Stock Prices', 'Market Prices'])stock_price_df = dr.DataReader(company_ticker, 'yahoo', past_date, current_date)price_information_df['Stock Prices'] = stock_price_df['Adj Close']market_price_df = dr.DataReader('^GSPC', 'yahoo', past_date, current_date)
price_information_df['Market Prices'] = market_price_df['Adj Close']returns_information_df = pd.DataFrame(columns =['Stock Returns', 'Market Returns'])stock_return_lst = []
for i in range(1,len(price_information_df)):
open_price = price_information_df.iloc[i-1,0]
close_price = price_information_df.iloc[i,0]
stock_return = (close_price-open_price)/open_price
stock_return_lst.append(stock_return)
returns_information_df['Stock Returns'] = stock_return_lstmarket_return_lst = []
for i in range(1,len(price_information_df)):
open_price = price_information_df.iloc[i-1,1]
close_price = price_information_df.iloc[i,1]
market_return = (close_price-open_price)/open_price
market_return_lst.append(market_return)
returns_information_df['Market Returns'] = market_return_lstcovariance_df = returns_information_df.cov()
covariance_float = covariance_df.iloc[1,0]
variance_df = returns_information_df.var()
market_variance_float = variance_df.iloc[1]equity_beta = covariance_float/market_variance_float
equity_return = risk_free_rate_float+equity_beta*(market_risk_premium)
Pulling bond information from the internet is more difficult than it is for equities, which is why we can simply look up bond yields and hardcode them manually. Apple is AA+ rated by S&P, which is why yields on the company’s outstanding bonds are relatively low, at around 1%.
從互聯(lián)網(wǎng)上獲取債券信息比股票要困難得多,這就是為什么我們可以簡單地查詢債券收益率并手動(dòng)對其進(jìn)行硬編碼的原因。 蘋果被標(biāo)準(zhǔn)普爾(S&P)評為AA +級,這就是為什么該公司未償還債券的收益率相對較低,約為1%。
Finally, to calculate the WACC, we need pull the amount of company net debt outstanding and the market value of the firm’s equity from Yahoo Finance.
最后,要計(jì)算WACC,我們需要從Yahoo Finance中提取公司的未償債務(wù)凈額和公司股權(quán)的市值。
balance_sheet_url = '<https://finance.yahoo.com/quote/>' + company_ticker + '/balance-sheet?p=' + company_tickerbalance_sheet_html = requests.get(balance_sheet_url)balance_sheet_soup = bs(balance_sheet_html.text, 'html.parser')balance_sheet_table = balance_sheet_soup.find('div', class_='D(tbrg)')net_debt_lst = []net_debt_row = balance_sheet_table.find('div', attrs={'title':'Net Debt'}).parent.parent
for value in net_debt_row.find_all('div'):
value = value.text
value = value.replace(',','')
net_debt_lst.append(value)
net_debt_int = int(net_debt_lst[3])market_cap_url = '<https://finance.yahoo.com/quote/>' + company_ticker + '?p=' + company_ticker
market_cap_html = requests.get(market_cap_url)
market_cap_soup = bs(market_cap_html.text, 'html.parser')market_cap_int = 0market_cap_row = market_cap_soup.find('td', attrs={'data-test':'MARKET_CAP-value'})
market_cap_str = market_cap_row.text
market_cap_lst = market_cap_str.split('.')if market_cap_str[len(market_cap_str)-1] == 'T':
market_cap_length = len(market_cap_lst[1])-1
market_cap_lst[1] = market_cap_lst[1].replace('T',(9-market_cap_length)*'0')
market_cap_int = int(''.join(market_cap_lst))if market_cap_str[len(market_cap_str)-1] == 'B':
market_cap_length = len(market_cap_lst[1])-1
market_cap_lst[1] = market_cap_lst[1].replace('B',(6-market_cap_length)*'0')
market_cap_int = int(''.join(market_cap_lst))company_value = market_cap_int + net_debt_intWACC = market_cap_int/company_value * equity_return + net_debt_int/company_value * debt_return * (1-tax_rate)
III.4現(xiàn)金流量折現(xiàn) (III.4 Discounting the Cash Flows)
Finally, we need to discount all the cash flows to get the present value and the overall enterprise value of the company. First, the forecasted EBIT (i.e. FCF) for the next five years are discounted and the present value of the terminal value of the company is added to this amount.
最后,我們需要對所有現(xiàn)金流量進(jìn)行折現(xiàn)以獲得公司的現(xiàn)值和整體企業(yè)價(jià)值。 首先,對未來五年的預(yù)測EBIT(即FCF)進(jìn)行折現(xiàn),然后將公司最終價(jià)值的現(xiàn)值添加到該金額中。
As the resulting value gives us the enterprise value of the company, which is the value to both equity and debt holders, we need to deduct the company’s net debt to arrive at the equity value of the firm.
由于最終的價(jià)值使我們獲得了公司的企業(yè)價(jià)值,即對股權(quán)和債務(wù)持有人的價(jià)值,因此我們需要扣除公司的凈債務(wù)以得出公司的股權(quán)價(jià)值。
discounted_EBIT_lst = []for year in range(0,5):discounted_EBIT = forecast_df.iloc[1,year]/(1+WACC)**(year+1)
discounted_EBIT_lst.append(int(discounted_EBIT))terminal_value = forecast_df.iloc[1,5]/(WACC-long_term_growth)
PV_terminal_value = int(terminal_value/(1+WACC)**5)enterprise_value = sum(discounted_EBIT_lst)+PV_terminal_value
equity_value = enterprise_value-net_debt_int
IV。 模型表現(xiàn) (IV. Model Performance)
Just to get a feeling for whether or not the program is performing somewhat accurately, I calculated intrinsic values for large US stocks and compared the valuations with the market caps of the respective companies. As stock in the companies chosen is heavily traded, great discrepancies between intrinsic and market value are unlikely, which is why market prices should provide a good indication of the actual value of the companies.
只是為了了解程序是否執(zhí)行得有些準(zhǔn)確,我計(jì)算了美國大型股票的內(nèi)在價(jià)值,并將估值與各自公司的市值進(jìn)行了比較。 由于所選公司的股票交易量很大,因此內(nèi)在價(jià)值和市場價(jià)值之間的巨大差異不太可能出現(xiàn),這就是為什么市場價(jià)格應(yīng)能很好地表明公司的實(shí)際價(jià)值。
Model performance compared to company market cap, all values in thousands.模型性能與公司市值相比,所有價(jià)值都在數(shù)千。As can be seen, the model does a reasonably good job for certain companies, while its quite off for others. The two main issues at play here are firstly that the somewhat questionable assumptions on which the model is built are simply unreasonable for certain companies. Secondly, the model output is highly sensitive to the WACC input data due to the approach used to calculate the terminal company value. A more appropriate approach would be to apply an EBIT or EBITDA multiple based on comparable companies, as this entails a lower sensitivity of the program output to the WACC and the terminal growth rate.
可以看出,該模型對于某些公司而言做得相當(dāng)不錯(cuò),而對其他公司而言則相當(dāng)不理想。 這里發(fā)揮的兩個(gè)主要問題是,首先,對于某些公司而言,建立模型所基于的有點(diǎn)可疑的假設(shè)是完全不合理的。 其次,由于用于計(jì)算終端公司價(jià)值的方法,模型輸出對WACC輸入數(shù)據(jù)高度敏感。 一種更合適的方法是在可比公司的基礎(chǔ)上應(yīng)用EBIT或EBITDA倍數(shù),因?yàn)檫@會(huì)使程序輸出對WACC和最終增長率的敏感性降低。
五,結(jié)語 (V. Concluding Remarks)
Obviously, the program described above is a simplified approach to valuation and is unlikely to be accurate if the underlying assumptions are violated. Still, the tool might be useful in determining the aggregate intrinsic value of a large number of companies.
顯然,上述程序是一種簡化的估值方法,如果違反了基本假設(shè),則該程序就不太可能是準(zhǔn)確的。 盡管如此,該工具在確定大量公司的總內(nèi)在價(jià)值時(shí)可能還是有用的。
V.1免責(zé)聲明 (V.1 Disclaimer)
The code above is only a side-project and should not be used to make investment decisions. Further, the information pulled from Yahoo Finance should not be used for any commercial purposes. As mentioned earlier, the program is simply a fun exercise of applying Python programming to finance and I recommend against employing web-scraping if resulting information is to be used for commercial purposes.
上面的代碼僅是一個(gè)附屬項(xiàng)目,不應(yīng)用于做出投資決策。 此外,從Yahoo Finance提取的信息不得用于任何商業(yè)目的。 如前所述,該程序只是將Python編程應(yīng)用于金融的一項(xiàng)有趣的練習(xí),如果將所得信息用于商業(yè)目的,我建議不要使用網(wǎng)絡(luò)抓取。
V.2最終代碼 (V.2 Final Code)
The final code looks as follows. In order to run it, you will have to install Python (I use version 3.7.8.) and pip install BeautifulSoup, pandas, requests, and pandas-datareader.
最終代碼如下所示。 為了運(yùn)行它,您將必須安裝Python(我使用版本3.7.8。)并pip安裝BeautifulSoup,pandas,requests和pandas-datareader。
from bs4 import BeautifulSoup as bsimport pandas as pd
import requests
import pandas_datareader as dr
import datetime'''---------- // Hard-coded variables below // ----------'''
company_ticker = 'AAPL'
timespan = 100 #timespan for the equity beta calculation
market_risk_premium = 0.0523
long_term_growth = 0.01
debt_return = 0.01
tax_rate = 0.3
'''---------- // Hard-coded variables above // ----------''''''----- // I. Financial Information from Yahoo Finance // -----'''
income_statement_url = '<https://finance.yahoo.com/quote/>' + company_ticker + '/financials?p=' + company_ticker
income_statement_html = requests.get(income_statement_url)
income_statement_soup = bs(income_statement_html.text, 'html.parser')
income_statement_table = income_statement_soup.find('div', class_='M(0) Whs(n) BdEnd Bdc($seperatorColor) D(itb)')
income_statement_header = income_statement_table.find('div', class_='D(tbr) C($primaryColor)')
header_lst = []
for i in income_statement_header.find_all('div'):
if len(i) != 0:
header_lst.append(i.text)
header_lst = header_lst[::-1]
del header_lst[len(header_lst)-1]
header_lst.insert(0,'Breakdown')
income_statement_df = pd.DataFrame(columns = header_lst)
revenue_row = income_statement_table.find('div', class_='D(tbr) fi-row Bgc($hoverBgColor):h')
revenue_lst = []
for i in revenue_row.find_all('div', attrs={'data-test':'fin-col'}):
i = i.text
i = i.replace(",","")
revenue_lst.append(int(i))
revenue_lst = revenue_lst[::-1]
revenue_lst.insert(0,'Total Revenue')
income_statement_df.loc[0] = revenue_lst
EBIT_row = income_statement_table.find('div', attrs={'title':'EBIT'}).parent.parent
EBIT_lst = []
for i in EBIT_row.find_all('div', attrs={'data-test':'fin-col'}):
i = i.text
i = i.replace(",","")
EBIT_lst.append(int(i))
EBIT_lst = EBIT_lst[::-1]
EBIT_lst.insert(0,'EBIT')
income_statement_df.loc[1] = EBIT_lst
income_statement_df = income_statement_df.drop('ttm', axis=1)'''---------- // II. Forecasting Revenues and EBIT // ----------'''
latest_rev = income_statement_df.iloc[0,len(income_statement_df.columns)-1]
earliest_rev = income_statement_df.iloc[0,1]
rev_CAGR = (latest_rev/earliest_rev)**(float(1/(len(income_statement_df.columns)-2)))-1
EBIT_margin_lst = []
for year in range(1,len(income_statement_df.columns)):
EBIT_margin = income_statement_df.iloc[1,year]/income_statement_df.iloc[0,year]
EBIT_margin_lst.append(EBIT_margin)
avg_EBIT_margin = sum(EBIT_margin_lst)/len(EBIT_margin_lst)
forecast_df = pd.DataFrame(columns=['Year ' + str(i) for i in range(1,7)])
rev_forecast_lst = []
for i in range(1,7):
if i != 6:
rev_forecast = latest_rev*(1+rev_CAGR)**i
else:
rev_forecast = latest_rev*(1+rev_CAGR)**(i-1)*(1+long_term_growth)
rev_forecast_lst.append(int(rev_forecast))
forecast_df.loc[0] = rev_forecast_lst
EBIT_forecast_lst = []
for i in range(0,6):
EBIT_forecast = rev_forecast_lst[i]*avg_EBIT_margin
EBIT_forecast_lst.append(int(EBIT_forecast))
forecast_df.loc[1] = EBIT_forecast_lst
'''---------- // III. Calculating the WACC // ----------'''
current_date = datetime.date.today()
past_date = current_date-datetime.timedelta(days=timespan)
risk_free_rate_df = dr.DataReader('^TNX', 'yahoo', past_date, current_date)
risk_free_rate_float = (risk_free_rate_df.iloc[len(risk_free_rate_df)-1,5])/100
price_information_df = pd.DataFrame(columns=['Stock Prices', 'Market Prices'])
stock_price_df = dr.DataReader(company_ticker, 'yahoo', past_date, current_date)
price_information_df['Stock Prices'] = stock_price_df['Adj Close']
market_price_df = dr.DataReader('^GSPC', 'yahoo', past_date, current_date)
price_information_df['Market Prices'] = market_price_df['Adj Close']
returns_information_df = pd.DataFrame(columns =['Stock Returns', 'Market Returns'])
stock_return_lst = []
for i in range(1,len(price_information_df)):
open_price = price_information_df.iloc[i-1,0]
close_price = price_information_df.iloc[i,0]
stock_return = (close_price-open_price)/open_price
stock_return_lst.append(stock_return)
returns_information_df['Stock Returns'] = stock_return_lst
market_return_lst = []
for i in range(1,len(price_information_df)):
open_price = price_information_df.iloc[i-1,1]
close_price = price_information_df.iloc[i,1]
market_return = (close_price-open_price)/open_price
market_return_lst.append(market_return)
returns_information_df['Market Returns'] = market_return_lst
covariance_df = returns_information_df.cov()
covariance_float = covariance_df.iloc[1,0]
variance_df = returns_information_df.var()
market_variance_float = variance_df.iloc[1]
equity_beta = covariance_float/market_variance_float
equity_return = risk_free_rate_float+equity_beta*(market_risk_premium)
balance_sheet_url = '<https://finance.yahoo.com/quote/>' + company_ticker + '/balance-sheet?p=' + company_ticker
balance_sheet_html = requests.get(balance_sheet_url)
balance_sheet_soup = bs(balance_sheet_html.text, 'html.parser')
balance_sheet_table = balance_sheet_soup.find('div', class_='D(tbrg)')
net_debt_lst = []
net_debt_row = balance_sheet_table.find('div', attrs={'title':'Net Debt'}).parent.parent
for value in net_debt_row.find_all('div'):
value = value.text
value = value.replace(',','')
net_debt_lst.append(value)
net_debt_int = int(net_debt_lst[3])
market_cap_url = '<https://finance.yahoo.com/quote/>' + company_ticker + '?p=' + company_ticker
market_cap_html = requests.get(market_cap_url)
market_cap_soup = bs(market_cap_html.text, 'html.parser')
market_cap_int = 0
market_cap_row = market_cap_soup.find('td', attrs={'data-test':'MARKET_CAP-value'})
market_cap_str = market_cap_row.text
market_cap_lst = market_cap_str.split('.')
if market_cap_str[len(market_cap_str)-1] == 'T':
market_cap_length = len(market_cap_lst[1])-1
market_cap_lst[1] = market_cap_lst[1].replace('T',(9-market_cap_length)*'0')
market_cap_int = int(''.join(market_cap_lst))
if market_cap_str[len(market_cap_str)-1] == 'B':
market_cap_length = len(market_cap_lst[1])-1
market_cap_lst[1] = market_cap_lst[1].replace('B',(6-market_cap_length)*'0')
market_cap_int = int(''.join(market_cap_lst))
company_value = market_cap_int + net_debt_int
WACC = market_cap_int/company_value * equity_return + net_debt_int/company_value * debt_return * (1-tax_rate)
'''-------- // IV. Discounting the Forecasted EBIT // --------'''
discounted_EBIT_lst = []
for year in range(0,5):
discounted_EBIT = forecast_df.iloc[1,year]/(1+WACC)**(year+1)
discounted_EBIT_lst.append(int(discounted_EBIT))
terminal_value = forecast_df.iloc[1,5]/(WACC-long_term_growth)
PV_terminal_value = int(terminal_value/(1+WACC)**5)
enterprise_value = sum(discounted_EBIT_lst)+PV_terminal_value
equity_value = enterprise_value-net_debt_int
翻譯自: https://medium.com/analytics-vidhya/building-an-intrinsic-value-calculator-with-python-7986833962cd
python期權(quán)價(jià)格計(jì)算器
總結(jié)
以上是生活随笔為你收集整理的python期权价格计算器_使用Python构建内在价值计算器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: eclipse中svn从分支合并到主干及
- 下一篇: python实现同态滤波