Module: OptionLab::Support

Defined in:
lib/option_lab/support.rb

Class Method Summary collapse

Class Method Details

._get_array_price_from_BS(inputs, n) ⇒ Numo::DFloat (private)

Generate array of prices using Black-Scholes model

Parameters:

Returns:

  • (Numo::DFloat)

    Array of prices



437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/option_lab/support.rb', line 437

def _get_array_price_from_BS(inputs, n)
  # Calculate mean and std
  mean = Math.log(inputs.stock_price) + 
         (inputs.interest_rate - inputs.dividend_yield - 0.5 * inputs.volatility**2) * 
         inputs.years_to_target_date
  std = inputs.volatility * Math.sqrt(inputs.years_to_target_date)
  
  # Generate random values
  random_values = Numo::DFloat.new(n).rand_norm(0, 1)
  
  # Apply formula
  Numo::NMath.exp(mean + std * random_values)
end

._get_array_price_from_laplace(inputs, n) ⇒ Numo::DFloat (private)

Generate array of prices using Laplace distribution

Parameters:

Returns:

  • (Numo::DFloat)

    Array of prices



455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/option_lab/support.rb', line 455

def _get_array_price_from_laplace(inputs, n)
  # Calculate location and scale
  location = Math.log(inputs.stock_price) + inputs.mu * inputs.years_to_target_date
  scale = (inputs.volatility * Math.sqrt(inputs.years_to_target_date)) / Math.sqrt(2.0)
  
  # Generate random values from uniform distribution
  u = Numo::DFloat.new(n).rand - 0.5
  
  # Convert to Laplace distribution
  laplace_values = location - scale * u.abs.map { |v| v < 0 ? -1 : 1 } * Numo::NMath.log(1 - 2 * u.abs)
  
  # Apply formula
  Numo::NMath.exp(laplace_values)
end

._get_payoff(option_type, s, x) ⇒ Numo::DFloat (private)

Calculate option payoff at expiration

Parameters:

  • option_type (String)

    'call' or 'put'

  • s (Numo::DFloat)

    Array of stock prices

  • x (Float)

    Strike price

Returns:

  • (Numo::DFloat)

    Option payoff



225
226
227
228
229
230
231
232
233
234
235
# File 'lib/option_lab/support.rb', line 225

def _get_payoff(option_type, s, x)
  if option_type == 'call'
    diff = s - x
    (diff + diff.abs) / 2.0
  elsif option_type == 'put'
    diff = x - s
    (diff + diff.abs) / 2.0
  else
    raise ArgumentError, "Option type must be either 'call' or 'put'!"
  end
end

._get_pl_option(option_type, opvalue, action, s, x) ⇒ Numo::DFloat (private)

Calculate P/L of an option at expiration

Parameters:

  • option_type (String)

    'call' or 'put'

  • opvalue (Float)

    Option price

  • action (String)

    'buy' or 'sell'

  • s (Numo::DFloat)

    Array of stock prices

  • x (Float)

    Strike price

Returns:

  • (Numo::DFloat)

    P/L profile



210
211
212
213
214
215
216
217
218
# File 'lib/option_lab/support.rb', line 210

def _get_pl_option(option_type, opvalue, action, s, x)
  if action == 'sell'
    opvalue - _get_payoff(option_type, s, x)
  elsif action == 'buy'
    _get_payoff(option_type, s, x) - opvalue
  else
    raise ArgumentError, "Action must be either 'sell' or 'buy'!"
  end
end

._get_pl_stock(s0, action, s) ⇒ Numo::DFloat (private)

Calculate P/L of a stock position

Parameters:

  • s0 (Float)

    Spot price

  • action (String)

    'buy' or 'sell'

  • s (Numo::DFloat)

    Array of stock prices

Returns:

  • (Numo::DFloat)

    P/L profile



242
243
244
245
246
247
248
249
250
# File 'lib/option_lab/support.rb', line 242

def _get_pl_stock(s0, action, s)
  if action == 'sell'
    s0 - s
  elsif action == 'buy'
    s - s0
  else
    raise ArgumentError, "Action must be either 'sell' or 'buy'!"
  end
end

._get_pop_array(inputs, target) ⇒ Array<Float, Float, Float, Float> (private)

Calculate PoP using array of terminal prices

Parameters:

Returns:

  • (Array<Float, Float, Float, Float>)

    PoP calculation results



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/option_lab/support.rb', line 312

