开云体育

ctrl + shift + ? for shortcuts
© 2025 开云体育

Determining which stock is bringing my portfolio into a loss


 

Hi all,

I am trying to write some code to determine which stock is bringing my
portfolio into a loss.

My logic is to see if the averageCost is greater than the current market
price for each stock in the portfolio.

The problem is that the current market price is nan. I am running this code
after market close. Here is the relevant snippet. What am I missing?
ib.connect('127.0.0.1', 4001, clientId=999990)
positions=ib.positions()
lc=0
for p in positions:

[ticker] = ib.reqTickers(p.contract)
print(p.contract.symbol)

print("number of shares=" + str(p.position))
print("Cost per share=",ib.portfolio()[lc].averageCost)
print("Current price per share=",ticker.marketPrice())

lc+=1
ib.sleep(1)
Pranav


 

Have a look at my reply to another topic, I think it is closely related to your issue because you are requesting after close: /g/ib-async/message/302


 

开云体育

Hi,

?

Yes, setting the market data type to 2 solved the problem.

?

Pranav

From: [email protected] <[email protected]> On Behalf Of biney59 via groups.io
Sent: Friday, April 4, 2025 11:19 PM
To: [email protected]
Subject: Re: [ib-async] Determining which stock is bringing my portfolio into a loss

?

Have a look at my reply to another topic, I think it is closely related to your issue because you are requesting after close: /g/ib-async/message/302


 

开云体育

I'm curious, does it work during regular trading hours?





-------- Original message --------
From: "Pranav Lal via groups.io" <pranav@...>
Date: 2025-04-03 6:26 p.m. (GMT-08:00)
Subject: [ib-async] Determining which stock is bringing my portfolio into a loss

Hi all,

I am trying to write some code to determine which stock is bringing my
portfolio into a loss.

My logic is to see if the averageCost is greater than the current market
price for each stock in the portfolio.

The problem is that the current market price is nan. I am running this code
after market close. Here is the relevant snippet. What am I missing?
ib.connect('127.0.0.1', 4001, clientId=999990)
positions=ib.positions()
lc=0
for p in positions:

[ticker] = ib.reqTickers(p.contract)
print(p.contract.symbol)

print("number of shares=" + str(p.position))
print("Cost per share=",ib.portfolio()[lc].averageCost)
print("Current price per share=",ticker.marketPrice())

lc+=1
ib.sleep(1)
Pranav