Hello,
I am using api.get_position(symbol) to check if I have a position for a given stock. But if the position is 0, it returns an error. Is there a way to return position of 0?
Thanks,
Jack
Hello,
I am using api.get_position(symbol) to check if I have a position for a given stock. But if the position is 0, it returns an error. Is there a way to return position of 0?
Thanks,
Jack
You can use a try except
statement to check for an error and then set to 0. Maybe something like this
try:
pos_qty = float(api.get_position('IBM').qty)
except Exception as exception:
if exception.__str__() == 'position does not exist':
pos_qty = 0
However, I personally would load all the positions into a dataframe and then query the dataframe rather than using the API to check each individual position. Having the positions in a dataframe also makes the data easily available all in one place. Something like this
# First get all the positions into a dataframe indexed by symbol
import pandas as pd
my_positions = api.list_positions()
my_positions_df = pd.DataFrame([position._raw for position in my_positions])
my_positions_df.set_index('symbol', inplace=True)
# Then check if a particular stock is in the index
if my_stock in my_positions_df.index:
qty = float(my_positions_df.at[my_stock, 'qty'])
else:
qty = 0
Hope that helps.
Very helpful!! Thank you for posting this