def _get_pop_array(inputs, target)
  if inputs.array.size == 0
    raise ArgumentError, "The array is empty!"
  end
  
  # Split array by target
  above_target = inputs.array[inputs.array >= target]
  below_target = inputs.array[inputs.array < target]
  
  # Calculate probabilities
  probability_of_reaching_target = above_target.size.to_f / inputs.array.size
  probability_of_missing_target = 1.0 - probability_of_reaching_target
  
  # Calculate expected returns
  expected_return_above_target = above_target.size > 0 ? above_target.mean.round(2) : nil
  expected_return_below_target = below_target.size > 0 ? below_target.mean.round(2) : nil
  
  [
    probability_of_reaching_target,
    expected_return_above_target,
    probability_of_missing_target,
    expected_return_below_target
  ]
end

._get_pop_bs(s, profit, inputs, profit_range) ⇒ Array<Float, Float, Float, Float> (private)

Calculate PoP using Black-Scholes model

Parameters:

  • s (Numo::DFloat)

    Array of stock prices

  • profit (Numo::DFloat)

    Array of profits

  • inputs (Models::BlackScholesModelInputs)

    Model inputs

  • profit_range (Array<Array<Array<Float>>>)

    Profit and loss ranges

Returns:

  • (Array<Float, Float, Float, Float>)

    PoP calculation results



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/option_lab/support.rb', line 258

def _get_pop_bs(s, profit, inputs, profit_range)
  # Initialize variables
  expected_return_above_target = nil
  expected_return_below_target = nil
  probability_of_reaching_target = 0.0
  probability_of_missing_target = 0.0
  
  # Calculate sigma
  sigma = inputs.volatility > 0.0 ? 
    inputs.volatility * Math.sqrt(inputs.years_to_target_date) : 1e-10
  
  # Calculate PoP for each range
  profit_range.each_with_index do |t, i|
    prob = 0.0
    
    if t != [[0.0, 0.0]]
      t.each do |p_range|
        # Calculate log values
        lval = p_range[0] > 0.0 ? Math.log(p_range[0]) : -Float::INFINITY
        hval = Math.log(p_range[1])
        
        # Calculate drift and mean
        drift = (
          inputs.interest_rate - 
          inputs.dividend_yield - 
          0.5 * inputs.volatility * inputs.volatility
        ) * inputs.years_to_target_date
        
        m = Math.log(inputs.stock_price) + drift
        
        # Calculate probability
        prob += Distribution::Normal.cdf((hval - m) / sigma) - Distribution::Normal.cdf((lval - m) / sigma)
      end
    end
    
    if i == 0
      probability_of_reaching_target = prob
    else
      probability_of_missing_target = prob
    end
  end
  
  [
    probability_of_reaching_target,
    expected_return_above_target,
    probability_of_missing_target,
    expected_return_below_target
  ]
end

._get_profit_range(s, profit, target = 0.01) ⇒ Array<Array<Array<Float>>> (private)

Find profit/loss ranges

Parameters:

  • s (Numo::DFloat)

    Array of stock prices

  • profit (Numo::DFloat)

    Array of profits

  • target (Float) (defaults to: 0.01)

    Profit target

Returns:

  • (Array<Array<Array<Float>>>)

    Profit and loss ranges



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/option_lab/support.rb', line 342

def _get_profit_range(s, profit, target = 0.01)
  profit_range = []
  loss_range = []
  
  # Find where profit crosses target
  crossings = _get_sign_changes(profit, target)
  n_crossings = crossings.size
  
  # Handle case with no crossings
  if n_crossings == 0
    if profit[0] >= target
      return [[[0.0, Float::INFINITY]], [[0.0, 0.0]]]
    else
      return [[[0.0, 0.0]], [[0.0, Float::INFINITY]]]
    end
  end
  
  # Find profit and loss ranges
  lb_profit = hb_profit = nil
  lb_loss = hb_loss = nil
  
  crossings.each_with_index do |index, i|
    if i == 0
      if profit[index] < profit[index - 1]
        lb_profit = 0.0
        hb_profit = s[index - 1]
        lb_loss = s[index]
        
        hb_loss = Float::INFINITY if n_crossings == 1
      else
        lb_profit = s[index]
        lb_loss = 0.0
        hb_loss = s[index - 1]
        
        hb_profit = Float::INFINITY if n_crossings == 1
      end
    elsif i == n_crossings - 1
      if profit[index] > profit[index - 1]
        lb_profit = s[index]
        hb_profit = Float::INFINITY
        hb_loss = s[index - 1]
      else
        hb_profit = s[index - 1]
        lb_loss = s[index]
        hb_loss = Float::INFINITY
      end
    else
      if profit[index] > profit[index - 1]
        lb_profit = s[index]
        hb_loss = s[index - 1]
      else
        hb_profit = s[index - 1]
        lb_loss = s[index]
      end
    end
    
    if lb_profit && hb_profit
      profit_range << [lb_profit, hb_profit]
      lb_profit = hb_profit = nil
    end
    
    if lb_loss && hb_loss
      loss_range << [lb_loss, hb_loss]
      lb_loss = hb_loss = nil
    end
  end
  
  [profit_range, loss_range]
