<jupyter_start><jupyter_text>Data Analysis: USDCAD Timeseries Analysis  This Project focuses on the Time Series analysis of USDCAD. Futhermore, how the price and return behavior of US 10 year Treasury bonds, Canadian 10 year treasury bonds and WTI Crude oil impact the returns of USDCAD. In this data analysis project, we download monthly data from FRED API and conduct multiple linear regression and regime switching analysis to determine if there any specific relationship between the variables and if so, how do they change over time? The motivation for this study is that the canadian dollar is known to be a commodity currency. The price of WTI crude oil and other commodities can greatly impact the canadian economy. In this analysis, we will explore if the monthly returns of crude oil have a significant impact on the price behavior of USDCAD. We will also add interest rates of 10 year bonds to improve the regression and just for fun.   Importing and cleaning of Timeseries Data<jupyter_code># Importing necessary packages for Canadian Dollar/Us Dollar Analysis 
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import pandas_datareader # To import FRED data
import datetime
from arch.unitroot import DFGLS, ADF, KPSS, PhillipsPerron # Downloaded package using 'pip install arch' for Stationarity tests
import statsmodels.formula.api as smf # For Multivariable OLS Regression
from statsmodels.regression.rolling import RollingOLS # For Rolling Regression
import statsmodels.api as sm
# a. Importing necessary data from FRED from January 1990 to April 2020
start = datetime.datetime(1990,1,1)
end = datetime.datetime(2020,4,1)
USDCAD = pandas_datareader.data.DataReader('DEXCAUS','fred', start, end) # USDCAD Exchange Rate
Oil = pandas_datareader.data.DataReader('DCOILWTICO','fred', start, end) # North American Crude Oil
UST = pandas_datareader.data.DataReader('DGS10','fred', start, end) # 10-year US Treasury yield 
CAT = pandas_datareader.data.DataReader('IRLTLT01CAM156N','fred', start, end) # 10-year Canadian Treasury yield
# b. Merging Dataframes
complete = pd.merge(CAT, Oil, left_index=True, right_index=True, how='left')
complete = pd.merge(complete, UST, left_index=True, right_index=True, how='left')
complete = pd.merge(complete, USDCAD, left_index=True, right_index=True, how='left')
# c. Renaming Variables and drop missing variables
Columnrename={'IRLTLT01CAM156N':'CAD_10_Year_Treasury', 'DCOILWTICO':'WTI_CRUDE','DGS10':'US_10_Year_Treasury','DEXCAUS':'USDCAD'}
complete.rename(columns = Columnrename, inplace=True)
complete = complete.dropna()
# d. Create new return variables 
Column_Variables=['CAD_10_Year_Treasury', 'WTI_CRUDE','US_10_Year_Treasury', 'USDCAD']

for columns in Column_Variables:
    complete[columns +'_pct'] = complete[columns].pct_change() # Percent change of each of the original variables 
complete = complete.dropna()
complete.head()<jupyter_output><empty_output><jupyter_text>Plotting  Variables<jupyter_code># a. Ploting the levels of each of our four variables
fig = plt.figure(figsize=(10,10))

plt.subplot(2,2,1)
complete['CAD_10_Year_Treasury'].plot(grid=True, title='Canadian 10 Year Treasury Yield')

plt.subplot(2,2,2)
complete['WTI_CRUDE'].plot(grid=True, title='WTI Crude Oil')

plt.subplot(2,2,3)
complete['US_10_Year_Treasury'].plot(grid=True, title ='US 10 Year Treasury Yield')

plt.subplot(2,2,4)
complete['USDCAD'].plot(grid=True, title='USDCAD Exchange Rate')

plt.subplots_adjust(wspace=.3, hspace=.3)<jupyter_output><empty_output><jupyter_text>Observing the 4 Charts above, there is some interesting time series behavior to note. Both Canadian and US Treasury yield follow a downward drifing behavior since the 1990. USDCAD and Crude oil have large variation in price, but one thing that is observable is that spikes in crude oil are also observable in USDCAD in some periods. This these similar behaviors persist when we observe the returns of each of our variables?<jupyter_code>fig = plt.figure(figsize=(10,10))

