# import libraries and set display options
import pandas as pd
import pprint
# set frame width and center output
from IPython.core.display import display, HTML
display(HTML("""
<style>
.container {width:84% !important;
}
</style>
"""))
# pretty print options
pd.options.display.float_format = '{:20,.4f}'.format
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 3000)
pd.set_option('display.colheader_justify', 'center')
pd.set_option('display.precision', 3)
# open file
x_rates = pd.read_csv("euro-daily-hist_1999_2020.csv")
# strip brackets and trailing space from country names
# replace remaining space with underscore
# lower case all column names
x_rates.columns = x_rates.columns.str.replace("[","").str.replace("]","")
x_rates.columns = x_rates.columns.str.rstrip()
x_rates.columns = x_rates.columns.str.replace(" ","_")
x_rates.columns = x_rates.columns.str.lower()
# rename columns
x_rates.rename(columns={"period\\unit:":"date",
"chinese_yuan_renminbi":"chinese_yuan",
"uk_pound_sterling":"uk_pound"}, inplace=True)
# convert datetime
x_rates["date"] = pd.to_datetime(x_rates["date"])
# resort and reindex
x_rates.sort_values("date", inplace=True)
x_rates.reset_index(drop=True, inplace=True)
# convert hyphens in currency columns to NaN
import numpy as np
x_rates = x_rates.replace("-", np.nan)
# convert exchange rate values to float
x_rates.iloc[:,1:] = x_rates.iloc[:,1:].astype(float)
display(x_rates.head())
/var/folders/bz/5cj1tzbj5xn319rpqrw6gpmh0000gn/T/ipykernel_10747/1632861684.py:4: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will *not* be treated as literal strings when regex=True. x_rates.columns = x_rates.columns.str.replace("[","").str.replace("]","")
date | australian_dollar | bulgarian_lev | brazilian_real | canadian_dollar | swiss_franc | chinese_yuan | cypriot_pound | czech_koruna | danish_krone | estonian_kroon | uk_pound | greek_drachma | hong_kong_dollar | croatian_kuna | hungarian_forint | indonesian_rupiah | israeli_shekel | indian_rupee | iceland_krona | japanese_yen | korean_won | lithuanian_litas | latvian_lats | maltese_lira | mexican_peso | malaysian_ringgit | norwegian_krone | new_zealand_dollar | philippine_peso | polish_zloty | romanian_leu | russian_rouble | swedish_krona | singapore_dollar | slovenian_tolar | slovak_koruna | thai_baht | turkish_lira | us_dollar | south_african_rand | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1999-01-04 | 1.9100 | NaN | NaN | 1.8004 | 1.6168 | NaN | 0.5823 | 35.1070 | 7.4501 | 15.6466 | 0.7111 | 327.1500 | 9.1332 | NaN | 251.4800 | 9,433.6100 | NaN | NaN | 81.4800 | 133.7300 | 1,398.5900 | 4.7170 | 0.6668 | 0.4432 | 11.6446 | 4.4798 | 8.8550 | 2.2229 | 45.5100 | 4.0712 | 1.3111 | 25.2875 | 9.4696 | 1.9554 | 189.0450 | 42.9910 | 42.6799 | 0.3723 | 1.1789 | 6.9358 |
1 | 1999-01-05 | 1.8944 | NaN | NaN | 1.7965 | 1.6123 | NaN | 0.5823 | 34.9170 | 7.4495 | 15.6466 | 0.7122 | 324.7000 | 9.1341 | NaN | 250.8000 | 9,314.5100 | NaN | NaN | 81.5300 | 130.9600 | 1,373.0100 | 4.7174 | 0.6657 | 0.4432 | 11.5960 | 4.4805 | 8.7745 | 2.2011 | 44.7450 | 4.0245 | 1.3168 | 26.5876 | 9.4025 | 1.9655 | 188.7750 | 42.8480 | 42.5048 | 0.3728 | 1.1790 | 6.7975 |
2 | 1999-01-06 | 1.8820 | NaN | NaN | 1.7711 | 1.6116 | NaN | 0.5820 | 34.8500 | 7.4452 | 15.6466 | 0.7076 | 324.7200 | 9.1010 | NaN | 250.6700 | 9,337.6800 | NaN | NaN | 81.5400 | 131.4200 | 1,359.5400 | 4.6994 | 0.6649 | 0.4420 | 11.4705 | 4.4637 | 8.7335 | 2.1890 | 44.8720 | 4.0065 | 1.3168 | 27.4315 | 9.3050 | 1.9699 | 188.7000 | 42.7780 | 42.6949 | 0.3722 | 1.1743 | 6.7307 |
3 | 1999-01-07 | 1.8474 | NaN | NaN | 1.7602 | 1.6165 | NaN | 0.5819 | 34.8860 | 7.4431 | 15.6466 | 0.7058 | 324.4000 | 9.0131 | NaN | 250.0900 | 9,218.7700 | NaN | NaN | 81.0600 | 129.4300 | 1,337.1600 | 4.6548 | 0.6627 | 0.4413 | 11.5511 | 4.4203 | 8.6295 | 2.1531 | 44.4360 | 4.0165 | 1.3092 | 26.9876 | 9.1800 | 1.9436 | 188.8000 | 42.7650 | 42.1678 | 0.3701 | 1.1632 | 6.8283 |
4 | 1999-01-08 | 1.8406 | NaN | NaN | 1.7643 | 1.6138 | NaN | 0.5819 | 34.9380 | 7.4433 | 15.6466 | 0.7094 | 324.0000 | 9.0302 | NaN | 250.1500 | 9,321.6300 | NaN | NaN | 80.9900 | 130.0900 | 1,366.7300 | 4.6643 | 0.6654 | 0.4419 | 11.4414 | 4.4295 | 8.5900 | 2.1557 | 44.2950 | 4.0363 | 1.3143 | 27.2075 | 9.1650 | 1.9537 | 188.8400 | 42.5600 | 42.5590 | 0.3718 | 1.1659 | 6.7855 |
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.pyplot import cm
colors = iter([plt.cm.Set3(i) for i in range(20)])
# create a list of data frame names
# not sure this is neccessary but trying df = df_list.index(currency) in the framer function doesn't seem to work
# create a list of data frames for each currency with log rate of the exchange rate, 30 day rolling mean, and year
# col_names = []
df_dict = {}
for currency in x_rates.columns[1:]:
df_name = currency
# col_names.append(df_name)
df = x_rates[["date", currency]].copy()
df = df[df[currency].notna()]
df["log_rate"] = np.log(df.iloc[:,1]/df.iloc[:,1].shift()) # getting the log of the exchange rate # double check this is the correct way to get log
df["rolling_mean_30"] = df[currency].rolling(30).mean()
df["year"] = df["date"].dt.year
df_dict[currency] = df
# currencies for comparison
high_freq = [df_dict["us_dollar"], df_dict["japanese_yen"], df_dict["uk_pound"], df_dict["australian_dollar"]]
low_freq = [df_dict["israeli_shekel"], df_dict["philippine_peso"], df_dict["malaysian_ringgit"], df_dict["romanian_leu"]]
# line graph showing Euro to four high frequency trading pairs overlapped
# widget can be turned on and off to discover specific dates
%matplotlib widget
fig, ax = plt.subplots(figsize=(7.5,5))
ax1 = ax.twinx()
ax2 = ax.twinx()
ax3 = ax.twinx()
line = ax.plot(df_dict["us_dollar"]["date"], df_dict["us_dollar"]["rolling_mean_30"], 'tab:orange')
line_1 = ax1.plot(df_dict["us_dollar"]["date"], df_dict["japanese_yen"]["rolling_mean_30"], 'tab:blue')
line_2 = ax2.plot(df_dict["us_dollar"]["date"], df_dict["uk_pound"]["rolling_mean_30"], 'tab:green')
line_3 = ax3.plot(df_dict["us_dollar"]["date"], df_dict["australian_dollar"]["rolling_mean_30"], 'tab:red')
lines = [line, line_1, line_2, line_3]
for ax in ax, ax1, ax2, ax3:
ax.set(yticks=[])
plt.show()
--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) /var/folders/bz/5cj1tzbj5xn319rpqrw6gpmh0000gn/T/ipykernel_10747/3736899207.py in <module> 1 # line graph showing Euro to four high frequency trading pairs overlapped 2 # widget can be turned on and off to discover specific dates ----> 3 get_ipython().run_line_magic('matplotlib', 'widget') 4 fig, ax = plt.subplots(figsize=(7.5,5)) 5 ax1 = ax.twinx() /opt/anaconda3/envs/geo_env/lib/python3.9/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth) 2349 kwargs['local_ns'] = self.get_local_scope(stack_depth) 2350 with self.builtin_trap: -> 2351 result = fn(*args, **kwargs) 2352 return result 2353 /opt/anaconda3/envs/geo_env/lib/python3.9/site-packages/decorator.py in fun(*args, **kw) 230 if not kwsyntax: 231 args, kw = fix(args, kw, sig) --> 232 return caller(func, *(extras + args), **kw) 233 fun.__name__ = func.__name__ 234 fun.__doc__ = func.__doc__ /opt/anaconda3/envs/geo_env/lib/python3.9/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k) 185 # but it's overkill for just that one bit of state. 186 def magic_deco(arg): --> 187 call = lambda f, *a, **k: f(*a, **k) 188 189 if callable(arg): /opt/anaconda3/envs/geo_env/lib/python3.9/site-packages/IPython/core/magics/pylab.py in matplotlib(self, line) 97 print("Available matplotlib backends: %s" % backends_list) 98 else: ---> 99 gui, backend = self.shell.enable_matplotlib(args.gui.lower() if isinstance(args.gui, str) else args.gui) 100 self._show_matplotlib_backend(args.gui, backend) 101 /opt/anaconda3/envs/geo_env/lib/python3.9/site-packages/IPython/core/interactiveshell.py in enable_matplotlib(self, gui) 3531 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) 3532 -> 3533 pt.activate_matplotlib(backend) 3534 configure_inline_support(self, backend) 3535 /opt/anaconda3/envs/geo_env/lib/python3.9/site-packages/IPython/core/pylabtools.py in activate_matplotlib(backend) 357 from matplotlib import pyplot as plt 358 --> 359 plt.switch_backend(backend) 360 361 plt.show._needmain = False /opt/anaconda3/envs/geo_env/lib/python3.9/site-packages/matplotlib/pyplot.py in switch_backend(newbackend) 265 backend_name = cbook._backend_module_name(newbackend) 266 --> 267 class backend_mod(matplotlib.backend_bases._Backend): 268 locals().update(vars(importlib.import_module(backend_name))) 269 /opt/anaconda3/envs/geo_env/lib/python3.9/site-packages/matplotlib/pyplot.py in backend_mod() 266 267 class backend_mod(matplotlib.backend_bases._Backend): --> 268 locals().update(vars(importlib.import_module(backend_name))) 269 270 required_framework = _get_required_interactive_framework(backend_mod) /opt/anaconda3/envs/geo_env/lib/python3.9/importlib/__init__.py in import_module(name, package) 125 break 126 level += 1 --> 127 return _bootstrap._gcd_import(name[level:], package, level) 128 129 /opt/anaconda3/envs/geo_env/lib/python3.9/importlib/_bootstrap.py in _gcd_import(name, package, level) /opt/anaconda3/envs/geo_env/lib/python3.9/importlib/_bootstrap.py in _find_and_load(name, import_) /opt/anaconda3/envs/geo_env/lib/python3.9/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_) /opt/anaconda3/envs/geo_env/lib/python3.9/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds) /opt/anaconda3/envs/geo_env/lib/python3.9/importlib/_bootstrap.py in _gcd_import(name, package, level) /opt/anaconda3/envs/geo_env/lib/python3.9/importlib/_bootstrap.py in _find_and_load(name, import_) /opt/anaconda3/envs/geo_env/lib/python3.9/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_) ModuleNotFoundError: No module named 'ipympl'