end

._get_sign_changes(profit, target) ⇒ Array<Integer> (private)

Find indices where profit crosses target

Parameters:

  • profit (Numo::DFloat)

    Array of profits

  • target (Float)

    Profit target

Returns:

  • (Array<Integer>)

    Array of indices



416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/option_lab/support.rb', line 416

def _get_sign_changes(profit, target)
  # Subtract target and add small epsilon
  p_temp = profit - target + 1e-10
  
  # Get signs (convert to array first since Numo::DFloat doesn't have collect)
  signs_1 = p_temp[0...-1].to_a.map { |v| v > 0 ? 1 : -1 }
  signs_2 = p_temp[1..-1].to_a.map { |v| v > 0 ? 1 : -1 }
  
  # Find sign changes
  changes = []
  signs_1.each_with_index do |s1, i|
    changes << i + 1 if s1 * signs_2[i] < 0
  end
  
  changes
end

.create_price_array(inputs_data, n: 100_000, seed: nil) ⇒ Numo::DFloat

Create price array for simulations

Parameters:

Returns:

  • (Numo::DFloat)

    Array of prices



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/option_lab/support.rb', line 169

def create_price_array(inputs_data, n: 100_000, seed: nil)
  # Set random seed if provided
  Kernel.srand(seed) if seed
  
  # Convert hash to appropriate model if needed
  inputs = if inputs_data.is_a?(Hash)
            if %w[black-scholes normal].include?(inputs_data[:model] || inputs_data['model'])
              Models::BlackScholesModelInputs.new(inputs_data)
            elsif (inputs_data[:model] || inputs_data['model']) == 'laplace'
              Models::LaplaceInputs.new(inputs_data)
            else
              raise ArgumentError, "Invalid model type!"
            end
          else
            inputs_data
          end
  
  # Generate array based on model
  arr = if inputs.is_a?(Models::BlackScholesModelInputs)
          _get_array_price_from_BS(inputs, n)
        elsif inputs.is_a?(Models::LaplaceInputs)
          _get_array_price_from_laplace(inputs, n)
        else
          raise ArgumentError, "Invalid inputs type!"
        end
  
  # Reset random seed
  Kernel.srand if seed
  
  arr
end

.create_price_seq(min_price, max_price) ⇒ Numo::DFloat

Generate a sequence of stock prices from min to max with $0.01 increment

Parameters:

  • min_price (Float)

    Minimum stock price

  • max_price (Float)

    Maximum stock price

Returns:

  • (Numo::DFloat)

    Array of sequential stock prices



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/option_lab/support.rb', line 100

def create_price_seq(min_price, max_price)
  cache_key = "#{min_price}-#{max_price}"
  
  # Return cached result if available
  return @price_seq_cache[cache_key] if @price_seq_cache.key?(cache_key)
  
  if max_price > min_price
    # Create array with increment 0.01
    steps = ((max_price - min_price) * 100 + 1).to_i
    arr = Numo::DFloat.new(steps).seq(min_price, 0.01)
    
    # Round to 2 decimal places (Numo::DFloat doesn't support arguments to round)
    arr = arr.round
    
    # Cache the result
    @price_seq_cache[cache_key] = arr
    
    arr
  else
    raise ArgumentError, "Maximum price cannot be less than minimum price!"
  end
end

.get_pl_profile(option_type, action, x, val, n, s, commission = 0.0) ⇒ Array<Numo::DFloat, Float>

Get profit/loss profile and cost of an options trade at expiration

Parameters:

  • option_type (String)

    'call' or 'put'

  • action (String)

    'buy' or 'sell'

  • x (Float)

    Strike price

  • val (Float)

    Option price

  • n (Integer)

    Number of options

  • s (Numo::DFloat)

    Array of stock prices

  • commission (Float) (defaults to: 0.0)

    Brokerage commission

Returns:

  • (Array<Numo::DFloat, Float>)

    P/L profile and cost



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/option_lab/support.rb', line 21

def get_pl_profile(option_type, action, x, val, n, s, commission = 0.0)
  if action == 'buy'
    cost = -val
  elsif action == 'sell'
    cost = val
  else
    raise ArgumentError, "Action must be either 'buy' or 'sell'!"
  end
  
  if Models::OPTION_TYPES.include?(option_type)
    [
      n * _get_pl_option(option_type, val, action, s, x) - commission,
      n * cost - commission
    ]
  else
    raise ArgumentError, "Option type must be either 'call' or 'put'!"
  end
