Skip to content

Commit

Permalink
refactor: small tweaks & simplifications
Browse files Browse the repository at this point in the history
  • Loading branch information
MadeInPierre committed Jan 15, 2024
1 parent f961f03 commit b095b39
Show file tree
Hide file tree
Showing 7 changed files with 51 additions and 92 deletions.
11 changes: 5 additions & 6 deletions finalynx/analyzer/asset_class.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from datetime import date
from typing import Any
from typing import Dict

Expand Down Expand Up @@ -70,15 +69,15 @@ class AnalyzeAssetClasses(Analyzer):

def analyze(self) -> Dict[str, Any]:
""":returns: A dictionary with keys as the asset class names and values as the
sum of investments corresponding to each class."""
sum of investments corresponding to each class. Two-layer dictionary with classes and subclasses."""
return self._recursive_merge(self.node)

def analyzeTime(self, target_date: date) -> Dict[str, float]:
def analyze_flat(self) -> Dict[str, float]:
""":returns: A dictionary with keys as the asset class names and values as the
sum of investments corresponding to each class."""
return self._recursive_mergeTime(self.node, target_date)
return self._recursive_merge_flat(self.node)

def _recursive_mergeTime(self, node: Node, target_date: date) -> Dict[str, Any]:
def _recursive_merge_flat(self, node: Node) -> Dict[str, Any]:
"""Internal method for recursive searching."""
total = {c.value: 0.0 for c in AssetClass}

Expand All @@ -90,7 +89,7 @@ def _recursive_mergeTime(self, node: Node, target_date: date) -> Dict[str, Any]:
# Folders merge what the children return
elif isinstance(node, Folder):
for child in node.children:
for key, value in self._recursive_mergeTime(child, target_date).items():
for key, value in self._recursive_merge_flat(child).items():
total[key] += value
return total

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from datetime import date
from typing import Any
from typing import Dict

Expand All @@ -10,7 +9,7 @@
from .analyzer import Analyzer


class AnalyzeSubAssetClasses(Analyzer):
class AnalyzeAssetSubclasses(Analyzer):
"""Aims to agglomerate the children's Sub asset classes and return
the amount represented by each Sub asset class.
:returns: a dictionary with Sub asset classes as keys and the
Expand Down Expand Up @@ -102,16 +101,16 @@ class AnalyzeSubAssetClasses(Analyzer):
}

def analyze(self) -> Dict[str, Any]:
""":returns: A dictionary with keys as the asset class names and values as the
sum of investments corresponding to each class."""
""":returns: A dictionary with keys as the asset class names and values as the sum of
investments corresponding to each class. Two-layer dictionary with classes and subclasses."""
return self._recursive_merge(self.node)

def analyzeTime(self, target_date: date) -> Dict[str, float]:
def analyze_flat(self) -> Dict[str, float]:
""":returns: A dictionary with keys as the Sub asset class names and values as the
sum of investments corresponding to each class."""
return self._recursive_mergeTime(self.node, target_date)
sum of investments corresponding to each subclass."""
return self._recursive_merge_flat(self.node)

def _recursive_mergeTime(self, node: Node, target_date: date) -> Dict[str, Any]:
def _recursive_merge_flat(self, node: Node) -> Dict[str, Any]:
"""Internal method for recursive searching."""
total = {}

Expand All @@ -123,7 +122,7 @@ def _recursive_mergeTime(self, node: Node, target_date: date) -> Dict[str, Any]:
# Folders merge what the children return
elif isinstance(node, Folder):
for child in node.children:
for key, value in self._recursive_mergeTime(child, target_date).items():
for key, value in self._recursive_merge_flat(child).items():
if key in total.keys():
total[key] += value
else:
Expand Down
32 changes: 0 additions & 32 deletions finalynx/analyzer/envelopes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from datetime import date
from typing import Any
from typing import Dict

Expand All @@ -20,37 +19,6 @@ def analyze(self) -> Dict[str, float]:
sum of investments corresponding to each class."""
return self._recursive_merge(self.node)

def analyzeTime(self, target_date: date) -> Dict[str, float]:
""":returns: A dictionary with keys as the asset class names and values as the
sum of investments corresponding to each class."""
return self._recursive_mergeTime(self.node, target_date)

def _recursive_mergeTime(self, node: Node, target_date: date) -> Dict[str, Any]:
"""Internal method for recursive searching."""
total = {}

# Lines simply return their own amount
if isinstance(node, Line):
if node.envelope:
total[node.envelope.name] = node.get_amount()
else:
total["Unknown"] = node.get_amount()
return total

# Folders merge what the children return
elif isinstance(node, Folder):
for child in node.children:
for key, value in self._recursive_mergeTime(child, target_date).items():
if key in total.keys():
total[key] += value
else:
total[key] = value
return total

# Safeguard for future versions
else:
raise ValueError(f"Unknown node type '{type(node)}'.")

def _recursive_merge(self, node: Node) -> Dict[str, float]:
"""Internal method for recursive searching."""
total = {}
Expand Down
9 changes: 4 additions & 5 deletions finalynx/analyzer/lines.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from datetime import date
from typing import Any
from typing import Dict

