2
$\begingroup$

How can I get an IMM date from its 2 character symbol (eg. "U6", "Z8") in python?

I have not been able to install the quantlib addin (it's hard if you aren't tech savy), so please don't point me in that direction..

$\endgroup$
5
$\begingroup$

This does the trick. Given "U8", function will get the IMM date for Sep 2018. Given "U4", function gets the IMM date for Sep 2024 (or it will until we've passed that date). Could be easily modified to also pull historical IMMs from a given longer symbol eg. "U2014".

def getIMMDate(IMMcode):

'''Takes 2 digit IMM code and returns effective date as datetime object'''
from datetime import datetime, timedelta

monthcodes = [[1, 'F'], [2, 'G'], [3, 'H'], [4, 'J'], [5, 'K'], [6, 'M'], [7, 'N'], [8, 'Q'],
              [9, 'U'], [10, 'V'], [11, 'X'], [12, 'Z']]
month = [pair[0] for pair in monthcodes if pair[1] == IMMcode[0].upper()][0]

year_prefix = str(datetime.now().year)[:3]
year = int(year_prefix + IMMcode[1])

the_date = datetime(year, month, 1)
temp = the_date.replace(day=1)
nth_week = 3
week_day = 2
adj = (week_day - temp.weekday()) % 7
temp += timedelta(days=adj)
temp += timedelta(weeks=nth_week - 1)

if temp < datetime.now():
    year_prefix = str(int(str(datetime.now().year)[:3]) + 1)
    year = int(year_prefix + IMMcode[1])

    the_date = datetime(year, month, 1)
    temp = the_date.replace(day=1)
    nth_week = 3
    week_day = 2
    adj = (week_day - temp.weekday()) % 7
    temp += timedelta(days=adj)
    temp += timedelta(weeks=nth_week - 1)

return datetime.strftime(temp, "%m/%d/%Y")
$\endgroup$
  • $\begingroup$ I would calculate the month and day first assuming it is the current year. then check to see if that date > today(). If not, add one to the current year and recalculate the month/day. This will also get rid of that hardcoded 202 and 201 which could cause bugs not too far in the future. $\endgroup$ – rhaskett Sep 25 '15 at 18:42
  • $\begingroup$ Appreciate the guidance @rhaskett. Could probably find some fancy recursive solution, but this clunky if statement works fine. $\endgroup$ – rvictordelta Dec 17 '15 at 17:48

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.