python期权价格计算器_使用Python构建内在价值计算器
python期權價格計算器
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.
噸他下面的段落簡短描述了如何構建一個Python程序,可以計算出公司的合理價值,利用雅虎財經的數據。 在開始使用Python技術之前,先快速了解影響公司公允價值的因素是有意義的。
一,理論背景 (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:
財務理論認為,企業的公允價值等于該企業產生的所有未來現金流量的總和,并使用風險調整率對其進行折現。 換句話說,任何公司的現值等于該公司將產生的現金,并經過調整以考慮該公司的風險狀況。 這實質上可以歸結為以下等式:
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是公司的現值,FCF是第i年產生的自由現金流量,而r是風險調整后的折現率。 由于未來5年以上很難以任何合理的準確度預測現金流量,因此在此時間段之后計算終端公司的價值是有意義的。 在這里,我們可以將公司視為永續經營,可以通過以下公式對其進行估值:
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年產生的自由現金流量,r是折現率,g是公司的長期增長率。 公司的最終價值也需要隨后折價才能獲得其現值。
二。 金融理論的涵義 (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程序的一般結構,我們基本上可以僅從上方獲取PV公式并將其拆分為其主要組成部分。
II.1自由現金流量 (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.
公司在第一年產生的自由現金流量通常是通過計算公司運營產生的現金流量并減去資本支出來計算的。 結果數字是該業務的債務和股權持有人在第一年可以從公司中提取的現金量。 預測這些現金流量可能會變得非常復雜,通常需要構建廣泛的Excel模型以對這些值進行合理的估算。 可以通過使用幾個(過度)簡化的假設來解決此問題,這些假設在下文中進行了概述。
II.2折現率 (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:
計算公司的企業價值所需的第二個主要組成部分是適當的風險調整后的折現率。 此處使用的適當比率是加權平均資本成本(WACC),即公司的平均資本成本(即債務和股權融資的總和)。 該公式如下所示:
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是公司股權的市場價值,D是公司債務的價值,r分別表示權益和債務持有人所需的收益,tau表示公司的稅率。
II.3簡化假設 (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.
如前所述,獲得這兩個主要組成部分可能需要數周的計算和模型構建。 由于這只是一個有限的練習,而不是一個成熟的量化項目,因此,我們進行了一些簡化的假設,以將程序的復雜性保持在合理的水平。
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.
首先,假設公司的息稅前利潤(EBIT)足以代替公司產生的自由現金流,可以簡化獲取未來自由現金流的任務。 這對于那些不再具有較大增長資本支出,但維持資本支出大約與公司固定資產折舊水平相當的公司而言,是合理的。
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.
其次,我們假設過去三年中公司的平均收入增長率和平均息稅前利潤率將在未來五年中繼續適用。 使用這種方法,生成EBIT預測非常簡單。
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:
最后,為了計算WACC,我們將假定公司債務已由市場充分定價,從而使未償債務的收益成為債務持有人所需的回報。 計算所需的股本回報會比較棘手。 在這里,資本資產定價模型(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.
其中,權益beta實質上是股票收益和一般市場收益的共同變動,可以使用S&P500進行代理。 權益beta的計算方法是:股票和市場收益的協方差除以市場收益的方差。
三, 用Python實現 (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)作為后續代碼中被評估的公司,但是,該程序可與任何大型上市公司的股票一起使用。
For the program to work, several modules need to be imported to pull financial information from Yahoo Finance and store it appropriately.
為了使程序正常運行,需要導入幾個模塊以從Yahoo Finance中提取財務信息并適當地存儲它。
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獲得的值進行編碼。
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提取財務數據 (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有一個提供大量信息的API,但是,首先需要進行網絡爬網以獲得特定的損益表和資產負債表財務狀況。 為此,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.
創建BeautifulSoup對象后,我們必須瀏覽網站以獲取正確的信息并將其存儲在包含所需信息的一個熊貓數據框中。 為此,我們首先創建一個以正確日期作為列名的數據框。
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.
之后,可以附加相應年份的Yahoo Finance提供的收入和EBIT數據。
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數據框導出到csv文件時,我們得到以下信息:
III.2預測收入和息稅前利潤 (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.
如前所述,根據過去的銷售和EBIT數據推斷出未來五年的收入和EBIT。 為此,我們計算了過去幾年的收入復合年增長率(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.
使用這些數字,可以預測收入和息稅前收益。
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.
預測數據幀的結果csv文件如下所示,其中索引為0和1的行分別提供了預測收入和EBIT數字。
III.3計算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.
要計算WACC,我們首先需要找到股權持有人要求的回報率。 這要求找到無風險利率(此處附有10年期美國國庫券的收益率)并確定市場風險溢價。
Determining the risk-free rate is relatively straightforward, as we only need the current yield on the 10-year US treasury note.
確定無風險利率相對簡單,因為我們只需要10年期美國國債的當前收益率即可。
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.
我沒有自己計算出足夠的市場風險溢價估算,而是使用紐約大學金融學教授阿斯瓦斯·達莫達蘭 ( Aswath Damodaran)提供的費率,他還發布了許多其他非常有趣的金融統計數據。 目前,他估計美國市場的市場溢價每年為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.
計算公司的權益貝塔系數需要幾個輸入。 首先,我們必須訪問Yahoo Finance的API,以獲取有關公司股票和市場的價格信息。 這些價格存儲在熊貓數據框中,并且這些值用于計算兩組價格的每日收益。 隨后,將股票和市場收益的協方差除以市場收益的方差。
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%.
從互聯網上獲取債券信息比股票要困難得多,這就是為什么我們可以簡單地查詢債券收益率并手動對其進行硬編碼的原因。 蘋果被標準普爾(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.
最后,要計算WACC,我們需要從Yahoo Finance中提取公司的未償債務凈額和公司股權的市值。
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現金流量折現 (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.
最后,我們需要對所有現金流量進行折現以獲得公司的現值和整體企業價值。 首先,對未來五年的預測EBIT(即FCF)進行折現,然后將公司最終價值的現值添加到該金額中。
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.
由于最終的價值使我們獲得了公司的企業價值,即對股權和債務持有人的價值,因此我們需要扣除公司的凈債務以得出公司的股權價值。
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。 模型表現 (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.
只是為了了解程序是否執行得有些準確,我計算了美國大型股票的內在價值,并將估值與各自公司的市值進行了比較。 由于所選公司的股票交易量很大,因此內在價值和市場價值之間的巨大差異不太可能出現,這就是為什么市場價格應能很好地表明公司的實際價值。
Model performance compared to company market cap, all values in thousands.模型性能與公司市值相比,所有價值都在數千。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.
可以看出,該模型對于某些公司而言做得相當不錯,而對其他公司而言則相當不理想。 這里發揮的兩個主要問題是,首先,對于某些公司而言,建立模型所基于的有點可疑的假設是完全不合理的。 其次,由于用于計算終端公司價值的方法,模型輸出對WACC輸入數據高度敏感。 一種更合適的方法是在可比公司的基礎上應用EBIT或EBITDA倍數,因為這會使程序輸出對WACC和最終增長率的敏感性降低。
五,結語 (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.
顯然,上述程序是一種簡化的估值方法,如果違反了基本假設,則該程序就不太可能是準確的。 盡管如此,該工具在確定大量公司的總內在價值時可能還是有用的。
V.1免責聲明 (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.
上面的代碼僅是一個附屬項目,不應用于做出投資決策。 此外,從Yahoo Finance提取的信息不得用于任何商業目的。 如前所述,該程序只是將Python編程應用于金融的一項有趣的練習,如果將所得信息用于商業目的,我建議不要使用網絡抓取。
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.
最終代碼如下所示。 為了運行它,您將必須安裝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期權價格計算器
總結
以上是生活随笔為你收集整理的python期权价格计算器_使用Python构建内在价值计算器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: eclipse中svn从分支合并到主干及
- 下一篇: websocket python爬虫_p