Skip to content

Commit

Permalink
Merge PR #39
Browse files Browse the repository at this point in the history
* miry-miry_master:
  If multiple documents would have the same file path when downloading, try to append the document id to make the file path unique.
  Show name of the isin in portfolio and use real netvalue
  Use compactPortfolio
  • Loading branch information
marzzzello committed Oct 29, 2023
2 parents 607d459 + 2023cf5 commit ea02920
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 17 deletions.
6 changes: 6 additions & 0 deletions pytr/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,12 @@ def run_blocking(self, fut, timeout=5.0):
async def portfolio(self):
return await self.subscribe({'type': 'portfolio'})

async def portfolio_status(self):
return await self.subscribe({'type': 'portfolioStatus'})

async def compact_portfolio(self):
return await self.subscribe({'type': 'compactPortfolio'})

async def watchlist(self):
return await self.subscribe({'type': 'watchlist'})

Expand Down
1 change: 0 additions & 1 deletion pytr/dl.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,6 @@ def dl_doc(self, doc, titleText, subtitleText, subfolder=None):
return
else:
filepath = filepath_with_doc_id

self.filepaths.append(filepath)

if filepath.is_file() is False:
Expand Down
79 changes: 63 additions & 16 deletions pytr/portfolio.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio

from pytr.utils import preview


Expand All @@ -8,39 +9,85 @@ def __init__(self, tr):

async def portfolio_loop(self):
recv = 0
await self.tr.portfolio()
# await self.tr.portfolio()
# recv += 1
await self.tr.compact_portfolio()
recv += 1
await self.tr.cash()
recv += 1
# await self.tr.available_cash_for_payout()
# recv += 1

while True:
_subscription_id, subscription, response = await self.tr.recv()
while recv > 0:
subscription_id, subscription, response = await self.tr.recv()

if subscription['type'] == 'portfolio':
recv += 1
recv -= 1
self.portfolio = response
elif subscription['type'] == 'compactPortfolio':
recv -= 1
self.portfolio = response
elif subscription['type'] == 'cash':
recv += 1
recv -= 1
self.cash = response
# elif subscription['type'] == 'availableCashForPayout':
# recv += 1
# recv -= 1
# self.payoutCash = response
else:
print(f"unmatched subscription of type '{subscription['type']}':\n{preview(response)}")

if recv == 2:
return
await self.tr.unsubscribe(subscription_id)

# Populate netValue for each ISIN
positions = self.portfolio['positions']
subscriptions = {}
for pos in sorted(positions, key=lambda x: x['netSize'], reverse=True):
isin = pos['instrumentId']
# subscription_id = await self.tr.instrument_details(pos['instrumentId'])
subscription_id = await self.tr.ticker(isin, exchange='LSX')
subscriptions[subscription_id] = pos

while len(subscriptions) > 0:
subscription_id, subscription, response = await self.tr.recv()

if subscription['type'] == 'ticker':
await self.tr.unsubscribe(subscription_id)
pos = subscriptions[subscription_id]
subscriptions.pop(subscription_id, None)
pos['netValue'] = response['last']['price'] * pos['netSize']
else:
print(f"unmatched subscription of type '{subscription['type']}':\n{preview(response)}")

# Populate name for each ISIN
subscriptions = {}
for pos in sorted(positions, key=lambda x: x['netSize'], reverse=True):
isin = pos['instrumentId']
subscription_id = await self.tr.instrument_details(pos['instrumentId'])
subscriptions[subscription_id] = pos

while len(subscriptions) > 0:
subscription_id, subscription, response = await self.tr.recv()

if subscription['type'] == 'instrument':
await self.tr.unsubscribe(subscription_id)
pos = subscriptions[subscription_id]
subscriptions.pop(subscription_id, None)
pos['name'] = response['shortName']
else:
print(f"unmatched subscription of type '{subscription['type']}':\n{preview(response)}")

def overview(self):
for x in ['netValue', 'unrealisedProfit', 'unrealisedProfitPercent', 'unrealisedCost']:
print(f'{x:24}: {self.portfolio[x]:>10.2f}')
print()
# for x in ['netValue', 'unrealisedProfit', 'unrealisedProfitPercent', 'unrealisedCost']:
# print(f'{x:24}: {self.portfolio[x]:>10.2f}')
# print()

print('ISIN avgCost * quantity = buyCost -> netValue diff %-diff')
print('Name ISIN avgCost * quantity = buyCost -> netValue diff %-diff')
totalBuyCost = 0.0
totalNetValue = 0.0
positions = self.portfolio['positions']
for pos in sorted(positions, key=lambda x: x['netValue'], reverse=True):
buyCost = pos['unrealisedAverageCost'] * pos['netSize']
for pos in sorted(positions, key=lambda x: x['netSize'], reverse=True):
# pos['netValue'] = 0 # TODO: Update the value from each Stock request
buyCost = pos['averageBuyIn'] * pos['netSize']
diff = pos['netValue'] - buyCost
if buyCost == 0:
diffP = 0.0
Expand All @@ -50,11 +97,11 @@ def overview(self):
totalNetValue += pos['netValue']

print(
f"{pos['instrumentId']} {pos['unrealisedAverageCost']:>10.2f} * {pos['netSize']:>10.2f}"
f"{pos['name']:<25} {pos['instrumentId']} {pos['averageBuyIn']:>10.2f} * {pos['netSize']:>10.2f}"
+ f" = {buyCost:>10.2f} -> {pos['netValue']:>10.2f} {diff:>10.2f} {diffP:>7.1f}%"
)

print('ISIN avgCost * quantity = buyCost -> netValue diff %-diff')
print('Name ISIN avgCost * quantity = buyCost -> netValue diff %-diff')
print()

diff = totalNetValue - totalBuyCost
Expand Down

0 comments on commit ea02920

Please sign in to comment.