2023年3月25日 星期六

ln跟log的差異,為什麼自然對數這麼重要?

 log是取對數(指數的相反方向)

log再加個數在下面,就是以那個數為底的對數。如log0.2(10),即為以0.2為底的對數。

具體來說:如果a(a>0,且a≠1)的b次冪等於n,即ab=n,那麼數b叫做以a為底n的對數,記作:logan=b,其中a叫做對數的底數,n叫做真數。

lg是以10為底數的對數。

ln是以e為底數,稱為自然對數。

exp(1/n)=e1/n(1 + 1/n)n


http://blog.udn.com/cchahacaptain/4565752

基本上只要和微積分沾的上關係的,電子、化工、乃至於純數學,一定看的見這兩個符號:【e】【ln】,從高中開始看見這個符號,沒有一個老師能回答我為什麼要有這個符號?為什麼它存在?為什麼不用log卻用ln?為什麼會需要一個2.7182818..這麼奇怪的數字?老是要我背,不希望我問為什麼?我真的是刁鑽的學生嗎?好痛苦!我真的沒辦法忽略它,跳過這個問題去考試。

這個問題困擾了我將近二十年,後來我終於看懂了,搞死我了,原來只是這樣!

所有的運算,都是基於加減法而來,而人類社會越來越複雜,越來越依賴數字的運作,乘除法便應運而生,乘除法是加減法的簡式,它把一大堆符號合併成單一式子,使得我們可以進行更複雜的紀錄與運算。

當社會越來越進步,建築、航海、經濟等等越來越發達,使得我們不只需要計算複雜的式子,也需要快速得到答案,在沒有計算機的年代,查表變成了最快得到答案的方法,可怕的是,要有一個瘋子去建出這本好似電話簿的數字表!

2 = 21   1

4 = 22   2

8 = 23   3

16 = 24  4

32 = 25  5

早期的科學家,發現了下面兩個式子的對應關係。

4 * 8 = 32 ……(1)

log2(4) + log2(8) = log2(32) ……(2)

換句話說,(4*8)這個計算,我只需要做出(2+3=5),接下來在第5欄查到32就可以得到答案了,或許有人會直接用99乘法表心算得到答案,覺得這個查表很愚蠢,我必須要說,你在用的99乘法表不就是在查表嗎?你在幹的事不就和幾百年前做的一模一樣嗎?算一下4096*8192,沒背了!就寫不出來了!

很遺憾,上述的表格再大也查不出來(9*9)的答案,問題就在底數的選擇,這裡選的是(2),這期間有許多人做出許多奮鬥,嘗試了各種數字,納皮爾這個人花了將近20年做出了一本精確到7位數字的對數表,所以人類的進步都是依賴這些瘋子完成的,不是看那些大學生整天用嘴說:【用青春寫歷史、青春萬歲、燃燒青春】,這裏面我只承認【燃燒青春】,每天熬夜在玩不燃燒青春嗎?

一直到有一個傢伙選了一個極為聰明的函數,就因為這個特殊的函數型態,導致日後的微積分,乃至於其他的科學,才得以行進下去,沒有這個東西,我們現在可能還停留在莊園時代,說不定是個佃農:

(1 + 1/n)n

假設n = 1000就是1.0011000,為了方便,我們使用n = 100就是1.01100,假設它為a,那我們就用這個數字建一個對數表:

第一欄 0.01 = loga(N)  N = (1.01100)0.01 = 1.011 = 1.01

第二欄 0.02 = loga(N)  N = (1.01100)0.02 = 1.012 = 1.0201

第三欄 0.03 = loga(N)  N = (1.01100)0.03 = 1.013 = 1.030301

……

有一種東西叫巴斯卡三角形,這個東西是基於二項式定理來的

   1

  1 1

 1 2 1

1 3 3 1

看到了這個三角形,再看看上面對數表最後面的數字,大概可以感受到為什麼要使用1.011.001等等這麼奇怪的數字型態了吧,因為這種數字型態可以更快速計算出答案。

說到這裡要再囉嗦一下,不要再去計較中國的楊輝三角比巴斯卡三角要早,所以中國人比較厲害,感覺很像小孩子吵架,你爸爸憋氣一分鐘,我爸爸更厲害,可以憋10分鐘,再怎麼厲害,也是祖先厲害,又不是你,沾甚麼光!

另一個巨人:尤拉(Euler),眼睛瞎了還可以寫數學著作,也是一個偉大的瘋子,聽說這個人個性很謙虛,他證明出當n為無限大時:

這個式子是收斂值,這是一個極為重要的發現,一個確認大小的數字,裡面可以切割出無限個點,這表示我可以做出刻度無限小的對數表(0.0…..0001),換句話說任何數字經過nature log相關運算必定能算出數字,而這個數字存在,只是寫不出來,寫不寫得出來只是書寫極限,並不影響存不存在的問題。