plt.subplot(2,2,1)
complete['CAD_10_Year_Treasury_pct'].plot(grid=True, title='Canadian 10 Year Treasury Yield')

plt.subplot(2,2,2)
complete['WTI_CRUDE_pct'].plot(grid=True, title='WTI Crude Oil')

plt.subplot(2,2,3)
complete['US_10_Year_Treasury_pct'].plot(grid=True, title ='US 10 Year Treasury Yield')

plt.subplot(2,2,4)
complete['USDCAD_pct'].plot(grid=True, title='USDCAD Exchange Rate')

plt.subplots_adjust(wspace=.3, hspace=.3)<jupyter_output><empty_output><jupyter_text>Observing the returns of all of our 4 variables since 1990 there are some interesting spikes in volatility. Spikes in volatilty of WTI Crude Oil tend to be in line with many of the spikes in volatility in USDCAD. Furthermore, it is observable in both the Canadian and US 10 year treasury yield that volatility in treasury bonds have increased dramatically since 2008.<jupyter_code>complete.describe()<jupyter_output><empty_output><jupyter_text>The table above is just for us to to observe the general statistics of our variables. The standard deviations of our return variables are most interesting because they show the difference in the volatility of each of our variables. Crude oil is a particularly volatile asset. This is not surprising as crude oil is a highly sensitive asset to a series of shocks. Geopolitical and economic shocks have made the price of crude oil range from under 20 dollars a barrel to a peak of over 140 dollars a barrel.   Data Analysis Now we have observed some interesting behavior in our variables. We will conduct multi-variable OLS regression and rolling window regression to see if our variables adjust over time, highlighting possible regime shifts that influnce USDCAD since the 1990s. Before conducting our regressions, it would be useful to construct a correlation matrix in order to observe if there are any interesting correlations.<jupyter_code># a. Correlation Matrix of our variables
complete.corr()<jupyter_output><empty_output><jupyter_text>Key Correlations to observe are:             1. CAD/US 10 Year Treasury Before and after making variable stationary              2. WTI Crude oil with CAD/USDOur level variables of CAD and US 10 year Treasury bond yields appear to have very high positive correlation of 0.97. However, once we convert these variables to their percent change then the relationship drops down to 0.63. This is still a strong relationship, but it is expected that the downward trend over time that both of the variables experienced make the correlation appear stronger that it actually is. Our level variables of WTI Crude and USDCAD show a strong negative correlation of -0.78. This makes us hopeful to find a statistically significant effect of WTI Crude oil returns on the returns of USDCAD. Furthermore, it is not surprising that the correlation is negative. As the price of crude oil increases, this helps support the canadian GDP and thus would make the Candian dollar appreciate over the US Dollar holding all other variables constant.<jupyter_code>Next, we will conduct a regression on how US 10 year treasury yield, Canadian 10 year treasury yield and Crude oil returns impact the returns on CAD/USD. However, it is essential to check that our manipulated variables are now stationariy prior to conducting our regression. we confirm that the new percent change variables are stationary with a Augmented Dickey-Fuller Test<jupyter_output><empty_output><jupyter_text>b. Conduct Stationary test via Augmented Dickey fuller test  Create function to test for stationarity def stationarity_test(df):    '''    Determines if series from a dataframe is stationary by conducting a unit root test, the augmented dickey fuller test.        Arguments:    df(series): series to be tested for stationarity         Returns: if series is stationary or not and if stationary with what level of significance.    '''        result = ADF(df)        if abs(result.stat) > abs(result.critical_values['5%']) and abs(result.stat) < abs(result.critical_values['1%']):        x ='Stationary with 5% level of significance'    elif abs(result.stat) > abs(result.critical_values['1%']):        x='Stationary with 1% level of significance'    else:        x='Non-Stationary'        return x  Test for Stationarity for all of our variablesupdated_list=['CAD_10_Year_Treasury_pct', 'WTI_CRUDE_pct','US_10_Year_Treasury_pct','USDCAD_pct']old_list=['CAD_10_Year_Treasury', 'WTI_CRUDE','US_10_Year_Treasury','USDCAD']for columns in old_list:    print(columns+':'+stationarity_test(complete[columns]))for columns in updated_list:    print(columns+':'+stationarity_test(complete[columns]))<jupyter_code>We can conclude that $\underline{ALL}$ of our time series variables converted to percent returns surpass the 1% critical value of possessing a unit root. Therefore, we can assume stationarity and proceed with a multivariable regression.<jupyter_output><empty_output><jupyter_text>c. Conduct Multivariable OLS Regressionformula = 'USDCAD_pct ~ CAD_10_Year_Treasury_pct + US_10_Year_Treasury_pct + WTI_CRUDE_pct'results = smf.ols(formula, complete).fit()print(results.summary())<jupyter_code>From our first regression, we discover that Canadian 10 year treasury yield percent returns and WTI crude oil percent returns are highly significant both surpassing the 5% critical level. However, US 10 year treasury yields appear to have no significant effect on USDCAD returns. Furthermore, the sign of our signifiant coeffecients both are negative. This makes logical sense from theory and expectations. As Canadian interest rates rise holding all other variables constant, there will be more capital flows into Canada causing an appeciation of the Canadian dollar. As crude oil prices increases, the large oil sector of the canadian economy will profit from increased prices causing larger GDP growth. As output increases in Canada, this will result in higher money demand causing the canadian dollar to appreciate. It is surprising that the US 10 year treasury yield has no significant impact on USDCAD returns. This requires more study.<jupyter_output><empty_output><jupyter_text>formula = 'USDCAD_pct ~ CAD_10_Year_Treasury_pct+ WTI_CRUDE_pct'results = smf.ols(formula, complete).fit()print(results.summary())<jupyter_code>We redid the OLS regression removing our insiginificant variable. This pushed all of our variables to surpass the 1% level of significance and improved our adjusted r-squared. One important thing to note from our regression is that even though are remaining variables are highly significant, they only account for 17.3 percent of the variation in USDCAD returns. This OLS regression has lots of room for improvements.<jupyter_output><empty_output><jupyter_text>d. Conducting a rolling regression endog = complete['USDCAD_pct']  Endogenous Variable-USDCAD Returnexog_vars = ['CAD_10_Year_Treasury_pct', 'WTI_CRUDE_pct']  Our remaining significant exogenous variablesexog = sm.add_constant(complete[exog_vars])rols = RollingOLS(endog, exog, window=60)  Conduct Rolling windowed OLS regression with a window lenght of 60 months rres = rols.fit()fig = rres.plot_recursive_coefficient(variables=exog_vars, figsize=(14,18))<jupyter_code>From our rolling windowed OLS regression, we find that that there are variations in the coeffcients of WTI crude oil returns and Canadian 10 year treasury bond yield returns. The effect of canadian treasuries once had a depreciative effect on the Candian dollar, but over time had a stonger appreciative effect until 2010. After 2010 the appreciative effect on the Canadian dollar started to weaken. 

Since 1990, it appears that positive returns in crude oil have an appreciative effect on the Canadian dollar, but there is a clear regime shift in 2008 and 2016. In 2008, the appreciative effects of positive crude oil returns increased dramatically. This was when the crude oil market bubble popped during the great recession causing a dramatic drop in the price of crude oil. If we observe the level graphs earlier. The large drop in crude oil prices coincided with a large depreciation of the Canadian dollar. In 2016, there appears to be another regime shift, where the effect of crude oil returns on USDCAD returns starts to weaken. The cause of this regime shift is uncertain.<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.06339683826509931, 'fraction_numerical': 0.017754357519254155, 'mean_word_length': 5.715296679368536, 'pattern_counts': {'":': 0, '<': 42, '<?xml version=': 0, '>': 43, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '545519', 'license': 'MIT', 'n_tokens_mistral': 3604, 'n_tokens_neox': 3261, 'n_words': 1498, 'path': 'dataproject/TimeSeries_Analysis.ipynb', 'repo_name': 'NumEconCopenhagen/projects-2020-international', 'size': '12335'}