From e300bb4c5b57825b0a076449c932aba2836cf3d1 Mon Sep 17 00:00:00 2001 From: Philipp Schmitt Date: Sat, 15 Mar 2025 11:34:13 +0100 Subject: [PATCH 1/2] Add --export-format {csv,json} to portfolio command --- pytr/main.py | 14 +++++++++++--- pytr/portfolio.py | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/pytr/main.py b/pytr/main.py index 2ffd5626..4a256b92 100644 --- a/pytr/main.py +++ b/pytr/main.py @@ -190,8 +190,13 @@ def formatter(prog): help=info, description=info, ) - parser_portfolio.add_argument("-o", "--output", help="Output path of CSV file", type=Path) - + parser_portfolio.add_argument("-o", "--output", help="Output path of the file", type=Path) + parser_portfolio.add_argument( + "--export-format", + choices=("json", "csv"), + default="csv", + help="The output file format.", + ) # details info = "Get details for an ISIN" parser_details = parser_cmd.add_parser( @@ -367,7 +372,10 @@ def main(): ) p.get() if args.output is not None: - p.portfolio_to_csv(args.output) + if args.export_format == "csv": + p.portfolio_to_csv(args.output) + elif args.export_format == "json": + p.portfolio_to_json(args.output) elif args.command == "export_transactions": events = [Event.from_dict(item) for item in json.load(args.input)] TransactionExporter( diff --git a/pytr/portfolio.py b/pytr/portfolio.py index b4b8f57f..375456ff 100644 --- a/pytr/portfolio.py +++ b/pytr/portfolio.py @@ -1,4 +1,5 @@ import asyncio +import json from pytr.utils import preview @@ -84,6 +85,19 @@ def portfolio_to_csv(self, output_path): print(f"Wrote {len(csv_lines) + 1} lines to {output_path}") + def portfolio_to_json(self, output_path): + # Combine the portfolio positions with the cash portfolio. + data = { + "positions": sorted(self.portfolio["positions"], key=lambda x: x["netSize"], reverse=True), + "cash": self.cash + } + if output_path is None or str(output_path) == "-": + print(json.dumps(data, indent=2)) + else: + with open(output_path, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2) + print(f"Wrote portfolio and cash data to {output_path}") + def overview(self): print( "Name ISIN avgCost * quantity = buyCost -> netValue diff %-diff" From 607357824c7c5dde0c7ed9e8b4e1da5372489bc7 Mon Sep 17 00:00:00 2001 From: Philipp Schmitt Date: Thu, 20 Mar 2025 13:40:20 +0100 Subject: [PATCH 2/2] ruff fmt --- pytr/portfolio.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pytr/portfolio.py b/pytr/portfolio.py index 375456ff..a9e4375c 100644 --- a/pytr/portfolio.py +++ b/pytr/portfolio.py @@ -89,7 +89,7 @@ def portfolio_to_json(self, output_path): # Combine the portfolio positions with the cash portfolio. data = { "positions": sorted(self.portfolio["positions"], key=lambda x: x["netSize"], reverse=True), - "cash": self.cash + "cash": self.cash, } if output_path is None or str(output_path) == "-": print(json.dumps(data, indent=2))