我認為,這也就是為什麼許多地方,無論是物理學、數學、工程等等的方程式推演,很喜歡朝向ln(nature log)e的方向行進,就是這個原因。

現在我有的時候回頭看古人搞科學,看到那些神妙處,真慚愧,越古會的應該越少才對,我甚麼都不會,應該才是古代人,他們是現代人,曾國藩的兒子曾紀鴻是一個大數學家,算出的圓周率竟然準確到小數點100位,我的媽呀!他是用手算耶!愛因斯坦十幾歲的時候,他的老師告訴他媽媽,妳一定要讓愛因斯坦去學一門手藝,不然他那麼笨,將來非餓死不可,結果他20幾歲發表了相對論、光電效應等論文,聰明還是笨,古代還是現代,真的很難說!

2023年3月7日 星期二

Chatgpt: give me a program about how to get latest option price and prediction using quantlib

 Here's an example Python program that uses QuantLib to calculate the Black-Scholes option price and predicts the option price based on the latest market data:



import QuantLib as ql import yfinance as yf # User inputs symbol = input("Enter stock symbol: ") expiry = input("Enter option expiry date (YYYY-MM-DD): ") option_type = input("Enter option type (call/put): ") strike_price = float(input("Enter option strike price: ")) risk_free_rate = float(input("Enter risk-free interest rate: ")) # Get option chain for the stock symbol option_chain = yf.Ticker(symbol).option_chain(expiry) # Get the latest market data underlying_price = option_chain.calls['lastPrice'][0] implied_volatility = option_chain.calls['impliedVolatility'][0] # Set up QuantLib objects calendar = ql.UnitedStates() day_count = ql.Actual365Fixed() calculation_date = ql.Date.todaysDate() ql.Settings.instance().evaluationDate = calculation_date option_expiry_date = ql.Date(expiry.split('-')[2], int(expiry.split('-')[1]), int(expiry.split('-')[0])) option_type_q = ql.Option.Call if option_type == 'call' else ql.Option.Put option = ql.EuropeanOption(ql.PlainVanillaPayoff(option_type_q, strike_price), ql.EuropeanExercise(option_expiry_date)) # Set up Black-Scholes process underlying_q = ql.QuoteHandle(ql.SimpleQuote(underlying_price)) risk_free_rate_q = ql.YieldTermStructureHandle(ql.FlatForward(calculation_date, risk_free_rate, day_count)) dividend_yield_q = ql.YieldTermStructureHandle(ql.FlatForward(calculation_date, 0.0, day_count)) volatility_q = ql.BlackVolTermStructureHandle(ql.BlackConstantVol(calculation_date, calendar, implied_volatility, day_count)) process = ql.BlackScholesProcess(underlying_q, dividend_yield_q, risk_free_rate_q, volatility_q) # Calculate Black-Scholes option price option.setPricingEngine(ql.AnalyticEuropeanEngine(process)) bs_price = option.NPV() # Display Black-Scholes option price print("The Black-Scholes option price is {:.2f}".format(bs_price)) # Predict option price based on latest market data delta_t = day_count.yearFraction(calculation_date, option_expiry_date) forward_price = underlying_price * np.exp(risk_free_rate * delta_t) predicted_price = bs_price + (implied_volatility / np.sqrt(delta_t)) * ((forward_price / underlying_price) - 1) print("The predicted option price based on the latest market data is {:.2f}".format(predicted_price))



In this program, we use the QuantLib library to calculate the Black-Scholes option price using the latest market data retrieved from Yahoo Finance. We start by asking the user to input the stock symbol, option expiry date, option type, strike price, and risk-free interest rate. We then retrieve the option chain for the stock symbol and extract the latest market data (underlying price and implied volatility).

We set up the necessary QuantLib objects, including the calculation date, option expiry date, option type, and Black-Scholes process. We then calculate the Black-Scholes option price using the setPricingEngine method.

Finally, we predict the option price based on the latest market data by calculating the forward price and using it to adjust the Black-Scholes price accordingly. We display the Black-Scholes option price and the predicted option price to the user. Note that you'll need to install the `

Chatgp: give me a program how to get latest option price

 Here's an example Python program that uses the Yahoo Finance API to retrieve the latest option prices for a given stock symbol:


import yfinance as yf # User inputs symbol = input("Enter stock symbol: ") expiry = input("Enter option expiry date (YYYY-MM-DD): ") option_type = input("Enter option type (call/put): ") strike_price = float(input("Enter option strike price: ")) # Get option chain for the stock symbol option_chain = yf.Ticker(symbol).option_chain(expiry) # Get the option price for the given strike price and option type if option_type == 'call': option_price = option_chain.calls.loc[option_chain.calls['strike'] == strike_price, 'lastPrice'].values[0] else: option_price = option_chain.puts.loc[option_chain.puts['strike'] == strike_price, 'lastPrice'].values[0] # Display the option price print("The latest {} option price for {} with strike price {} and expiry date {} is {:.2f}".format(option_type, symbol, strike_price, expiry, option_price))


