← Back to Problems
Piecewise Volatility Barrier
Medium standard Pricing
Time limit: 4 s per test  ·  Memory: 256 MB

A stock follows geometric Brownian motion under the risk-neutral measure with constant risk-free rate r, constant dividend yield q, and a volatility that is piecewise constant in time: over the m consecutive time segments the volatility takes values sigma_1, ..., sigma_m, with segment j lasting dt_j years. The option maturity is the total time T = dt_1 + ... + dt_m.

Price a continuously monitored knock-out barrier call with strike K and barrier B:

  • if type is up, the option is up-and-out: it pays max(S_T - K, 0) at maturity unless the stock's price rises to B or above at any time in [0, T], in which case it pays nothing;
  • if type is down, the option is down-and-out: it pays max(S_T - K, 0) at maturity unless the stock's price falls to B or below at any time in [0, T], in which case it pays nothing.

The spot S_0 never starts on the wrong side of the barrier. Output the option's present value.

Input

The first line contains type (the string up or down), then S_0, K, B, r, q, and the integer m.

Each of the next m lines contains a segment duration dt_j and its volatility sigma_j.

All real inputs have at most 6 digits after the decimal point.

Output

One real number: the present value of the option, with relative error at most 1e-4.

Constraints

1 <= m <= 20

0.01 <= S_0, K, B <= 1000

0 <= r, q <= 0.2

0.01 <= sigma_j <= 1.0

0.01 <= dt_j, and T <= 10

Scoring

This is a standard problem: a submission scores full points if it produces the correct output for every test case, and zero otherwise.

Numeric answers are accepted if they are within a relative tolerance of 0.0001 of the expected value.

Examples

input
up 100 100 130 0.03 0.0 2
0.5 0.2
0.5 0.3
output
2.057109152271259
input
down 100 100 85 0.02 0.01 1
1.0 0.25
output
9.148343651974292
Python 3.13 i Execution environment Isolated microVM · 1 vCPU · no internet access Time and memory limits are set per problem Available packages numpy 2.5.0scipy 1.18.0pandas 3.0.0scikit-learn 1.9.0statsmodels 0.15.0cvxpy 1.9.2