aboutsummaryrefslogtreecommitdiffstats
path: root/python/yieldcurve.py
blob: 97b811e9e543632d8c99ac4df91285c1ece1e7bc (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
from common import root
import os
import requests, zipfile
from io import BytesIO
import xml.etree.ElementTree as ET
import datetime
from quantlib.settings import Settings
from quantlib.time.api import (WeekendsOnly, Date, Period, Days, Schedule, Annual,
                               Semiannual, today, Actual360, Months, ModifiedFollowing,
                               Thirty360, Actual365Fixed, calendar_from_name)
from quantlib.currency.api import USDCurrency, EURCurrency
from quantlib.indexes.ibor_index import IborIndex
from quantlib.termstructures.yields.api import (
    PiecewiseYieldCurve, DepositRateHelper, SwapRateHelper)
from quantlib.time.date import pydate_from_qldate

import numpy as np
import matplotlib.pyplot as plt
from quantlib.quotes import SimpleQuote

def getMarkitIRData(date = datetime.date.today(), currency="USD"):
    basedir = os.path.join(root, "data", "Yield Curves")
    filename = "InterestRates_{0}_{1:%Y%m%d}".format(currency, date)
    if not os.path.exists(os.path.join(basedir, filename + '.xml')):
        r = requests.get('http://www.markit.com/news/{0}.zip'.format(filename))
        if "x-zip" in r.headers['content-type']:
            with zipfile.ZipFile(BytesIO(r.content)) as z:
                z.extractall(path = os.path.join(root, "data", "Yield Curves"))
        else:
            return getMarkitIRData(date-datetime.timedelta(days=1))

    tree = ET.parse(os.path.join(root, "data", "Yield Curves", filename + '.xml'))
    deposits = {tenor: rate for tenor, rate in \
                zip([e.text for e in tree.findall('./deposits/*/tenor')],
                    [float(e.text) for e in tree.findall('./deposits/*/parrate')])}
    swaps = {tenor: rate for tenor, rate in \
             zip([e.text for e in tree.findall('./swaps/*/tenor')],
                 [float(e.text) for e in tree.findall('./swaps/*/parrate')])}
    effectiveasof = tree.find('./effectiveasof').text
    MarkitData = {'deposits': deposits,
                  'swaps': swaps,
                  'effectiveasof': datetime.datetime.strptime(effectiveasof, "%Y-%m-%d").date()}
    return MarkitData

def get_futures_data(date = datetime.date.today()):
    futures_file = os.path.join(root, "data", "Yield Curves",
                                "futures-{0:%Y-%m-%d}.csv".format(date))
    with open(futures_file) as fh:
        quotes = [float(line.split(",")[1]) for line in fh]
    return quotes

def rate_helpers(currency="USD", MarkitData=None):
    settings = Settings()
    if not MarkitData:
        MarkitData = getMarkitIRData(pydate_from_qldate(settings.evaluation_date-1), currency)
        if MarkitData['effectiveasof'] != pydate_from_qldate(settings.evaluation_date):
            raise RuntimeError("Yield curve effective date: {0} doesn't " \
                               "match the evaluation date: {1}".format(
                                   MarkitData['effectiveasof'],
                                   qldate_to_pydate(settings.evaluation_date)))
    calendar = WeekendsOnly()
    if currency == "USD":
        isda_ibor = IborIndex("IsdaIbor", Period(3, Months), 2, USDCurrency(), calendar,
                              ModifiedFollowing, False, Actual360())
        fix_freq = Semiannual
    elif currency == "EUR":
        isda_ibor = IborIndex("IsdaIbor", Period(6, Months), 2, EURCurrency(), calendar,
                              ModifiedFollowing, False, Actual360())
        fix_freq = Annual
    deps = [DepositRateHelper(q, Period(t), 2, calendar, ModifiedFollowing, False, Actual360())
            for t, q in MarkitData['deposits'].items()]
    swaps = [SwapRateHelper.from_tenor(q, Period(t), calendar, fix_freq, ModifiedFollowing,
                                       Thirty360(), isda_ibor) for t, q in MarkitData['swaps'].items()]
    return deps + swaps

def YC(currency="USD", MarkitData=None):
    settings = Settings()
    helpers = rate_helpers(currency, MarkitData)
    curve = PiecewiseYieldCurve("discount", "loglinear", settings.evaluation_date,
                                helpers, Actual365Fixed())
    return curve

if __name__=="__main__":
    #evaluation_date = Date(29, 4, 2014)
    Settings.instance().evaluation_date = today()
    ts = YC()
    cal = calendar_from_name('USA')
    p1 = Period('1Mo')
    p2 = Period('2Mo')
    p3 = Period('3Mo')
    p6 = Period('6Mo')
    p12 = Period('12Mo')
    sched = Schedule(ts.reference_date, ts.reference_date+Period('5Yr'), Period('3Mo'), cal)
    days = [pydate_from_qldate(d) for d in sched]
    f3 = [ts.forward_rate(d, d+p3, Actual360(), 0).rate for d in sched]
    f6 = [ts.forward_rate(d, d+p6, Actual360(), 0).rate for d in sched]
    f2 = [ts.forward_rate(d, d+p2, Actual360(), 0).rate for d in sched]

    plt.plot(days, f2, days, f3, days, f6)