aboutsummaryrefslogtreecommitdiffstats
path: root/gen.py
blob: 149e28741606f0543cbe2389bf430949b8697e9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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
163
164
165
166
167
168
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#! /usr/bin/env python3
# author : S. Mandalia
#          shivesh.mandalia@outlook.com
#
# date   : May 20, 2020


"""
Exotic options by Monte Carlo.

Generate fake data.

"""

import random
from typing import List

import numpy as np

from utils.engine import PricingEngine
from utils.path import PathGenerator
from utils.payoff import AsianArithmeticPayOff, DiscreteBarrierPayOff
from utils.payoff import VanillaPayOff


__all__ = ['vanilla', 'asian', 'barrier']


NGEN = 13
# NGEN = 10
NTRIALS = 1e5


def vanilla() -> None:
    """Generate Vanilla option fake data."""
    outfile = './vanilla.csv'

    with open(outfile, 'w') as f:
        s = 'ID,Spot,Strike,Risk-Free Rate,Years to Expiry,Volatility,' \
            'Option Right,Price\n'
        f.write(s)

        idx = 0
        for ndx in range(NGEN):
            if (ndx + 1) % 10 == 0:
                print('{0} / {1}'.format(ndx + 1, NGEN))

            for right in ('Call', 'Put'):
                S, K, T, r, vol = np.random.random(5)
                S *= 300
                K *= 300
                r = r * 1E-2 - 5E-3
                T *= 3
                vol += 1E-4

                path = PathGenerator(S=S, r=r, div=0., vol=vol)
                payoff = VanillaPayOff(K=K, option_right=right)
                engine = PricingEngine(payoff=payoff, path=path)

                # Price
                result = engine.price(T=[0, T], ntrials=NTRIALS)
                s = '{0},{1:.6g},{2:.6g},{3:.6g},{4:.6g},{5:.6g},{6},' \
                    '{7:.6g}\n'.format(
                        idx, S, K, r, T, vol, right, result.price
                    )
                f.write(s)
                idx += 1


