Treasury Data

Overview

The treasury data script is designed to pull treasury yield data from the US Treasury Site.

Usage

import treasury as ty #pull the yields for the most recently reported date current = ty.current() #pull the data for 2026 y2026,stacked2026 = ty.get('2026') #pull multiple years of data data, stacked = ty.get(['2025', '2026']) #get all the years available all, all_stacked = ty.get('all')

Configuration

The treasury script utilizes the standard davinci data framework, including using the cache function to retrieve and cache the data. For any year that is prior to the current year, the file is downloaded once and cached. If the current year is the same as the year being requested, you can specify how long to hold the currently cached file in the .env file.

Specify the amount of time to hold the file by providing a value for "expires-treasury". The numeric value is the number of seconds to hold the file. (86400 is a single day)

expires-treasury=86400

Full Script

from datetime import date, timedelta, datetime import requests import xml.etree.ElementTree as ET from pathlib import Path import pandas as pd from dotenv import load_dotenv import os import davinci.python as py from dotenv import load_dotenv load_dotenv() # expires = os.getenv('expires-treasury') if expires != None:expires = int(expires) ''' Returns an object representing the most recent yields ''' def current(): today_iso = date.today().isoformat() year = today_iso.split('-')[0] flat,_ = get(year) return flat[len(flat)-1] # get all years in a single dataset def get_all(): update() flat = [] stacked = [] files = [f for f in Path(root).iterdir() if f.is_file()] for file in files : content = file.read_text(encoding="utf-8") flat1, stacked1 = process(content) for item in flat1:flat.append(item) for item in stacked1:stacked.append(item) pass return flat, stacked def get_years(): current_year = date.today().year return list(range(1990, current_year)) ''' get takes a single parameter which can be either a list of years a year denoted as a string the string 'all' ''' def get(years): global root flat = [] stacked = [] if isinstance(years, int): years = str(years) if years == 'all': years = get_years() if isinstance(years, str): flat1, stacked1 = retrieve(years) return flat1, stacked1 else: for year in years: flat1, stacked1 = get(year) for item in flat1:flat.append(item) for item in stacked1:stacked.append(item) pass return flat, stacked def process(xml): root = ET.fromstring(xml) date = None stacked = [] flat = [] record = None for elem in root.iter(): tag = elem.tag if 'NEW_DATE' in tag: date = elem.text.split('T')[0] record = {"date":date} flat.append(record) if 'BC_' in tag and 'YEARDISPLAY' not in tag: tagname = tag[tag.find('}')+1:] tagname = tagname.replace('BC_','').replace('YEAR','Y').replace('MONTH','M').replace('_','.') record[tagname] = float(elem.text) record2 = {"date":date} record2['value'] = float(elem.text) record2['period'] = tagname if 'Y' in tagname:record2['time'] = int(tagname[:-1]) else: record2['time'] = float(tagname[:-1])/12 stacked.append(record2) pass return flat, stacked #downloads the file from the treasury website #if save is set to true, it will save it as a local file def retrieve(year, save=True): global root url = 'https://home.treasury.gov/resource-center/data-chart-center/interest-rates/pages/xml?data=daily_treasury_yield_curve&field_tdr_date_value='+str(year) #if the year being requested is not the current year, then do not redownload it, it will not be updated #otherwise, default to the standard expires framework today_iso = date.today().isoformat() cyear = today_iso.split('-')[0] cexpires = expires if cyear!=year:cexpires = None xml = py.cache(url,expires=cexpires) '''with open(root+'treasury/'+year+".txt", "w", encoding="utf-8") as file: file.write(response.text)''' flat, stacked = process(xml) return flat, stacked