SecurityPortfolioManager
QuantConnect.Securities.SecurityPortfolioManager
SecurityPortfolioManager(
security_manager: SecurityManager,
transactions: SecurityTransactionManager,
algorithm_settings: IAlgorithmSettings,
default_order_properties: IOrderProperties = None,
)
Bases: ExtendedDictionary[Symbol, SecurityHolding], IDictionary[Symbol, SecurityHolding], ISecurityProvider, Iterable[KeyValuePair[Symbol, SecurityHolding]]
Portfolio manager class groups popular properties and makes them accessible through one interface. It also provide indexing by the vehicle symbol to get the Security.Holding objects.
Initialise security portfolio manager.
securities
securities: SecurityManager
Local access to the securities collection for the portfolio summation.
transactions
transactions: SecurityTransactionManager
Local access to the transactions collection for the portfolio summation and updates.
cash_book
cash_book: CashBook
Gets the cash book that keeps track of all currency holdings (only settled cash)
unsettled_cash_book
unsettled_cash_book: CashBook
Gets the cash book that keeps track of all currency holdings (only unsettled cash)
count
count: int
Count the securities objects in the portfolio.
is_read_only
is_read_only: bool
Check if the underlying securities array is read only.
get_keys
get_keys: Iterable[Symbol]
Gets an System.Collections.Generic.ICollection{T} containing the Symbol objects of the System.Collections.Generic.IDictionary{TKey, TValue}.
This codeEntityType is protected.
get_values
get_values: Iterable[SecurityHolding]
Gets an System.Collections.Generic.ICollection{T} containing the values in the System.Collections.Generic.IDictionary{TKey, TValue}.
This codeEntityType is protected.
cash
cash: float
Sum of all currencies in account in US dollars (only settled cash)
unsettled_cash
unsettled_cash: float
Sum of all currencies in account in US dollars (only unsettled cash)
total_unlevered_absolute_holdings_cost
total_unlevered_absolute_holdings_cost: float
Absolute value of cash discounted from our total cash by the holdings we own.
total_absolute_holdings_cost
total_absolute_holdings_cost: float
Gets the total absolute holdings cost of the portfolio. This sums up the individual absolute cost of each holding
total_holdings_value
total_holdings_value: float
Absolute sum the individual items in portfolio.
hold_stock
hold_stock: bool
Boolean flag indicating we have any holdings in the portfolio.
invested
invested: bool
Alias for HoldStock. Check if we have any holdings.
total_unrealised_profit
total_unrealised_profit: float
Get the total unrealised profit in our portfolio from the individual security unrealized profits.
total_unrealized_profit
total_unrealized_profit: float
Get the total unrealised profit in our portfolio from the individual security unrealized profits.
total_portfolio_value
total_portfolio_value: float
Total portfolio value if we sold all holdings at current market rates.
total_portfolio_value_less_free_buffer
total_portfolio_value_less_free_buffer: float
Returns the adjusted total portfolio value removing the free amount If the IAlgorithmSettings.free_portfolio_value has not been set, the free amount will have a trailing behavior and be updated when requested
total_fees
total_fees: float
Total fees paid during the algorithm operation across all securities in portfolio.
total_profit
total_profit: float
Sum of all gross profit across all securities in portfolio and dividend payments.
total_net_profit
total_net_profit: float
Sum of all net profit across all securities in portfolio and dividend payments.
total_sale_volume
total_sale_volume: float
Total sale volume since the start of algorithm operations.
total_margin_used
total_margin_used: float
Gets the total margin used across all securities in the account's currency
margin_remaining
margin_remaining: float
Gets the remaining margin on the account in the account's currency
margin_call_model
margin_call_model: IMarginCallModel
Gets or sets the margin_call_model for the portfolio. This is used to executed margin call orders.
__contains__
__contains__(
symbol: Union[Symbol, str, BaseContract],
) -> bool
__contains__(key: Union[Symbol, str, BaseContract]) -> bool
Signature descriptions:
-
Check if the portfolio contains this symbol string.
-
Checks if the dictionary contains the specified key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[Union[Symbol, str, BaseContract]]
|
String search symbol for the security |
None
|
key
|
Optional[Union[Symbol, str, BaseContract]]
|
The key to locate in the dictionary |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
Depends on the signature used. Case 1: [Boolean true if portfolio contains this symbol.]; Case 2: [true if the dictionary contains an element with the specified key; otherwise, false.] |
__getitem__
__getitem__(
symbol: Union[Symbol, str, BaseContract],
) -> SecurityHolding
__getitem__(
key: Union[Symbol, str, BaseContract],
) -> SecurityHolding
Signature descriptions:
-
Indexer for the PortfolioManager class to access the underlying security holdings objects.
-
Indexer method for the base dictioanry to access the objects by their symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[Union[Symbol, str, BaseContract]]
|
Symbol object indexer |
None
|
key
|
Optional[Union[Symbol, str, BaseContract]]
|
Key object indexer |
None
|
Returns:
| Type | Description |
|---|---|
SecurityHolding
|
Depends on the signature used. Case 1: [SecurityHolding class from the algorithm securities.]; Case 2: [Object of t_value.] |
__setitem__
__setitem__(
symbol: Union[Symbol, str, BaseContract],
value: SecurityHolding,
) -> None
__setitem__(
key: Union[Symbol, str, BaseContract],
value: SecurityHolding,
) -> None
Signature descriptions:
-
Indexer for the PortfolioManager class to access the underlying security holdings objects.
-
Indexer method for the base dictioanry to access the objects by their symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[Union[Symbol, str, BaseContract]]
|
Symbol object indexer |
None
|
key
|
Optional[Union[Symbol, str, BaseContract]]
|
Key object indexer |
None
|
Returns:
| Type | Description |
|---|---|
Optional[None]
|
Depends on the signature used. Case 1: [SecurityHolding class from the algorithm securities.]; Case 2: [Object of t_value.] |
add
add(
symbol: Union[Symbol, str, BaseContract],
holding: SecurityHolding,
) -> None
add(pair: KeyValuePair[Symbol, SecurityHolding]) -> None
Signature descriptions:
-
Add a new securities string-security to the portfolio.
-
Add a new securities key value pair to the portfolio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[Union[Symbol, str, BaseContract]]
|
Symbol of dictionary |
None
|
holding
|
Optional[SecurityHolding]
|
SecurityHoldings object |
None
|
pair
|
Optional[KeyValuePair[Symbol, SecurityHolding]]
|
Key value pair of dictionary |
None
|
contains_key
contains_key(
symbol: Union[Symbol, str, BaseContract],
) -> bool
contains_key(key: Union[Symbol, str, BaseContract]) -> bool
Signature descriptions:
-
Check if the portfolio contains this symbol string.
-
Checks if the dictionary contains the specified key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[Union[Symbol, str, BaseContract]]
|
String search symbol for the security |
None
|
key
|
Optional[Union[Symbol, str, BaseContract]]
|
The key to locate in the dictionary |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
Depends on the signature used. Case 1: [Boolean true if portfolio contains this symbol.]; Case 2: [true if the dictionary contains an element with the specified key; otherwise, false.] |
get
get(
key: Union[Symbol, str, BaseContract],
) -> SecurityHolding
get(
key: Union[Symbol, str, BaseContract],
value: SecurityHolding,
) -> SecurityHolding
Returns the value for the specified key if key is in dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Union[Symbol, str, BaseContract]
|
key to be searched in the dictionary |
required |
value
|
Optional[SecurityHolding]
|
Value to be returned if the key is not found. The default value is null. |
None
|
Returns:
| Type | Description |
|---|---|
SecurityHolding
|
The value for the specified key if key is in dictionary. |
get_margin_remaining
get_margin_remaining(total_portfolio_value: float) -> float
get_margin_remaining(
symbol: Union[Symbol, str, BaseContract],
direction: OrderDirection = ...,
) -> float
Gets the remaining margin on the account in the account's currency for the given total portfolio value
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
total_portfolio_value
|
Optional[float]
|
The total portfolio value total_portfolio_value |
None
|
pop
pop(
key: Union[Symbol, str, BaseContract],
) -> SecurityHolding
pop(
key: Union[Symbol, str, BaseContract],
default_value: SecurityHolding,
) -> SecurityHolding
Removes and returns an element from a dictionary having the given key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Union[Symbol, str, BaseContract]
|
Key which is to be searched for removal |
required |
default_value
|
Optional[SecurityHolding]
|
Value which is to be returned when the key is not in the dictionary |
None
|
Returns:
| Type | Description |
|---|---|
SecurityHolding
|
If key is found - removed/popped element from the dictionary |
remove
remove(pair: KeyValuePair[Symbol, SecurityHolding]) -> bool
remove(symbol: Union[Symbol, str, BaseContract]) -> bool
remove(key: Union[Symbol, str, BaseContract]) -> bool
Signature descriptions:
-
Remove this keyvalue pair from the portfolio.
-
Remove this symbol from the portfolio.
-
Removes the value with the specified key
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pair
|
Optional[KeyValuePair[Symbol, SecurityHolding]]
|
Key value pair of dictionary |
None
|
symbol
|
Optional[Union[Symbol, str, BaseContract]]
|
Symbol of dictionary |
None
|
key
|
Optional[Union[Symbol, str, BaseContract]]
|
The key object of the element to remove. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
true if the element is successfully found and removed; otherwise, false. |
set_cash
set_cash(cash: float) -> None
set_cash(
symbol: str, cash: float, conversion_rate: float
) -> None
Signature descriptions:
-
Set the account currency cash this algorithm is to manage.
-
Set the cash for the specified symbol
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cash
|
float
|
Decimal cash value of portfolio |
required |
symbol
|
Optional[str]
|
The cash symbol to set |
None
|
conversion_rate
|
Optional[float]
|
The current conversion rate for the |
None
|
set_margin_call_model
set_margin_call_model(py_object: Any) -> None
set_margin_call_model(
margin_call_model: IMarginCallModel,
) -> None
Sets the margin call model
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
py_object
|
Optional[Any]
|
Model that represents a portfolio's model to executed margin call orders. |
None
|
margin_call_model
|
Optional[IMarginCallModel]
|
Model that represents a portfolio's model to executed margin call orders. |
None
|
setdefault
setdefault(
key: Union[Symbol, str, BaseContract],
) -> SecurityHolding
setdefault(
key: Union[Symbol, str, BaseContract],
default_value: SecurityHolding,
) -> SecurityHolding
Returns the value of a key (if the key is in dictionary). If not, it inserts key with a value to the dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Union[Symbol, str, BaseContract]
|
Key with null/None value is inserted to the dictionary if key is not in the dictionary. |
required |
default_value
|
Optional[SecurityHolding]
|
Default value |
None
|
Returns:
| Type | Description |
|---|---|
SecurityHolding
|
The value of the key if it is in the dictionary |
try_get_value
try_get_value(
symbol: Union[Symbol, str, BaseContract],
holding: Optional[SecurityHolding],
) -> Tuple[bool, SecurityHolding]
try_get_value(
key: Union[Symbol, str, BaseContract],
value: Optional[SecurityHolding],
) -> Tuple[bool, SecurityHolding]
Signature descriptions:
-
Attempt to get the value of the securities holding class if this symbol exists.
-
Gets the value associated with the specified key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[Union[Symbol, str, BaseContract]]
|
String search symbol |
None
|
holding
|
Optional[Optional[SecurityHolding]]
|
Holdings object of this security |
None
|
key
|
Optional[Union[Symbol, str, BaseContract]]
|
The key whose value to get. |
None
|
value
|
Optional[Optional[SecurityHolding]]
|
When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[bool, SecurityHolding]
|
Depends on the signature used. Case 1: [Boolean true if successful locating and setting the holdings object.]; Case 2: [true if the object that implements System.Collections.Generic.IDictionary`2 contains an element with the specified key; otherwise, false.] |
__len__
__len__() -> int
add_transaction_record
add_transaction_record(
time: Union[datetime, date],
transaction_profit_loss: float,
is_win: bool,
) -> None
Record the transaction value and time in a list to later be processed for statistics creation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time
|
Union[datetime, date]
|
Time of order processed |
required |
transaction_profit_loss
|
float
|
Profit Loss. |
required |
is_win
|
bool
|
Whether the transaction is a win. For options exercise, this might not depend only on the profit/loss value |
required |
apply_dividend
apply_dividend(
dividend: Dividend,
live_mode: bool,
mode: DataNormalizationMode,
) -> None
Applies a dividend to the portfolio
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dividend
|
Dividend
|
The dividend to be applied |
required |
live_mode
|
bool
|
True if live mode, false for backtest |
required |
mode
|
DataNormalizationMode
|
The DataNormalizationMode for this security |
required |
apply_split
apply_split(
split: Split,
security: Security,
live_mode: bool,
mode: DataNormalizationMode,
) -> None
Applies a split to the portfolio
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
split
|
Split
|
The split to be applied |
required |
security
|
Security
|
The security the split will be applied to |
required |
live_mode
|
bool
|
True if live mode, false for backtest |
required |
mode
|
DataNormalizationMode
|
The DataNormalizationMode for this security |
required |
clear
clear() -> None
Clear the portfolio of securities objects.
contains
contains(
pair: KeyValuePair[Symbol, SecurityHolding],
) -> bool
Check if the key-value pair is in the portfolio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pair
|
KeyValuePair[Symbol, SecurityHolding]
|
Pair we're searching for |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if we have this object. |
copy_to
copy_to(
array: List[KeyValuePair[Symbol, SecurityHolding]],
index: int,
) -> None
Copy contents of the portfolio collection to a new destination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
List[KeyValuePair[Symbol, SecurityHolding]]
|
Destination array |
required |
index
|
int
|
Position in array to start copying |
required |
get_buying_power
get_buying_power(
symbol: Union[Symbol, str, BaseContract],
direction: OrderDirection = ...,
) -> float
Gets the margin available for trading a specific symbol in a specific direction. Alias for get_margin_remaining(Symbol, OrderDirection)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Union[Symbol, str, BaseContract]
|
The symbol to compute margin remaining for |
required |
direction
|
OrderDirection
|
The order/trading direction |
...
|
Returns:
| Type | Description |
|---|---|
float
|
The maximum order size that is currently executable in the specified direction. |
get_items
get_items() -> (
Iterable[KeyValuePair[Symbol, SecurityHolding]]
)
Gets all the items in the dictionary
Returns:
| Type | Description |
|---|---|
Iterable[KeyValuePair[Symbol, SecurityHolding]]
|
All the items in the dictionary. |
has_sufficient_buying_power_for_order
has_sufficient_buying_power_for_order(
orders: List[Order],
) -> HasSufficientBuyingPowerForOrderResult
Will determine if the algorithms portfolio has enough buying power to fill the given orders
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
orders
|
List[Order]
|
The orders to check |
required |
Returns:
| Type | Description |
|---|---|
HasSufficientBuyingPowerForOrderResult
|
True if the algorithm has enough buying power available. |
invalidate_total_portfolio_value
invalidate_total_portfolio_value() -> None
Will flag the current total_portfolio_value as invalid so it is recalculated when gotten
log_margin_information
log_margin_information(
order_request: OrderRequest = None,
) -> None
Logs margin information for debugging
process_fills
process_fills(fills: List[OrderEvent]) -> None
Calculate the new average price after processing a list of partial/complete order fill events.
set_account_currency
set_account_currency(
account_currency: str,
starting_cash: Optional[float] = None,
) -> None
Sets the account currency cash symbol this algorithm is to manage, as well as the starting cash in this currency if given
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
account_currency
|
str
|
The account currency cash symbol to set |
required |
starting_cash
|
Optional[float]
|
The account currency starting cash to set |
None
|
set_positions
set_positions(
position_group_model: SecurityPositionGroupModel,
) -> None
Will set the security position group model to use
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
position_group_model
|
SecurityPositionGroupModel
|
The position group model instance |
required |
get_security
get_security(
symbol: Union[Symbol, str, BaseContract],
) -> Security
Retrieves a summary of the holdings for the specified symbol
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Union[Symbol, str, BaseContract]
|
The symbol to get holdings for |
required |
Returns:
| Type | Description |
|---|---|
Security
|
The holdings for the symbol or null if the symbol is invalid and/or not in the portfolio. |
fromkeys
fromkeys(
sequence: List[QuantConnect_ExtendedDictionary_TKey],
) -> Dict[Any, Any]
fromkeys(
sequence: List[QuantConnect_ExtendedDictionary_TKey],
value: QuantConnect_ExtendedDictionary_TValue,
) -> Dict[Any, Any]
Signature descriptions:
-
Creates a new dictionary from the given sequence of elements.
-
Creates a new dictionary from the given sequence of elements with a value provided by the user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sequence
|
List[QuantConnect_ExtendedDictionary_TKey]
|
Sequence of elements which is to be used as keys for the new dictionary |
required |
value
|
Optional[QuantConnect_ExtendedDictionary_TValue]
|
Value which is set to each each element of the dictionary |
None
|
Returns:
| Type | Description |
|---|---|
Dict[Any, Any]
|
Returns a new dictionary with the given sequence of elements as the keys of the dictionary. |
copy
copy() -> Dict[Any, Any]
Creates a shallow copy of the IExtendedDictionary{TKey, TValue}.
Returns:
| Type | Description |
|---|---|
Dict[Any, Any]
|
Returns a shallow copy of the dictionary. It doesn't modify the original dictionary. |
items
items() -> List[Any]
Returns a view object that displays a list of dictionary's (key, value) tuple pairs.
Returns:
| Type | Description |
|---|---|
List[Any]
|
Returns a view object that displays a list of a given dictionary's (key, value) tuple pair. |
keys
keys() -> List[Any]
Returns a view object that displays a list of all the key objects in the dictionary
Returns:
| Type | Description |
|---|---|
List[Any]
|
Returns a view object that displays a list of all the key objects. When the dictionary is changed, the view object also reflect these changes. |
popitem
popitem() -> Any
Returns and removes an arbitrary element (key, value) pair from the dictionary.
Returns:
| Type | Description |
|---|---|
Any
|
Returns an arbitrary element (key, value) pair from the dictionary removes an arbitrary element(the same element which is returned) from the dictionary. Note: Arbitrary elements and random elements are not same.The popitem() doesn't return a random element. |
update
update(other: Any) -> None
Updates the dictionary with the elements from the another dictionary object or from an iterable of key/value pairs. The update() method adds element(s) to the dictionary if the key is not in the dictionary.If the key is in the dictionary, it updates the key with the new value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
Takes either a dictionary or an iterable object of key/value pairs (generally tuples). |
required |
values
values() -> List[Any]
Returns a view object that displays a list of all the values in the dictionary.
Returns:
| Type | Description |
|---|---|
List[Any]
|
Returns a view object that displays a list of all values in a given dictionary. |
check_for_implicitly_created_symbol
check_for_implicitly_created_symbol(
symbol: Union[Symbol, str, BaseContract],
) -> None
Checks if the symbol is implicitly created from a string, in which case it is not in the symbol cache, and throws a KeyNotFoundException.
This codeEntityType is protected.