#!/usr/bin/env python # coding: utf-8 # # Euros vs. Dollars: Covid Times # **An quick analysis of the EUR-USD exchage rates from 2016-21** # # Index # - [1 Introduction](#1) # - [2 Reading the Data](#2) # - [3 Euro vs. Dollar!](#3) # - [4 Conclusions](#4) # # 1 # ## Introduction # ![image.png](attachment:image.png) # *Source*: [FXEMPIRE](https://www.fxempire.com/forecasts/article/eurusd-weekly-fundamental-analysis-april-28-may-2-2014-forecast-192372) # The foreign exchange market or [Forex](https://www.investopedia.com/articles/forex/11/why-trade-forex.asp) allows in trading foreign currency. Unlike the stock market where shares can be brought and sold, the forex requires buying one currency in exchange of another. Depending on how much a currency is exchanged for, one could make or lose money in the foreign exchange market. e.g. If the EUR-USD curreny rate is 1.5, it means that for every 1 Euro someone doing the exchange would get US$1.5 # # Like the stock market the Forex is subject to market risks. Issues in a country or other parameters like inflation can cause the value of a currency to fall. Covid-19 was one such crisis that affected Forex markets worldwide. # # In this project we are going to do a quick analysis of the impact of Covid on EUR-USD exchange rate. # The goal will be to: # - Compare how the EUR-USD exchange rate was affected by Covid-19 versus its trends before the crisis hit. # - Create a plot that encompasses the entire history of the trends. # [Index](#Index) # # 2 # ## Reading the Data # The data for the EU exchange rates for the period 1999-2021 is provided by Daria Chemkaeva who put together the data set and made it available on [Kaggle](https://www.kaggle.com/lsind18/euro-exchange-daily-rates-19992020). The dataset is regularly updated. The dataset used for this project was downloaded on January 2021. # # We shall assess the data below. # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') import pandas as pd import matplotlib.pyplot as plt exchange_rates = pd.read_csv('euro-daily-hist_1999_2020.csv') exchange_rates # In[2]: exchange_rates.info() # The dataset seems to have the following issues: # - The column names are inconsistent to the Python standards and need correction. # - The date column is a string. Converting it to DateTime data type would make analysis easier. # - A number of columns have null data which will be individually corrected based on the currencies we will be evaluating. # - Some columns have the string data type while others are of type float. This will be corrected on a need-only basis. # # We shall rename the columns and correct the date column to make them more consistent. # In[3]: #Clean the column names exchange_rates.rename(columns = {"Period\\Unit:":"dates"},inplace = True) exchange_rates.columns = exchange_rates.columns.str.replace(' ', '_') #Remove square brackets exchange_rates.columns = exchange_rates.columns.str.replace('[\[\]]','',regex=True).str.lower() #Remove the last underscore from column names exchange_rates.columns = exchange_rates.columns.str[:-1] exchange_rates.columns # In[4]: #Set the date column to datetime format exchange_rates['date']= pd.to_datetime(exchange_rates['date']) exchange_rates.sort_values('date', inplace=True) exchange_rates.reset_index(drop=True, inplace=True) exchange_rates # [Index](#Index) # # 3 # ## Euro vs. Dollar! # **Analysing the EUR-USD exchange rate** # Now that we have a cleaner dataset we can begin analysis on the EUR-USD exchange rates for the period between 2016-2021. We would have to begin by first analysing the dataset itself as it was observed to have a number of null values. Besides the null values we may also need to remove any invalid values as well. # In[5]: exchange_rates['us_dollar'].value_counts() # There are 62 data points for which the exchange rate value is a hyphen(-) which will need to be removed. # In[6]: #Consolidate and clean the us_dollar column euro_dollar = exchange_rates.loc[:,['date','us_dollar']] #Consider only datapoints with no hyphen euro_dollar = euro_dollar[euro_dollar['us_dollar'] != '-' ].copy() euro_dollar['us_dollar'] = euro_dollar['us_dollar'].astype('float') euro_dollar.info() # The EUR-USD exchange rates are cleaner. The data in the dataset is for daily exchange rates. Our assessment is based on a long term view of about five years. Taking this in to consideration we shall calculate the mean value for each day based on the [rolling average](https://www.portent.com/blog/analytics/rolling-averages-math-moron.htm) method with a rolling window of 90 days. # # Based on this we could also plot the exchange rate movement over the above mentioned period. # In[7]: #Calculate the rolling mean by setting the rolling window = 90 days (Quarterly) euro_dollar['rolling_mean'] = euro_dollar['us_dollar'].rolling(90).mean() #Calculate the min and max for each year euro_dollar['year'] = euro_dollar['date'].dt.year # In[8]: #Calculate the rolling mean by setting the rolling window = 90 days (Quarterly) euro_dollar['rolling_mean'] = euro_dollar['us_dollar'].rolling(90).mean() euro_dollar = euro_dollar[euro_dollar['date'].dt.year.between(2016,2021)] #Set the layout fig,ax = plt.subplots(figsize = (9,5)) plt.style.use('seaborn-whitegrid') plt.title("EU-US exchange rates between 2016-2021") for each_spine in ["top",'bottom','right','left']: ax.spines[each_spine].set_visible(False) ax.tick_params(left=False, bottom = False) #Plot the graph ax.plot(euro_dollar['date'],euro_dollar['rolling_mean']) #Demarcate the Pre-Covid and Covid era ax.axvline(x = pd.Timestamp('2020-01-01'), ymin = 0.01, linestyle = 'dashed', alpha = 0.5) plt.show() # Now that we have a clearer picture of the exchange rate movement over the period specified, we can analyse the impact of Covid-19 on the the same. # In[9]: #Capture the min and max values of exchanges rates over the 5 year period df = pd.DataFrame(columns = ['mini','mini_date','maxa','maxa_date'], index = [2016,2017,2018,2019,2020]) for each_year in df.index: mini = euro_dollar[(euro_dollar['date'].dt.year==each_year)]['rolling_mean'].min() mini_date = euro_dollar[(euro_dollar['date'].dt.year==each_year) & (euro_dollar['rolling_mean']== mini)]['date'].iloc[0] maxa = euro_dollar[(euro_dollar['date'].dt.year==each_year)]['rolling_mean'].max() maxa_date = euro_dollar[(euro_dollar['date'].dt.year==each_year) & (euro_dollar['rolling_mean']== maxa)]['date'].iloc[0] df.loc[each_year] = [mini,mini_date,maxa,maxa_date] mean = round(euro_dollar[(euro_dollar['date'].dt.year.between(2016,2021))]['rolling_mean'].mean(),4) # In[12]: fig,((ax1,ax2,ax3,ax4,ax5,ax6)) = plt.subplots(nrows = 6, ncols = 1, figsize = (17,14)) ax = [ax1,ax2,ax3,ax4,ax5,ax6] #Set dates for vertical lines x_dates = ['2015-12-10','2016-12-10','2017-12-10','2018-12-10','2019-12-10','2020-12-10'] #Set color scheme colormin = '#ffff00' colormax = '#00ffbf' colorplot = '#ff0000' covmin = '#ff4d4d' covmax = '#e60000' covplot = '#00ff00' v_color = '#8000ff' h_color = '#1a0000' #Create the default plots plt.style.use('fivethirtyeight') for each_ax in ax: for each_spine in ["top",'bottom','right','left']: each_ax.spines[each_spine].set_visible(False) each_ax.tick_params(left = False, bottom = False, labelbottom = False, labelleft = False) each_ax.grid(b=None) each_ax.set_ylabel(None) each_ax.set_xlabel(None) each_ax.plot(euro_dollar['date'],euro_dollar['rolling_mean'], alpha = 0.1, color = covplot) #Set start and end dates for each plot start_date = ['2016-01-01','2017-01-01','2018-01-01','2019-01-01','2020-01-01'] end_date = ['2016-12-31','2017-12-31','2018-12-31','2019-12-31','2020-12-31'] #Set arrow and box for annotations arrowmin = dict(arrowstyle="wedge,tail_width=0.5", alpha=0.7, color=colormin) arrowmax = dict(arrowstyle="wedge,tail_width=0.5", alpha=0.7, color=colormax) arrowmin_cov = dict(arrowstyle="wedge,tail_width=0.5", alpha=0.7, color=covmin) arrowmax_cov = dict(arrowstyle="wedge,tail_width=0.5", alpha=0.7, color=covmax) bboxmin=dict(boxstyle="round", alpha=0.8, color=colormin) bboxmax=dict(boxstyle="round", alpha=0.8, color=colormax) bboxmin_cov=dict(boxstyle="round", alpha=0.8, color=covmin) bboxmax_cov=dict(boxstyle="round", alpha=0.8, color=covmax) #Draw plot for individual periods for i,each_ax in zip(range(5),ax[:5]): if i==0: #Title each_ax.text(s = 'EURO-USD Rates were above Above Average during Covid-19', x = pd.Timestamp('2015-10-10'), y = 1.38, size=22, weight='bold') #Sub-title each_ax.text(s = 'The best and the worst of the EURO-USD exchange rate for every year between 2016-2021', x = pd.Timestamp('2015-10-10'), y = 1.32, size=18) #Extract data related to each year timeline = euro_dollar[(euro_dollar['date']>=start_date[i]) & (euro_dollar['date']<=end_date[i])][['date','rolling_mean']] #Plot data each_ax.plot(timeline['date'],timeline['rolling_mean'], color = covplot if i<4 else colorplot,linewidth=3.5) #Specify the timeline on the plot each_ax.axvline(x = pd.Timestamp(start_date[i]), ymax=0.95, color = v_color, linestyle = 'dashed', alpha = 0.5) each_ax.text(x = pd.Timestamp(x_dates[i]),y = 1.24, s = str(pd.Timestamp(start_date[i]).year), font = "fantasy", size='x-large', weight='bold') each_ax.text(x = pd.Timestamp(x_dates[i+1]),y = 1.24, s = str(pd.Timestamp(start_date[i]).year+1), font = "fantasy", size='x-large',weight='bold') each_ax.axvline(x = pd.Timestamp(end_date[i]), ymax=0.95, linestyle = 'dashed', color = v_color, alpha = 0.5) #Annotate the min rates each_ax.annotate(text = str(round(df.iloc[i]['mini'],4)), xy = (df.iloc[i]['mini_date'],df.iloc[i]['mini']), xytext = (df.iloc[i]['mini_date']+pd.Timedelta(90, unit = 'D'), df.iloc[i]['mini']), va="center", arrowprops=arrowmin if i<4 else arrowmin_cov, bbox = bboxmin if i<4 else bboxmin_cov,size = 13) #Annotate the max rates each_ax.annotate(text = str(round(df.iloc[i]['maxa'],4)), xy = (df.iloc[i]['maxa_date'],df.iloc[i]['maxa']), xytext = (df.iloc[i]['maxa_date']+pd.Timedelta(90, unit = 'D'), df.iloc[i]['maxa']), va="center", arrowprops=arrowmax if i<4 else arrowmax_cov, bbox = bboxmax if i<4 else bboxmax_cov, size = 13) #Summary plot timeline1 = euro_dollar[(euro_dollar['date']>=start_date[0]) & (euro_dollar['date']<=end_date[4])][['date','rolling_mean']] timeline2 = euro_dollar[(euro_dollar['date']>=start_date[-1]) & (euro_dollar['date']<=end_date[-1])][['date','rolling_mean']] #Pre-Covid plot ax6.plot(timeline1['date'],timeline1['rolling_mean'], color = covplot,linewidth=3.5) #Covid Plot ax6.plot(timeline2['date'],timeline2['rolling_mean'], color = colorplot, linewidth=3.5) #2016 v.line ax6.axvline(x = pd.Timestamp(start_date[0]), ymax=0.95, color = v_color, alpha = 0.5) #2016 Text ax6.text(x = pd.Timestamp(x_dates[0]),y = 1.24, s = '2016', font = "fantasy", size='x-large', weight = 'bold') #Pre-Covid title ax6.text(x = pd.Timestamp(x_dates[2]),y = 1.24, s = 'Pre-Covid', font = 'monospace', size = 22, alpha = 0.5) #2020 Text ax6.text(x = pd.Timestamp(x_dates[4]),y = 1.24, s = '2020', font = "fantasy", size='x-large', weight = 'bold') #Covid title ax6.text(x = pd.Timestamp('2020-5-3'),y = 1.24, s = 'Covid', font = 'monospace', size = 22, alpha = 0.5) #2021 Text ax6.text(x = pd.Timestamp(x_dates[5]),y = 1.24, s = '2021', font = "fantasy", size='x-large', weight = 'bold') #2021 v.line ax6.axvline(x = pd.Timestamp(end_date[-1]), ymax=0.95, color = v_color, alpha = 0.5) #Comparison h.line #df.loc[2020]['maxa'] ax6.axhline(y = mean,xmin=0.04,xmax=0.95, linestyle = 'dashed', color = h_color, alpha = 0.6) #Tick settings ax6.tick_params(bottom = False,left = True, labelleft = True, labelsize = 'large') #df.loc[2020]['maxa'] ax6.set_yticks([round(mean,4)]) #Signature ax6.text(x = pd.Timestamp('2015-6-1'), y = 1.01, s = '©maX'+ ' ' * 265 + 'Source: European Central Bank', color = '#f0f0f0', backgroundcolor = '#4d4d4d', size=13) plt.tight_layout(h_pad = 2) plt.show() # In[11]: print('\033[4m'+'\033[1m'+'Yearly Ups and Downs in the EUR-USD exchange rate'+'\033[0m') print(df,'\n') print('\033[1m'+'Mean Exchange Rate for 2016-21 period is {}'.format(mean)+'\033[0m') # Since the averages calculated for each year are based on rolling averages for each quarter, it would be incorrect to postulate the reasons behind the highs and lows on individual events for each year. # # Instead what can be observed is the yearly trends in the exchange market over the period of five years. Clearly from 2016-18 the exchange rate was below the five year average. However, it started picking up after it hit its lowest in 2018. # # By late May 2018 a downward trend began which uniformly continued till late May 2020. Considering how serious the pandemic is, its surprising to see the exchange rate picked up despite the nearly two year decline. # # There are multiple [factors](https://canamcurrencyexchange.com/9-factors-that-influence-currency-exchange-rates/) that affect the exchange rates of any currency market like GDP, inflation etc. Analysing each of these for the given periods are out of the scope of this project. # [Index](#Index) # # 4 # ## Conclusion # The foreign exchange market allows investors to make money by exchanging currency. In this project we analysed the changing trends of the EUR-US exchange rate over the course of five years and attempted to analyse the impact of Covid. # # It was interesting to note that despite the pandemic the EUR-USD exchange rate bounced back above the five year average after a steady two year slump. We have not analysed the reason behind the same as the exchange rates are affected by a number of parameters that require their own individual analysis over the same period. # # In addition, we were able to come up with a plot that clearly evaluates the trends in the EUR-USD exchange over the period of five years from 2016-2021. # [Index](#Index) # # 5 # ## Learnings # Learning: # - [Setting axvline for time data: ](http://5.9.10.113/66127918/adding-a-verticle-line-using-axvline-in-matplotlib-based-on-datetime-data) # - [When setting subplots with multiple columns using ax:](https://stackoverflow.com/questions/51736396/subplots-in-matplotlib-give-valueerror-not-enough-values-to-unpack) # - [Daily Fundamental Forcast USD-EUR reports](https://www.fxempire.com/forecasts/article/eurgbp-weekly-fundamental-analysis-december-29-january-2-2015-forecast-241481) # - [Diff. between Dovish and Hawkish](https://www.dailyfx.com/education/forex-fundamental-analysis/hawkish-vs-dovish-and-forex-trading.html) # - [Nice scrollable chart to study EUR-USD trends](https://www.macrotrends.net/2548/euro-dollar-exchange-rate-historical-chart) # [Index](#Index)