...
 
Commits (2)
This diff is collapsed.
......@@ -3,7 +3,7 @@ Holds a wrapper around the forex_python API, which caches the result and can ret
forex rate for a given range of dates. The ForexDB can be pickled for future use.
"""
from typing import Tuple, List
from typing import Tuple, List, Dict
from datetime import date, timedelta, datetime
from forex_python.converter import CurrencyRates
......@@ -98,15 +98,15 @@ class ForexDB(object):
self.c_pair = c_pair
self.resolution: timedelta = resolution
self.data: List[Tuple[date, ForexDay]] = list()
self.data: Dict[date, ForexDay] = dict()
def __query_range(self, l_dates: List[date]) -> List[Tuple[date, ForexDay]]:
def __query_range(self, l_dates: List[date]) -> Dict[date, ForexDay]:
data: List[Tuple[date, ForexDay]] = list()
data: Dict[date, ForexDay] = dict()
for day in l_dates:
print("API loading Forex Rate for: " + str(day), end="\r")
data.append((day, ForexDay(day, self.resolution, self.c_pair)))
data[day] = ForexDay(day, self.resolution, self.c_pair)
return data
......@@ -117,9 +117,9 @@ class ForexDB(object):
def get_dates(self) -> List[date]:
"""
Returns the days already cached in the database.
Returns a sorted list of the days already cached in the database.
"""
return [elem[0] for elem in self.data]
return sorted(self.data.keys())
def get_means(self) -> List[float]:
......@@ -127,7 +127,7 @@ class ForexDB(object):
Returns the mean exchange rate (measured at a resolution of self.resolution) for each day
in the database.
"""
return [elem[1].mean_rate() for elem in self.data]
return [self.data[key].mean_rate() for key in self.get_dates()]
def grow_db(self, start: date, end: date) -> None:
......@@ -139,8 +139,9 @@ class ForexDB(object):
self.__init_db(start, end)
return
d_start, _ = self.data[0]
d_end, _ = self.data[-1]
l_days = self.get_dates()
d_start = l_days[0]
d_end = l_days[-1]
if (d_start <= start) and (d_end >= end):
return
......@@ -148,8 +149,8 @@ class ForexDB(object):
r_start: List[date] = date_range(start, d_start - timedelta(days=1))
r_end: List[date] = date_range(d_end + timedelta(days=1), end)
self.data = self.__query_range(r_start) + self.data
self.data = self.data + self.__query_range(r_end)
self.data.update(self.__query_range(r_start))
self.data.update(self.__query_range(r_end))
def get_range(self, start: date, end: date) -> Tuple[List[date], List[float]]:
......@@ -158,14 +159,14 @@ class ForexDB(object):
cover this range, the database is grown.
"""
db_start, _ = self.data[0]
db_end, _ = self.data[-1]
l_days = self.get_dates()
if (start < db_start) or (end > db_end):
if (start < l_days[0]) or (end > l_days[-1]):
self.grow_db(start, end)
select: List[Tuple[date, float]] = [(cd[0], cd[1].mean_rate()) for cd in self.data
if cd[0] >= start and cd[0] <= end]
select: List[Tuple[date, float]] = [(key, self.data[key].mean_rate())
for key in self.get_dates()
if key >= start and key <= end]
dates, mean_rates = zip(*select)
......