|
| 1 | +""" |
| 2 | +Module for generating smoothed currency exchange rate charts. |
| 3 | +
|
| 4 | +This module provides an asynchronous function to create a visual |
| 5 | +representation of historical currency exchange rates. The function |
| 6 | +uses spline interpolation to smooth data points and matplotlib |
| 7 | +to generate a JPEG chart image returned as a binary stream. |
| 8 | +
|
| 9 | +It requires the Currency schema for input parameters and uses |
| 10 | +matplotlib and scipy for plotting and interpolation. |
| 11 | +""" |
| 12 | + |
| 13 | +from datetime import datetime |
| 14 | +from io import BytesIO |
| 15 | +from typing import Optional |
| 16 | + |
| 17 | +import numpy as np |
| 18 | +from database.server import Database |
| 19 | +from matplotlib import pyplot as plt |
| 20 | +from schemas.currency import Currency |
| 21 | +from scipy.interpolate import make_interp_spline |
| 22 | +from utils.config.get_dsn import get_dsn |
| 23 | +from utils.config.load_config import load_config |
| 24 | + |
| 25 | +config = load_config("config.hjson") |
| 26 | + |
| 27 | + |
| 28 | +async def create_chart( |
| 29 | + currency: Currency, dates: list, rates: list |
| 30 | +) -> Optional[BytesIO]: |
| 31 | + """ |
| 32 | + Generates a smoothed currency exchange rate chart image |
| 33 | + from historical data. |
| 34 | +
|
| 35 | + This asynchronous function receives historical exchange rate data |
| 36 | + for aspecified currency pair over a given date range. |
| 37 | + It applies spline interpolation to smooth the rate curve, |
| 38 | + then creates a matplotlib plot |
| 39 | + with formatted date labels on the x-axis. The resulting plot is saved |
| 40 | + as a JPEG image in a binary stream. |
| 41 | +
|
| 42 | + Args: |
| 43 | + currency (Currency): An object containing details about |
| 44 | + the currency pair and period. |
| 45 | + dates (list): A list of datetime objects |
| 46 | + representing the dates of the data points. |
| 47 | + rates (list): A list of float values representing |
| 48 | + exchange rates corresponding to the dates. |
| 49 | +
|
| 50 | + Returns: |
| 51 | + Optional[BytesIO]: A binary stream containing |
| 52 | + the JPEG image of the chart, |
| 53 | + or None if the interpolation fails or there is insufficient data. |
| 54 | + """ |
| 55 | + x_values = np.arange(len(dates)) |
| 56 | + try: |
| 57 | + spline = make_interp_spline(x_values, rates, k=2) |
| 58 | + except ValueError: |
| 59 | + return None |
| 60 | + |
| 61 | + new_x = np.linspace(0, len(dates) - 1, 200) |
| 62 | + new_y = spline(new_x) |
| 63 | + |
| 64 | + fig, ax = plt.subplots(figsize=(15, 6)) |
| 65 | + |
| 66 | + ax.set_xticks(np.linspace(0, len(dates) - 1, 10)) |
| 67 | + current_year = datetime.now().year |
| 68 | + ax.set_xticklabels( |
| 69 | + [ |
| 70 | + ( |
| 71 | + dates[int(i)].strftime("%m-%d") |
| 72 | + if dates[int(i)].year == current_year |
| 73 | + else dates[int(i)].strftime("%Y-%m-%d") |
| 74 | + ) |
| 75 | + for i in np.linspace(0, len(dates) - 1, 10).astype(int) |
| 76 | + ], |
| 77 | + ) |
| 78 | + |
| 79 | + ax.tick_params(axis="both", labelsize=10) |
| 80 | + |
| 81 | + if rates[0] < rates[-1]: |
| 82 | + color = "green" |
| 83 | + elif rates[0] > rates[-1]: |
| 84 | + color = "red" |
| 85 | + else: |
| 86 | + color = "grey" |
| 87 | + |
| 88 | + ax.plot(new_x, new_y, color=color, linewidth=2) |
| 89 | + |
| 90 | + ax.spines["top"].set_visible(False) |
| 91 | + ax.spines["right"].set_visible(False) |
| 92 | + |
| 93 | + buf = BytesIO() |
| 94 | + fig.savefig(buf, format="jpeg", bbox_inches="tight") |
| 95 | + plt.close(fig) |
| 96 | + buf.seek(0) |
| 97 | + |
| 98 | + return buf |
0 commit comments