6
\$\begingroup\$

I think I have this working, but I'm not sure it's completely accurate.

I'm trying to parse Option Symbols. An Option Symbol is made up of 4 parts:

  1. Root Symbol (up to 6 characters)
  2. Expiration Date (yymmdd)
  3. Option Type (1 character)
  4. Strike price (8 digits)

After parsing the following examples, the results should be as follows:

  1. C020216P00035000

    • Root Symbol ='C'
    • Expiration Date = datetime.date(2002, 2, 16)
    • Option Type = P
    • Strike Price = int(00035000) x .001 = 35.00
  2. P020216C00040000

    • Root Symbol = 'P'
    • Expiration Date = datetime.date(2002, 2, 16)
    • Option Type = C
    • Strike Price = int(00040000) x .001 = 40.00
  3. SBC020216C00030000

    • Root Symbol = 'SBC'
    • Expiration Date = datetime.date(2002, 2, 16)
    • Option Type = C
    • Strike Price = int(00030000) x .001 = 30.00

I'm using the following code:

import re
import datetime as dt

opra_symbol = re.compile(r'(^[^0-9]+)').search(OPRA).group()

opra_expiry = dt.datetime.strptime(re.compile(r'\d{2}\d{2}\d{2}').search(OPRA).group(), '%y%m%d').date()

opra_cp = re.compile(r'([CP])').search(re.compile(r'([CP]\d+$)').search(OPRA).group()).group()

opra_price = int(re.compile(r'(\d+)$').search(OPRA).group()) * .001

Is this the best way of getting my results? I'm mostly concerned with the nested regex expression for the Option Type.

\$\endgroup\$

migrated from stackoverflow.com Feb 24 '16 at 21:30

This question came from our site for professional and enthusiast programmers.

4
\$\begingroup\$

You say the date, option type and price are all fixed length fields, so you can do:

opra_symbol = OPRA[:-15]

opra_expiry = dt.datetime.strptime(OPRA[-15:-9]).date()

opra_cp = OPRA[-9]

opra_price = int(OPRA[-8:]) * .001
\$\endgroup\$
  • 1
    \$\begingroup\$ of course. thanks. by the way, I changed opra_expiry line to opra_expiry = dt.datetime.strptime(OPRA[-15:-9], '%y%m%d').date() \$\endgroup\$ – vlmercado Feb 25 '16 at 4:52
4
\$\begingroup\$

It looks like you can simplify it to the single regex:

    matcher = re.compile(r'^(.+)([0-9]{6})([PC])([0-9]+)$')
    groups = matcher.search(option)

Then symbol, expiry, type and price are in groups[0], groups[1], groups[2] and groups[3] respectively. The expiry is guaranteed to be in yymmdd format, hence the {6} qualifier. You may want to add a {8} length qualifier to the price.

\$\endgroup\$
  • \$\begingroup\$ That looks great. I couldn't get groups[n] to work, however. I got groups.group(n) to work. I don't know if it matters, but please let me know if I'm missing something. Thanks for your help. \$\endgroup\$ – vlmercado Feb 25 '16 at 2:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.