In this program, we use the yfinance library to retrieve the option chain for the given stock symbol and expiry date. We then extract the latest option price for the given strike price and option type (call or put). Finally, we display the option price to the user. Note that you'll need to install the yfinance library if you haven't done so already, using pip install yfinance.

Chatgpt: option price prediction program python

 Here's an example Python program that allows the user to input the necessary parameters to predict the price of a call or put option using the Black-Scholes model:




import numpy as np from scipy.stats import norm def black_scholes(S, K, T, r, sigma, option='call'): """ Calculates the Black-Scholes option price and Greeks. S: current stock price K: option strike price T: time to expiration (in years) r: risk-free interest rate sigma: implied volatility option: 'call' or 'put' option (default is 'call') """ d1 = (np.log(S/K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T)) d2 = d1 - sigma * np.sqrt(T) if option == 'call': price = S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2) delta = norm.cdf(d1) gamma = norm.pdf(d1) / (S * sigma * np.sqrt(T)) vega = S * norm.pdf(d1) * np.sqrt(T) theta = (-S * norm.pdf(d1) * sigma) / (2 * np.sqrt(T)) - r * K * np.exp(-r * T) * norm.cdf(d2) rho = K * T * np.exp(-r * T) * norm.cdf(d2) else: price = K * np.exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1) delta = -norm.cdf(-d1) gamma = norm.pdf(d1) / (S * sigma * np.sqrt(T)) vega = S * norm.pdf(d1) * np.sqrt(T) theta = (-S * norm.pdf(d1) * sigma) / (2 * np.sqrt(T)) + r * K * np.exp(-r * T) * norm.cdf(-d2) rho = -K * T * np.exp(-r * T) * norm.cdf(-d2) return {'price': price, 'delta': delta, 'gamma': gamma, 'vega': vega, 'theta': theta, 'rho': rho} # User inputs S = float(input("Enter the current stock price: ")) K = float(input("Enter the option strike price: ")) T = float(input("Enter the time to expiration in years: ")) r = float(input("Enter the risk-free interest rate: ")) sigma = float(input("Enter the implied volatility: ")) option = input("Enter 'call' or 'put' option (default is 'call'): ") # Calculate option price and Greeks using Black-Scholes model result = black_scholes(S, K, T, r, sigma, option) # Display results print("Option price: {:.2f}".format(result['price'])) print("Delta: {:.2f}".format(result['delta'])) print("Gamma: {:.2f}".format(result['gamma'])) print("Vega: {:.2f}".format(result['vega'])) print("Theta: {:.2f}".format(result['theta'])) print("Rho: {:.2f}".format(result['rho']))


In this program, we define the black_scholes function that takes in the Black-Scholes inputs and calculates the theoretical price of a call or put option, as well as its Greeks (delta, gamma, vega, theta, rho). We then ask the user to input the necessary

Chatgpt - option price prediction python

 There are many ways to predict option prices in Python, but one popular method is to use the Black-Scholes model. The Black-Scholes model is a mathematical formula that calculates the theoretical value of an option based on various inputs such as the current stock price, the option strike price, time to expiration, risk-free interest rate, and implied volatility.

Here's an example Python code using the Black-Scholes model to predict the price of a call option:



import numpy as np from scipy.stats import norm def bs_call(S, K, T, r, sigma): d1 = (np.log(S/K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T)) d2 = d1 - sigma * np.sqrt(T) return S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2) # Input parameters S = 100 # current stock price K = 110 # option strike price T = 0.5 # time to expiration in years r = 0.05 # risk-free interest rate sigma = 0.2 # implied volatility # Calculate the call option price call_price = bs_call(S, K, T, r, sigma) print(f"The predicted call option price is: {call_price:.2f}")


In this code, we define a function bs_call that takes in the Black-Scholes inputs and calculates the theoretical price of a call option. We then input the current stock price, option strike price, time to expiration, risk-free interest rate, and implied volatility, and use the bs_call function to predict the call option price. Finally, we print the predicted call option price rounded to two decimal places.

Note that there are many other methods to predict option prices, and the Black-Scholes model is just one of them. Additionally, the Black-Scholes model assumes certain conditions that may not hold in real-world scenarios, so it's important to understand the limitations of the model before using it to make investment decisions.

ubunto in windows10



1. 要安裝 Ubuntu 的話,需要先啟用 Windows Linux Subsystem 功能。需在『開啟或關閉 Windows 功能中設定』




2. 在Windows Store 裡安裝 Ubuntu App




3.第一次登入要輸入帳號密碼
4.之後直接開始->ubunto, 不用雙系統了!!?