function to improve the data to plot

This commit is contained in:
hjoaquim
2022-11-07 15:29:28 +00:00
parent 46afc9eb8f
commit 8d3798ff6a
3 changed files with 49 additions and 27 deletions

View File

@@ -1438,9 +1438,17 @@ class EconomyController(BaseController):
f"{country}{transformtype}[{parameter}, Units: {units}]"
] = data[variable]
elif key == "fred":
dataset_yaxis1[self.FRED_TITLES[variable]] = data[
variable
]
compound_detail = self.FRED_TITLES[variable]
detail = {
"units": compound_detail.split("(")[-1].split(
")"
)[0],
"title": compound_detail.split("(")[0].strip(),
}
data_to_plot, title = fred_view.format_data_to_plot(
data[variable], detail
)
dataset_yaxis1[title] = data_to_plot
elif (
key == "index"
and variable in yfinance_model.INDICES
@@ -1500,9 +1508,17 @@ class EconomyController(BaseController):
f"{country}{transformtype}[{parameter}, Units: {units}]"
] = data[variable]
elif key == "fred":
dataset_yaxis2[self.FRED_TITLES[variable]] = data[
variable
]
compound_detail = self.FRED_TITLES[variable]
detail = {
"units": compound_detail.split("(")[-1].split(
")"
)[0],
"title": compound_detail.split("(")[0].strip(),
}
data_to_plot, title = fred_view.format_data_to_plot(
data[variable], detail
)
dataset_yaxis2[title] = data_to_plot
elif (
key == "index"
and variable in yfinance_model.INDICES

View File

@@ -204,7 +204,7 @@ def get_series_data(
@check_api_key(["API_FRED_KEY"])
def get_aggregated_series_data(
series_ids: List[str], start_date: str = None, end_date: str = None
) -> pd.DataFrame:
) -> Tuple[pd.DataFrame, dict]:
"""Get Series data. [Source: FRED]
Parameters
----------
@@ -219,6 +219,8 @@ def get_aggregated_series_data(
----------
pd.DataFrame
Series data
dict
Dictionary of series ids and titles
"""
data = pd.DataFrame()

View File

@@ -4,7 +4,7 @@ __docformat__ = "numpy"
import logging
import os
import textwrap
from typing import Dict, Optional, List
from typing import Dict, Optional, List, Tuple
from datetime import datetime
import matplotlib.pyplot as plt
@@ -120,27 +120,17 @@ def display_fred_series(
else:
return
if len(series_ids) == 1:
s_id = series_ids[0]
sub_dict: Dict = detail[s_id]
title = f"{sub_dict['title']} ({sub_dict['units']})"
for s_id, sub_dict in detail.items():
data_to_plot, title = format_data_to_plot(data[s_id], sub_dict)
ax.plot(
data.index, data.iloc[:, 0], label="\n".join(textwrap.wrap(title, 80))
data_to_plot.index,
data_to_plot,
label="\n".join(textwrap.wrap(title, 80))
if len(series_ids) < 5
else title,
)
else:
for s_id, sub_dict in detail.items():
data_to_plot = data[s_id].dropna()
exponent = int(np.log10(data_to_plot.max()))
data_to_plot /= 10**exponent
multiplier = f"x {format_units(10**exponent)}" if exponent > 0 else ""
title = f"{sub_dict['title']} ({sub_dict['units']}) {'['+multiplier+']' if multiplier else ''}"
ax.plot(
data_to_plot.index,
data_to_plot,
label="\n".join(textwrap.wrap(title, 80))
if len(series_ids) < 5
else title,
)
ax.legend(
bbox_to_anchor=(0, 0.40, 1, -0.52),
@@ -173,6 +163,20 @@ def display_fred_series(
)
def format_data_to_plot(data: pd.DataFrame, detail: dict) -> Tuple[pd.DataFrame, str]:
"""Helper to format data to plot"""
data_to_plot = data.dropna()
exponent = int(np.log10(data_to_plot.max()))
data_to_plot /= 10**exponent
multiplier = f"x {format_units(10**exponent)}" if exponent > 0 else ""
title = f"{detail['title']} ({detail['units']}) {'['+multiplier+']' if multiplier else ''}"
data_to_plot.index = pd.to_datetime(data_to_plot.index)
return data_to_plot, title
@log_start_end(log=logger)
@check_api_key(["API_FRED_KEY"])
def display_yield_curve(