I'm trying to build a code that will trade based off when the 6 mo treasury yield crosses below the 30 yr treasury yield. My approach to this is essentially, if the 6 mo yield was greater than the 30 yr yield x days ago, and currently the 6 mo yield is below the 30 yr yield, then at some point in the past x days the 6 mo yield must have crossed below the 30 yr yield. It is important that I screen for a yield cross this way, because I am not simply trying to code my algo such that it buys when 6_mo_yield < 30_yr_yield and sells when 6_mo_yield > 30_yr_yield.
So far I've correctly set up fetch_csv to get the yields from quandl, and can calculate the current difference between the 6mo and 30yr yields:
def initialize(context):
fetch_csv('https://www.quandl.com/api/v3/datasets/USTREASURY/YIELD.csv?api_key=NzSb-s_fRzPMBMHauhbS', date_column='Date', date_format='%m-%d-%Y', symbol='TSRY', usecols=['6 MO', '30 YR'])
def handle_data(context, data):
# current yields
6_mo_yield = data.current('TSRY', '6 MO')
30_yr_yield = data.current('TSRY', '30 YR')
difference = 6_mo_yield - 30_yr_yield
record(difference=difference)
My problem comes when I try to use my csv columns with data.history. I've searched around and found multiple posts on working around not being able to use data.history with fetch_csv. As a beginner to python, I'm instead trying my hand at what seems like should be a simpler workaround. My work around is that I simply rename my columns '6 MO' and '30 YR' as 'price' and 'open', respectively, since data.history will only accept inputs like 'price', 'open', 'close', etc. My code for this is as follows:
def initialize(context):
fetch_csv('https://www.quandl.com/api/v3/datasets/USTREASURY/YIELD.csv?api_key=NzSb-s_fRzPMBMHauhbS', date_column='Date', date_format='%m-%d-%Y', symbol='TSRY', usecols=['6 MO', '30 YR'])
def post_func(df):
df = df.rename(columns={'6 MO': 'price', '30 YR': 'open'})
return df
def handle_data(context, data):
# current yields
6_mo_yield = data.current('TSRY', 'price')
30_yr_yield = data.current('TSRY', 'open')
6_mo_yield_old = data.history('TSRY', 'price', 5, '1d')[:-4]
30_yr_yield_old = data.history('TSRY', 'open', 5, '1d')[:-4]
difference = 6_mo_yield - 30_yr_yield
difference_old = 6_mo_yield_old - 30_yr_yield_old
context.cross_down = difference < 0 and difference_old > 0
record(difference=difference)
record(difference_old=difference_old)
When I run this code I get back the error:
"ValueError: invalid literal for int() with base 10: 'Y'"
which I've deduced has something to do with the values for the 6 mo yield and 30 yr yield I'm plugging into data.history. But I've searched all over and can't figure this one out. What exactly does this error mean? And is there a way to solve the problem so that I can use my csv data in data.history?