Black Scholes Model Python - Codearmo
文章推薦指數: 80 %
Black Scholes Model Python · 1) Interest rate is known and constant through time. · 2) The stock follows a random walk in continuous time, the ... IntroductiontoOptions GettingOptionsDatafromYahooFinancewithPandas BullandBearSpreadStrategies Straddles,Butterflies,IronCondorsandMore OptionsPricingIntroduction BinomialPricingModelwithPython BlackScholesModelPython TheGreeksbyAnalytic&NumericalMethodswithPython BinaryOptionsandImpliedDistributionswithPython CryptoCurrencyOptions CalculatingtheVolatilitySmile MertonJumpDiffusionModelwithPython HestonModelSimulationwithPython Menu BlackScholesModelPython John| December22,2020| TheBlack-ScholesequationsrevolutionizedoptionpricingwhenthepaperwaspublishedbyMryonScholesandFischerBlackin1973.Theargumentstheyuseintheirpaperalsofollownoarbitrageargumentswhichwerediscussedhere.Wepresenttheformulaeherewithoutderivation,whichwillbeprovidedinaseparatearticle.WecanalsosimulatetheBlack-Scholesmodel asshownhere. Contents -AssumptionsofBlackScholes -Non-dividendpayingstockformulaandPythonimplementation -Parametereffectsonoptionvalues -Dividendpayingstockimplementation -OOPimplementation. Black-ScholesAssumptions Thereareanumberofimportantassumptionstoconsiderwhenviewingtheformulaebelow. 1)Interestrateisknownandconstantthroughtime. 2)Thestockfollowsarandomwalkincontinuous time,thevarianceofthestockpricepathsfollowalog-normaldistribution. 3)Volatilityisconstant 4)Stockpaysnodividends(canbemodifiedtoincludethemhowever) 5)Theoptioncanonlybeexercisedatexpirationi.e.itisaEuropeantypeoption. 6)Notransactioncostsi.e.feesonshortingsellingetc. 7)Fractionaltradingispossiblei.e.wecanbuy/sell0.xofanygivenstock. BlackScholes FormulaforNonDividendPayingStock Theformulaeforboththeputandthecallisgivenbelow. \(Call=S_{0}N(d_1)-N(d_2)Ke^{-rT}\) \(Put=N(-d_2)Ke^{-rT}-N(-d_1)S_0\) \(\\d_1=\frac{ln(\frac{S}{K})+(r+\frac{\sigma^2}{2})T}{\sigma\sqrt{T}}\\\\d_2=d_1-\sigma\sqrt{T}\) S : currentassetprice K:strikepriceoftheoption r:riskfreerate T :timeuntiloptionexpiration σ:annualizedvolatilityoftheasset'sreturns N(x):isthecumulativedistributionfunctionforastandardnormaldistributionshownbelow. \(N(x)=\displaystyle\int_{-\infty}^{x}\frac{e^{-x^{2}/2}}{\sqrt{2\pi}}\) importnumpyasnp fromscipy.statsimportnorm N=norm.cdf defBS_CALL(S,K,T,r,sigma): d1=(np.log(S/K)+(r+sigma**2/2)*T)/(sigma*np.sqrt(T)) d2=d1-sigma*np.sqrt(T) returnS*N(d1)-K*np.exp(-r*T)*N(d2) defBS_PUT(S,K,T,r,sigma): d1=(np.log(S/K)+(r+sigma**2/2)*T)/(sigma*np.sqrt(T)) d2=d1-sigma*np.sqrt(T) returnK*np.exp(-r*T)*N(-d2)-S*N(-d1) Inthissectionwewillexaminetheeffectsofchangingtheinputparameterstothevalueofcallsandputs. SEffectonOptionValue HerewewillholdconstantallthevariablesexceptthecurrentstockpriceSandexaminehowthevalueofcallsandputschange. K=100 r=0.1 T=1 sigma=0.3 S=np.arange(60,140,0.1) calls=[BS_CALL(s,K,T,r,sigma)forsinS] puts=[BS_PUT(s,K,T,r,sigma)forsinS] plt.plot(STs,calls,label='CallValue') plt.plot(STs,puts,label='PutValue') plt.xlabel('$S_0$') plt.ylabel('Value') plt.legend() \(\sigma\) EffectonBlack-ScholesValue Aswewouldexpect,whenweholdtheothervariablesconstant,andincreasethevolatilityparameterbothcallsandputsincreaseinvalue,inwhatappearstobealinearfashionasshownbelow. Tounderstandwhythecallsvalueseemstobestrictlygreaterthantheputwithrespecttovolatility,changetheinterestrate \(r\) to0andnoticethatthecurvecoincideexactly.Ratherthanmakingplotsfortheeffectoninterestrates,wecandeducefromthisthatanincreaseininterestratesincreasesthevalueofcallsanddecreasesthevalueofputs. K=100 r=0.1 T=1 Sigmas=np.arange(0.1,1.5,0.01) S=100 calls=[BS_CALL(S,K,T,r,sig)forsiginSigmas] puts=[BS_PUT(S,K,T,r,sig)forsiginSigmas] plt.plot(Sigmas,calls,label='CallValue') plt.plot(Sigmas,puts,label='PutValue') plt.xlabel('$\sigma$') plt.ylabel('Value') plt.legend() EffectofTimeonBlack-ScholesPrice Asweincreasetimeweincreasetheuncertaintyregardingthefutureprice.Sinceuncertaintyistotheoptionsholderbenefit,thepriceoftheoptionincreaseswithtime.Againtrysettingtheinterestratetozerotoobservethatthedifferencebetweenputsandcallsiseliminated. K=100 r=0.05 T=np.arange(0,2,0.01) sigma=0.3 S=100 calls=[BS_CALL(S,K,t,r,sigma)fortinT] puts=[BS_PUT(S,K,t,r,sigma)fortinT] plt.plot(T,calls,label='CallValue') plt.plot(T,puts,label='PutValue') plt.xlabel('$T$inyears') plt.ylabel('Value') plt.legend() MainProblemwithBlackScholes ThescriptbelowcalculatestherollingstandarddeviationforAPPLEoverapproximately10years.Noticethatthevolatilityisinnowaystable,ifwetakethestandarddeviationovertheentiresampleitisapproximately0.28,however,noticethatinearly-mid2020duringthereisalargespike.Asmentioned,theBlack-Scholesmodelassumesthisparameterisconstant. importpandas_datareader.dataasweb importpandasaspd importdatetimeasdt importnumpyasnp importmatplotlib.pyplotasplt start=dt.datetime(2010,1,1) end=dt.datetime(2020,10,1) symbol='AAPL'###usingAppleasanexample source='yahoo' data=web.DataReader(symbol,source,start,end) data['change']=data['AdjClose'].pct_change() data['rolling_sigma']=data['change'].rolling(20).std()*np.sqrt(255) data.rolling_sigma.plot() plt.ylabel('$\sigma$') plt.title('AAPLRollingVolatility') Anotherkeyproblemisthatthemodelunderestimatesthetaildensity.TheKDEplotbelowshowstheempircalverusanormaldistributionforApplestock.ThismeansthatBlack-Scholeswillunderestimatethevalueofout-of-the-moneyoptions.Bothoftheseproblemswillbeaddressedinfuturearticles. std=data.change.std() WT=np.random.normal(data.change.mean(),std,size=Ndraws) plt.hist(np.exp(WT)-1,bins=300,color='red',alpha=0.4); plt.hist(data.change,bins=200,color='black',alpha=0.4); plt.xlim([-0.03,0.03]) importseabornassns fig,ax=plt.subplots() ax=sns.kdeplot(data=data['change'].dropna(),label='Empirical',ax=ax,shade=True) ax=sns.kdeplot(data=WT,label='LogNormal',ax=ax,shade=True) plt.xlim([-0.15,0.15]) plt.ylim([-1,40]) plt.xlabel('return') plt.ylabel('Density') Black-ScholesforDividendPayingStock Wecaneasilymodifythenon-dividendformuladescribedabovetoincludeadividend.Notethatthedividenddenotedas \(q\) belowisacontinuouslycompoundeddividend.Thismeansthattheactualdividenddateisirrelevanttothepricingformula.Clearlythisisn'tidealandcouldresultinlargeerrorsforstockswhichpayslargedividends. \(Call=S_{0}e^{-qT}N(d_1)-N(d_2)Ke^{-rT}\) \(Put=N(-d_2)Ke^{-rT}-N(-d_1)S_0e^{-qT}\) \(\\d_1=\frac{ln(\frac{S}{K})+(r-q+\frac{\sigma^2}{2})T}{\sigma\sqrt{T}}\\\\d_2=d_1-\sigma\sqrt{T}\) defBS_CALLDIV(S,K,T,r,q,sigma): d1=(np.log(S/K)+(r-q+sigma**2/2)*T)/(sigma*np.sqrt(T)) d2=d1-sigma*np.sqrt(T) returnS*np.exp(-q*T)*N(d1)-K*np.exp(-r*T)*N(d2) defBS_PUTDIV(S,K,T,r,q,sigma): d1=(np.log(S/K)+(r-q+sigma**2/2)*T)/(sigma*np.sqrt(T)) d2=d1-sigma*np.sqrt(T) returnK*np.exp(-r*T)*N(-d2)-S*np.exp(-q*T)*N(-d1) OOPImplemenation Noticethatthereisalotofrepetitivecodeinthefunctionsabove,wecancombineeverythingintoanobjectorientatedprogramasshownbelow.Topricebothacallandput,insert'B'forbothintothepricemethod. fromscipy.statsimportnorm classBsOption: def__init__(self,S,K,T,r,sigma,q=0): self.S=S self.K=K self.T=T self.r=r self.sigma=sigma self.q=q @staticmethod defN(x): returnnorm.cdf(x) @property defparams(self): return{'S':self.S, 'K':self.K, 'T':self.T, 'r':self.r, 'q':self.q, 'sigma':self.sigma} defd1(self): return(np.log(self.S/self.K)+(self.r-self.q+self.sigma**2/2)*self.T)\ /(self.sigma*np.sqrt(self.T)) defd2(self): returnself.d1()-self.sigma*np.sqrt(self.T) def_call_value(self): returnself.S*np.exp(-self.q*self.T)*self.N(self.d1())-\ self.K*np.exp(-self.r*self.T)*self.N(self.d2()) def_put_value(self): returnself.K*np.exp(-self.r*self.T)*self.N(-self.d2())-\ self.S*np.exp(-self.q*self.T)*self.N(-self.d1()) defprice(self,type_='C'): iftype_=='C': returnself._call_value() iftype_=='P': returnself._put_value() iftype_=='B': return{'call':self._call_value(),'put':self._put_value()} else: raiseValueError('Unrecognizedtype') if__name__=='__main__': K=100 r=0.1 T=1 sigma=0.3 S=100 print(BsOption(S,K,T,r,sigma).price('B')) #Out: #{'call':16.73413358238666,'put':7.217875385982609} BlackScholesModelPython LearnOptionsTradingUsingPython
延伸文章資訊
- 1Implementing the Black-Scholes in Python
the Black-Scholes Partial Differential Equation given below: ... We successfully implemented the ...
- 2Black Scholes Model in Python for Predicting Options Premiums
The Black Scholes model is considered to be one of the best ways of determining fair prices of op...
- 3Black Scholes Model Python - Codearmo
Black Scholes Model Python · 1) Interest rate is known and constant through time. · 2) The stock ...
- 4Black Scholes and Option Greeks in Python
Implement Black-Scholes Model using Opstrat ... Opstrat is a python package which deals with opti...
- 5Python財金應用:Black-Scholes選擇權訂價模型(1)
經典的量化金融案例,也是每天在交易室會碰到無數次的內容,推導Black-Scholes formula就不是本篇的重點,有興趣我會在文章最底下附上推薦書單。