Skip to content

Commit 0c8d542

Browse files
committed
Add --json-output to portfolio command
1 parent 5d8042d commit 0c8d542

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

pytr/main.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ def formatter(prog):
134134
help=info,
135135
description=info,
136136
)
137+
parser_portfolio.add_argument("-j", "--json-output", help="Output path of JSON file", metavar="OUTPUT", type=Path)
137138
parser_portfolio.add_argument("-o", "--output", help="Output path of CSV file", metavar="OUTPUT", type=Path)
138139
# details
139140
info = "Get details for an ISIN"
@@ -304,6 +305,8 @@ def main():
304305
p.get()
305306
if args.output is not None:
306307
p.portfolio_to_csv(args.output)
308+
if args.json_output is not None:
309+
p.portfolio_to_json(args.json_output)
307310
elif args.command == "export_transactions":
308311
export_transactions(args.input, args.output, args.lang, args.sort, args.date_isoformat)
309312
elif args.version:

pytr/portfolio.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import json
23

34
from pytr.utils import preview
45

@@ -84,6 +85,19 @@ def portfolio_to_csv(self, output_path):
8485

8586
print(f"Wrote {len(csv_lines) + 1} lines to {output_path}")
8687

88+
def portfolio_to_json(self, output_path):
89+
# Combine the portfolio positions with the cash portfolio.
90+
data = {
91+
"positions": sorted(self.portfolio["positions"], key=lambda x: x["netSize"], reverse=True),
92+
"cash": self.cash
93+
}
94+
if output_path is None or str(output_path) == "-":
95+
print(json.dumps(data, indent=2))
96+
else:
97+
with open(output_path, "w", encoding="utf-8") as f:
98+
json.dump(data, f, indent=2)
99+
print(f"Wrote portfolio and cash data to {output_path}")
100+
87101
def overview(self):
88102
print(
89103
"Name ISIN avgCost * quantity = buyCost -> netValue diff %-diff"

0 commit comments

Comments
 (0)