def asian() -> None:
    """Generate Asian option fake data."""
    outfile = './asian.csv'

    with open(outfile, 'w') as f:
        s = 'ID,Spot,Strike,Risk-Free Rate,Years to Expiry,Volatility,' \
            'Option Right,Averaging Days,Price\n'
        f.write(s)

        idx = 0
        for right in ('Call', 'Put'):
            idy = 0
            while idy < NGEN:
                S, K, T, r, vol = np.random.random(5)
                S *= 300
                K *= 300
                r = r * 1E-2 - 5E-3
                T *= 1
                vol += 1E-4

                path = PathGenerator(S=S, r=r, div=0., vol=vol)
                payoff = AsianArithmeticPayOff(K=K, option_right=right)
                engine = PricingEngine(payoff=payoff, path=path)

                # (i) an Asian call option with maturity in T year(s) and
                #     30 days averaging.
                ad = 30
                n = int(T * 365 // ad)
                if n > 1:
                    # f_start = (T * 365 - n * ad)
                    # t = [(x * ad) + f_start for x in range(n + 1)]
                    t = [(x * ad / 365.) for x in range(n + 1)]

                    # Price
                    result = engine.price(T=t, ntrials=NTRIALS)
                    if abs(result.price) < 1E-5:
                        continue
                    s = '{0},{1:.6g},{2:.6g},{3:.6g},{4:.6g},{5:.6g},{6},{7},' \
                        '{8:.6g}\n'.format(
                            idx, S, K, r, T, vol, right, ad, result.price
                        )
                    f.write(s)
                    idx += 1
                    idy += 1

                # # (ii) an Asian call option with maturity in T year(s) and
                # #      90 days averaging.
                # ad = 90
                # n = int(T * 365 // ad)
                # f_start = (T * 365 - n * ad)
                # t = [(x * ad) + f_start for x in range(n + 1)]
                #
                # # Price
                # result = engine.price(T=t, ntrials=NTRIALS)
                # s = '{0},{1:.6g},{2:.6g},{3:.6g},{4:.6g},{5:.6g},{6},{7},' \
                #     '{8:.6g}\n'.format(
                #         idx, S, K, r, T, vol, right, ad, result.price
                #     )
                # f.write(s)
                # idx += 1

                # (iii) an Asian call option with maturity in T year(s) and
                #       7 days averaging.
                ad = 7
                n = int(T * 365 // ad)
                if n > 1:
                    # f_start = (T * 365 - n * ad)
                    # t = [(x * ad) + f_start for x in range(n + 1)]
                    t = [(x * ad / 365.) for x in range(n + 1)]

                    # Price
                    result = engine.price(T=t, ntrials=NTRIALS)
                    if abs(result.price) < 1E-5:
                        continue
                    s = '{0},{1:.6g},{2:.6g},{3:.6g},{4:.6g},{5:.6g},{6},{7},' \
                        '{8:.6g}\n'.format(
                            idx, S, K, r, T, vol, right, ad, result.price
                        )
                    f.write(s)
                    idx += 1
                    idy += 1


def barrier() -> None:
    """Generate barrier option fake data."""
    outfile = './barrier.csv'

    with open(outfile, 'w') as f:
        s = 'ID,Spot,Strike,Risk-Free Rate,Years to Expiry,Volatility,' \
            'Option Right,Barrier Value,Barrier UpDown,Barrier InOut,Mesh Spacing,Price\n'
        f.write(s)

        idx = 0
        for right in ('Call', 'Put'):
            for b_inout in ('In', 'Out'):
                for b_updown in ('Up', 'Down'):
                    idy = 0
                    while idy < NGEN:
                        B, S, K, T, r, vol = np.random.random(6)
                        B *= 300
                        S *= 300
                        K *= 300
                        r = r * 1E-2 - 5E-3
                        T *= 1
                        vol += 1E-4

                        path = PathGenerator(S=S, r=r, div=0., vol=vol)
                        payoff = DiscreteBarrierPayOff(
                            K=K, option_right=right, B=B,
                            barrier_updown=b_updown, barrier_inout=b_inout
                        )
                        engine = PricingEngine(payoff=payoff, path=path)

                        # (i) Monthly barrier dates.
                        bd = 30
                        n = int(T * 365 // bd)
                        if n > 1:
                            t = [(x * bd / 365.) for x in range(n + 1)]

                            # Price
                            result = engine.price(T=t, ntrials=NTRIALS)
                            if abs(result.price) < 1E-5:
                                continue
                            s = '{0},{1:.6g},{2:.6g},{3:.6g},{4:.6g},{5:.6g},{6},{7:.6g},{8},' \
                                '{9},{10},{11:.6g}\n'.format(
                                    idx, S, K, r, T, vol, right, B, b_updown,
                                    b_inout, bd, result.price
                                )
                            f.write(s)
                            idx += 1
                            idy += 1

                        # (i) Weekly barrier dates.
                        bd = 7
                        n = int(T * 365 // bd)
                        if n > 1:
                            t = [(x * bd / 365.) for x in range(n + 1)]

                            # Price
                            result = engine.price(T=t, ntrials=NTRIALS)
                            if abs(result.price) < 1E-5:
                                continue
                            s = '{0},{1:.6g},{2:.6g},{3:.6g},{4:.6g},{5:.6g},{6},{7:.6g},{8},' \
                                '{9},{10},{11:.6g}\n'.format(
                                    idx, S, K, r, T, vol, right, B, b_updown,
                                    b_inout, bd, result.price
                                )
                            f.write(s)
                            idx += 1
                            idy += 1


def main() -> None:
    random.seed(1)

    # Pricing Vanilla options
    # vanilla()

    # Pricing Asian options
    asian()

    # Pricing discrete barrier options
    # barrier()

    print('==================')
    print('Shivesh Mandalia https://shivesh.org/')
    print('==================')


main.__doc__ = __doc__


if __name__ == '__main__':
    main()