end

.get_pl_profile_bs(option_type, action, x, val, r, target_to_maturity_years, volatility, n, s, y = 0.0, commission = 0.0) ⇒ Array<Numo::DFloat, Float>

Get profit/loss profile and cost of an options trade before expiration using Black-Scholes

Parameters:

  • option_type (String)

    'call' or 'put'

  • action (String)

    'buy' or 'sell'

  • x (Float)

    Strike price

  • val (Float)

    Option price

  • r (Float)

    Risk-free interest rate

  • target_to_maturity_years (Float)

    Time remaining to maturity from target date

  • volatility (Float)

    Volatility

  • n (Integer)

    Number of options

  • s (Numo::DFloat)

    Array of stock prices

  • y (Float) (defaults to: 0.0)

    Dividend yield

  • commission (Float) (defaults to: 0.0)

    Brokerage commission

Returns:

  • (Array<Numo::DFloat, Float>)

    P/L profile and cost



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/option_lab/support.rb', line 75

def get_pl_profile_bs(option_type, action, x, val, r, target_to_maturity_years, volatility, n, s, y = 0.0, commission = 0.0)
  if action == 'buy'
    cost = -val
    factor = 1
  elsif action == 'sell'
    cost = val
    factor = -1
  else
    raise ArgumentError, "Action must be either 'buy' or 'sell'!"
  end
  
  # Calculate prices using Black-Scholes
  d1 = BlackScholes.get_d1(s, x, r, volatility, target_to_maturity_years, y)
  d2 = BlackScholes.get_d2(s, x, r, volatility, target_to_maturity_years, y)
  calc_price = BlackScholes.get_option_price(option_type, s, x, r, target_to_maturity_years, d1, d2, y)
  
  profile = factor * n * (calc_price - val) - commission
  
  [profile, n * cost - commission]
end

.get_pl_profile_stock(s0, action, n, s, commission = 0.0) ⇒ Array<Numo::DFloat, Float>

Get profit/loss profile and cost of a stock position

Parameters:

  • s0 (Float)

    Initial stock price

  • action (String)

    'buy' or 'sell'

  • n (Integer)

    Number of shares

  • s (Numo::DFloat)

    Array of stock prices

  • commission (Float) (defaults to: 0.0)

    Brokerage commission

Returns:

  • (Array<Numo::DFloat, Float>)

    P/L profile and cost



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/option_lab/support.rb', line 47

def get_pl_profile_stock(s0, action, n, s, commission = 0.0)
  if action == 'buy'
    cost = -s0
  elsif action == 'sell'
    cost = s0
  else
    raise ArgumentError, "Action must be either 'buy' or 'sell'!"
  end
  
  [
    n * _get_pl_stock(s0, action, s) - commission,
    n * cost - commission
  ]
end

.get_pop(s, profit, inputs_data, target = 0.01) ⇒ Models::PoPOutputs

Estimate probability of profit

Parameters:

Returns:



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/option_lab/support.rb', line 129

def get_pop(s, profit, inputs_data, target = 0.01)
  # Initialize variables
  probability_of_reaching_target = 0.0
  probability_of_missing_target = 0.0
  expected_return_above_target = nil
  expected_return_below_target = nil
  
  # Get profit ranges
  t_ranges = _get_profit_range(s, profit, target)
  
  reaching_target_range = t_ranges[0] == [[0.0, 0.0]] ? [] : t_ranges[0]
  missing_target_range = t_ranges[1] == [[0.0, 0.0]] ? [] : t_ranges[1]
  
  # Calculate PoP based on inputs model
  if inputs_data.is_a?(Models::BlackScholesModelInputs)
    probability_of_reaching_target, expected_return_above_target,
    probability_of_missing_target, expected_return_below_target = 
      _get_pop_bs(s, profit, inputs_data, t_ranges)
  elsif inputs_data.is_a?(Models::ArrayInputs)
    probability_of_reaching_target, expected_return_above_target,
    probability_of_missing_target, expected_return_below_target = 
      _get_pop_array(inputs_data, target)
  end
  
  # Return outputs
  Models::PoPOutputs.new(
    probability_of_reaching_target: probability_of_reaching_target,
    probability_of_missing_target: probability_of_missing_target,
    reaching_target_range: reaching_target_range,
    missing_target_range: missing_target_range,
    expected_return_above_target: expected_return_above_target,
    expected_return_below_target: expected_return_below_target
  )
end