-- This Lua program calculates the IV (Implied Volatility) of the Black-Scholes model.
-- The Black-Scholes model is used to calculate the theoretical price of options.
-- The IV represents the volatility implied by the market price of the option.

-- Global constants for the Black-Scholes formula
local d1 = 0.0
local d2 = 0.0
local epsilon = 0.000001
local maxIterations = 100

--- Calculate the IV (Implied Volatility) of the Black-Scholes model
-- This function calculates and returns the IV of the Black-Scholes model based on the given parameters.
-- @param S The current price of the underlying asset
-- @param K The strike price of the option
-- @param r The risk-free interest rate
-- @param T The time to expiration of the option
-- @param C The market price of the option
-- @param type The type of the option (either "call" or "put")
-- @return The IV of the Black-Scholes model or nil if there's an error, along with an error message.
local function calculateIV(S, K, r, T, C, optionType)
    -- Validate the input
    if S <= 0 or K <= 0 or r <= 0 or T <= 0 or C <= 0 then
        return nil, "Invalid input. All parameters should be positive numbers."
    end
    
    if optionType ~= "call" and optionType ~= "put" then
        return nil, "Invalid input. Option type should be either 'call' or 'put'."
    end
    
    -- Define the function to calculate the option price using the Black-Scholes formula
    local function calculateOptionPrice(sigma)
        -- Calculate d1 and d2
        d1 = (math.log(S / K) + (r + 0.5 * sigma^2) * T) / (sigma * math.sqrt(T))
        d2 = d1 - sigma * math.sqrt(T)
        
        -- Calculate the option price
        local optionPrice = 0.0
        if optionType == "call" then
            optionPrice = S * norm.cdf(d1) - K * math.exp(-r * T) * norm.cdf(d2)
        else
            optionPrice = K * math.exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1)
        end
        
        return optionPrice
    end
    
    -- Define the function to calculate the derivative of the option price with respect to sigma
    local function calculateOptionPriceDerivative(sigma)
        -- Calculate the derivative of the option price
        local dOptionPrice = 0.0
        if optionType == "call" then
            dOptionPrice = S * math.sqrt(T) * norm.pdf(d1)
        else
            dOptionPrice = -S * math.sqrt(T) * norm.pdf(-d1)
        end
        
        return dOptionPrice
    end
    
    -- Implement the Newton-Raphson method to find the IV
    local sigma = math.sqrt(2 * math.abs((math.log(S / K) + r * T) / T))
    local optionPrice = calculateOptionPrice(sigma)
    local optionPriceDerivative = calculateOptionPriceDerivative(sigma)
    local iteration = 0
    
    while math.abs(optionPrice - C) > epsilon and iteration < maxIterations do
        sigma = sigma - (optionPrice - C) / optionPriceDerivative
        optionPrice = calculateOptionPrice(sigma)
        optionPriceDerivative = calculateOptionPriceDerivative(sigma)
        iteration = iteration + 1
    end
    
    -- Check if the IV calculation converged
    if iteration >= maxIterations then
        return nil, "Failed to converge. Maximum number of iterations reached."
    end
    
    return sigma
end

-- Main execution
print("[INFO] Starting program.")

local S = 100  -- Example input: current price of the underlying asset
local K = 100  -- Example input: strike price of the option
local r = 0.05  -- Example input: risk-free interest rate
local T = 1  -- Example input: time to expiration of the option
local C = 10  -- Example input: market price of the option
local optionType = "call"  -- Example input: type of the option

local IV, err = calculateIV(S, K, r, T, C, optionType)

if IV then
    plot(string.format("The IV of the Black-Scholes model is: %.4f", IV))
else
    plot("[ERROR]", err)
end

plot("[INFO] Program finished.") 

Lua online compiler

Write, Run & Share Lua code online using OneCompiler's Lua online compiler for free. It's one of the robust, feature-rich online compilers for Lua language, running the latest Lua version 5.4. Getting started with the OneCompiler's Lua editor is easy and fast. The editor shows sample boilerplate code when you choose language as Lua and start coding.

Taking inputs (stdin)

OneCompiler's Lua online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Lua program which takes name as input and prints hello message with your name.

name = io.read("*a")
print ("Hello ", name)

About Lua

Lua is a light weight embeddable scripting language which is built on top of C. It is used in almost all kind of applications like games, web applications, mobile applications, image processing etc. It's a very powerful, fast, easy to learn, open-source scripting language.

Syntax help

Variables

  • By default all the variables declared are global variables
  • If the variables are explicitly mentioned as local then they are local variables.
  • Lua is a dynamically typed language and hence only the values will have types not the variables.

Examples

-- global variables
a = 10

-- local variables

local x = 30
Value TypeDescription
numberRepresents numbers
stringRepresents text
nilDifferentiates values whether it has data or not
booleanValue can be either true or false
functionRepresents a sub-routine
userdataRepresents arbitary C data
threadRepresents independent threads of execution.
tableCan hold any value except nil

Loops

1. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(condition)
do
--code
end

2. Repeat-Until:

Repeat-Until is also used to iterate a set of statements based on a condition. It is very similar to Do-While, it is mostly used when you need to execute the statements atleast once.

repeat
   --code
until( condition )

3. For:

For loop is used to iterate a set of statements based on a condition.

for init,max/min value, increment
do
   --code
end

Functions

Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increase re-usuability and modularity.

optional_function_scope function function_name( argument1, argument2, argument3........, argumentn)
--code
return params with comma seperated
end