Expand All @@ -15,12 +14,12 @@ class AnalyzeLines(Analyzer):
corresponding total amount contained in the children.
"""

def analyzeTime(self, target_date: date) -> Dict[str, float]:
def analyze(self) -> Dict[str, float]:
""":returns: A dictionary with keys as the asset class names and values as the
sum of investments corresponding to each class."""
return self._recursive_mergeTime(self.node, target_date)
return self._recursive_merge(self.node)

def _recursive_mergeTime(self, node: Node, target_date: date) -> Dict[str, Any]:
def _recursive_merge(self, node: Node) -> Dict[str, Any]:
"""Internal method for recursive searching."""
total = {}

Expand All @@ -35,7 +34,7 @@ def _recursive_mergeTime(self, node: Node, target_date: date) -> Dict[str, Any]:
# Folders merge what the children return
elif isinstance(node, Folder):
for child in node.children:
for key, value in self._recursive_mergeTime(child, target_date).items():
for key, value in self._recursive_merge(child).items():
if key in total.keys():
total[key] += value
else:
Expand Down
2 changes: 1 addition & 1 deletion finalynx/assistant.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ def _parse_args(self) -> None:
if args["--sim-steps"] and self.simulation:
self.simulation.step_years = int(args["--sim-steps"])
if args["--metric-frequency"] and self.simulation:
self.simulation.metrics_record_freqency = str(args["--metric-frequency"])
self.simulation.metrics_record_frequency = str(args["--metric-frequency"])
if args["--theme"]:
theme_name = str(args["--theme"])
if theme_name not in finalynx.theme.AVAILABLE_THEMES:
Expand Down
22 changes: 11 additions & 11 deletions finalynx/dashboard/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
from typing import Set

from finalynx.analyzer.asset_class import AnalyzeAssetClasses
from finalynx.analyzer.asset_subclass import AnalyzeAssetSubclasses
from finalynx.analyzer.envelopes import AnalyzeEnvelopes
from finalynx.analyzer.investment_state import AnalyzeInvestmentStates
from finalynx.analyzer.subasset_class import AnalyzeSubAssetClasses
from finalynx.portfolio.folder import Folder
from finalynx.portfolio.folder import FolderDisplay
from finalynx.portfolio.line import Line
Expand Down Expand Up @@ -183,8 +183,8 @@ def _on_select_color_map(data: Any) -> None:
with ui.row():
self.chart_envelopes = ui.chart(AnalyzeEnvelopes(self.selected_node).chart())
self.chart_etats_enveloppes = ui.chart(
timeline.chartOnTimeline(
"Evolution des états d'enveloppes",
timeline.chart_timeline(
"Envelope States Evolution",
timeline._log_env_states,
{
"Unknown": "#434348",
Expand All @@ -198,31 +198,31 @@ def _on_select_color_map(data: Any) -> None:
else {}
)
self.chart_enveloppes = ui.chart(
timeline.chartOnTimeline("Evolution des enveloppes", timeline._log_enveloppe_values)
timeline.chart_timeline("Envelopes Evolution", timeline._log_enveloppe_values)
if timeline
else {}
)
self.chart_asset_classes = ui.chart(
timeline.chartOnTimeline(
"Evolution des classes d'actifs",
timeline.chart_timeline(
"Asset Classes Evolution",
timeline._log_assets_classes_values,
AnalyzeAssetClasses.ASSET_COLORS_FINARY,
)
if timeline
else {}
)
self.chart_subasset_classes = ui.chart(
timeline.chartOnTimeline(
"Evolution des sous-classes d'actifs",
timeline.chart_timeline(
"Asset Subclasses Evolution",
timeline._log_assets_subclasses_values,
AnalyzeSubAssetClasses.SUBASSET_COLORS_FINARY,
AnalyzeAssetSubclasses.SUBASSET_COLORS_FINARY,
)
if timeline
else {}
)
self.chart_lines = ui.chart(
timeline.chartOnTimeline(
"Evolution des lignes du portefeuille",
timeline.chart_timeline(
"Line-by-line Evolution",
timeline._log_lines_values,
visible_by_default=False,
)
Expand Down
50 changes: 22 additions & 28 deletions finalynx/simulator/timeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
from typing import Optional

from finalynx.analyzer.asset_class import AnalyzeAssetClasses
from finalynx.analyzer.asset_subclass import AnalyzeAssetSubclasses
from finalynx.analyzer.envelopes import AnalyzeEnvelopes
from finalynx.analyzer.investment_state import AnalyzeInvestmentStates
from finalynx.analyzer.lines import AnalyzeLines
from finalynx.analyzer.subasset_class import AnalyzeSubAssetClasses
from finalynx.portfolio.bucket import Bucket
from finalynx.portfolio.constants import AssetClass
from finalynx.portfolio.envelope import EnvelopeState
Expand Down Expand Up @@ -48,7 +48,7 @@ class Simulation:
step_years: int = 5

# Record the portfolio stats on each day of the simulation 'DAY', 'MONTH', 'YEAR'
metrics_record_freqency: str = "MONTH"
metrics_record_frequency: str = "MONTH"


class Timeline:
Expand Down Expand Up @@ -144,18 +144,11 @@ def step(self) -> bool:
self._sort_events()

# Record the metrics if the year changed
# if next_event.planned_date.year != self.current_date.year:
# self._record_metrics()
_freq = self.simulation.metrics_record_frequency
if (
(self.simulation.metrics_record_freqency == "DAY" and next_event.planned_date != self.current_date)
or (
self.simulation.metrics_record_freqency == "YEAR"
and next_event.planned_date.year != self.current_date.year
)
or (
self.simulation.metrics_record_freqency == "MONTH"
and next_event.planned_date.month != self.current_date.month
)
(_freq == "DAY" and next_event.planned_date != self.current_date)
or (_freq == "YEAR" and next_event.planned_date.year != self.current_date.year)
or (_freq == "MONTH" and next_event.planned_date.month != self.current_date.month)
):
self.current_date = next_event.planned_date
self._record_metrics()
Expand Down Expand Up @@ -187,52 +180,53 @@ def _record_metrics(self) -> None:
for key, value in AnalyzeInvestmentStates(self._portfolio).analyze(self.current_date).items():
self._log_env_states[key].append(value)

for key, value in AnalyzeEnvelopes(self._portfolio).analyzeTime(self.current_date).items():
for key, value in AnalyzeEnvelopes(self._portfolio).analyze().items():
if key in self._log_enveloppe_values:
self._log_enveloppe_values[key].append(value)
else:
self._log_enveloppe_values[key] = [value]

for key, value in AnalyzeAssetClasses(self._portfolio).analyzeTime(self.current_date).items():
for key, value in AnalyzeAssetClasses(self._portfolio).analyze_flat().items():
self._log_assets_classes_values[key].append(value)

for key, value in AnalyzeSubAssetClasses(self._portfolio).analyzeTime(self.current_date).items():
for key, value in AnalyzeAssetSubclasses(self._portfolio).analyze_flat().items():
if key in self._log_assets_subclasses_values:
self._log_assets_subclasses_values[key].append(value)
else:
self._log_assets_subclasses_values[key] = [value]

for key, value in AnalyzeLines(self._portfolio).analyzeTime(self.current_date).items():
for key, value in AnalyzeLines(self._portfolio).analyze().items():
if key in self._log_lines_values:
self._log_lines_values[key].append(value)
else:
self._log_lines_values[key] = [value]
else:
# On doit remplacer les valeurs stockées par les nouvelles sans créer 2 fois l'enregistrement
# ident = self._log_dates.index(self.current_date) # TODO

# Record the envelope states and their amounts at this date
for key, value in AnalyzeInvestmentStates(self._portfolio).analyze(self.current_date).items():
self._log_env_states[key][-1] = value
for key, value in AnalyzeEnvelopes(self._portfolio).analyzeTime(self.current_date).items():

for key, value in AnalyzeEnvelopes(self._portfolio).analyze().items():
if key in self._log_enveloppe_values:
self._log_enveloppe_values[key][-1] = value
else:
self._log_enveloppe_values[key] = [value]
for key, value in AnalyzeAssetClasses(self._portfolio).analyzeTime(self.current_date).items():

for key, value in AnalyzeAssetClasses(self._portfolio).analyze_flat().items():
self._log_assets_classes_values[key][-1] = value
for key, value in AnalyzeSubAssetClasses(self._portfolio).analyzeTime(self.current_date).items():

for key, value in AnalyzeAssetSubclasses(self._portfolio).analyze_flat().items():
if key in self._log_assets_subclasses_values:
self._log_assets_subclasses_values[key][-1] = value
else:
self._log_assets_subclasses_values[key] = [value]
for key, value in AnalyzeLines(self._portfolio).analyzeTime(self.current_date).items():

for key, value in AnalyzeLines(self._portfolio).analyze().items():
if key in self._log_lines_values:
self._log_lines_values[key][-1] = value
else:
self._log_lines_values[key] = [value]

def chartOnTimeline(
def chart_timeline(
self,
title: str,
valuesToGraph: Dict[str, List[float]],
Expand All @@ -249,7 +243,7 @@ def chartOnTimeline(
"plotShadow": False,
"type": "area",
"zooming": {"type": "xy"},
"height": 1200,
"height": 800,
"width": 1000,
},
"title": {"text": title, "align": "center"},
Expand All @@ -264,7 +258,7 @@ def chartOnTimeline(
"series": [
{
"name": key,
"data": self.convertDataSeries(value),
"data": self._convert_data_series(value),
"visible": visible_by_default,
"color": colors[key] if (key in colors) else {None},
}
Expand All @@ -280,7 +274,7 @@ def chartOnTimeline(
"credits": {"enabled": False},
}

def convertDataSeries(self, data: [float]) -> [Any]:
def _convert_data_series(self, data: List[float]) -> List[Any]:
"""Convert DataSeries in a time series format to allow non regular data"""
res = []
i = 0
Expand Down

0 comments on commit b095b39

Please sign in to comment.