---
title: "Key Concepts"
description: "Margin interest rate models model margin interest payments by directly adding or removing cash from your portfolio."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/margin-interest-rate/key-concepts
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/margin-interest-rate/key-concepts.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/24%20Reality%20Modeling/12%20Margin%20Interest%20Rate/01%20Key%20Concepts
modified: 2026-11-02
index: https://www.quantconnect.com/llms.txt
---

# Key Concepts

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Writing Algorithms](https://www.quantconnect.com/docs/v2/writing-algorithms.md) > Reality Modeling > Margin Interest Rate > Key Concepts

> Code examples are shown in Python. Append `?lang=csharp` to this URL for the C# version of this page.

## Introduction

Margin interest is a cost associated with trading on margin. Margin interest rate models model margin interest cash flows by directly adding or removing cash from your portfolio.

## Set Models

The brokerage model of your algorithm automatically sets the margin interest rate model for each security, but you can override it. To manually set the margin interest rate model of a security, assign a model to the `MarginInterestRateModel` property of the Security object.

```python
def initialize(self) -> None:
    security = self.add_equity("SPY")
    # For US Equity, use the ShortMarginInterestRateModel with IB data
    security.set_shortable_provider(InteractiveBrokersShortableProvider())
    security.margin_interest_rate_model = ShortMarginInterestRateModel()
```

You can also set the margin interest rate model in a [security initializer](https://www.quantconnect.com/docs/v2/writing-algorithms/initialization.md#07-Set-Security-Initializer). If your algorithm has a dynamic universe, use the security initializer technique. In order to initialize single security subscriptions with the security initializer, call `add_security_initializer` before you create the subscriptions.

```python
class AddSecurityInitializerExampleAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        # In the Initialize method, set the security initializer to set models of assets.
        self.add_security_initializer(self._custom_security_initializer)

    def _custom_security_initializer(self, security: Security) -> None:
        # Overwrite some of the reality models
        security.set_shortable_provider(InteractiveBrokersShortableProvider())
        security.margin_interest_rate_model = ShortMarginInterestRateModel()
```

To view all the pre-built margin interest rate models, see [Supported Models](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/margin-interest-rate/supported-models.md).

## Default Behavior

The brokerage model of your algorithm automatically sets the margin interest rate model of each security. The default brokerage model is the `DefaultBrokerageModel`, which sets the [NullMarginInterestRateModel](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/margin-interest-rate/supported-models.md#02-Null-Model).

## Model Structure

Margin interest rate models should implement the `IMarginInterestRateModel` interface. Extensions of the `IMarginInterestRateModel` interface must implement the `apply_margin_interest_rate` method, which applies margin interest payments to the portfolio.

```python
class CustomMarginInterestRateModelExampleAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        security = self.add_equity("SPY")
        # You should set it according to your broker information for the least actual-expected discrepancies
        security.set_margin_interest_rate_model(MyMarginInterestRateModel())

# Define the custom margin interest rate model
class MyMarginInterestRateModel:

    def apply_margin_interest_rate(self, margin_interest_rate_parameters: MarginInterestRateParameters) -> None:
        holdings = margin_interest_rate_parameters.security.holdings
        position_value = holdings.get_quantity_value(holdings.quantity)
        position_value.cash.add_amount(-1)
```

The `apply_margin_interest_rate` method is automatically called at the top of each hour.

## Examples

The following examples demonstrate some common practices for implementing a custom margin interest rate model.

### Example 1: Based On Interest Rate

The following algorithm buys and holds SPY, with 2x leverage and holds 1.5x of portfolio value. Hence, funds will be borrowed from the broker and are susceptible to margin interest. We implement a custom margin interest rate model to simulate the [Interactive Brokers](https://qnt.co/interactive-brokers) margin interest deduction. While following daily accrual and monthly accounting of the margin interest, we simplify the rate from tiered to fixed at 1% above the current interest rate.

```python
class MarginInterestRateModelAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(1000000)

        # Request SPY data for trading.
        equity = self.add_equity("SPY")
        self.spy = equity.symbol
        # Set a custom margin interest rate model for the SPY security to mimic IB margin interest deduction.
        equity.set_margin_interest_rate_model(MyMarginInterestRateModel(self, self.spy))

    def on_data(self, slice: Slice) -> None:
        if not self.portfolio.invested:
            # Place a position that exceeds available cash to buy with borrowed funds.
            self.set_holdings(self.spy, 1.5)

# Define the custom margin interest rate model
class MyMarginInterestRateModel:
    accrued_margin_interest = {}

    def __init__(self, algorithm: QCAlgorithm, symbol: Symbol) -> None:
        # Save the algorithm instance since we must access the at-the-time interest rate to calculate the margin rate.
        self.algorithm = algorithm
        # IBKR accrues interest daily and posts actual interest monthly on the third business day of the following month.
        algorithm.schedule.on(
            algorithm.date_rules.month_start(symbol, 3),
            algorithm.time_rules.at(0, 0),
            self.margin_deduction
        )

    def margin_deduction(self) -> None:
        for cash, accrued_interest in self.accrued_margin_interest.items():
            # Monthly deduction of cash position with accrued interests.
            cash.add_amount(accrued_interest)
            # Reset the accrued interest accumulator.
            self.accrued_margin_interest[cash] = 0

    def apply_margin_interest_rate(self, margin_interest_rate_parameters: MarginInterestRateParameters) -> None:
        # IBKR accrues interest daily for overnight positions only.
        if self.algorithm.time.hour == 16:
            holdings = margin_interest_rate_parameters.security.holdings
            # Calculate the borrowed capital. The margin interest will only applied to the borrowed capital.
            borrowed_value = holdings.unlevered_absolute_holdings_cost - holdings.absolute_holdings_cost
            # Margin interest rate is 1% above the current risk-free interest rate.
            margin_rate = self.algorithm.risk_free_interest_rate_model.get_interest_rate(self.algorithm.time) + 0.01
            # Deduct the margin interest on the account cash position by the margin rate, multiplying the borrowed sum.
            cash = holdings.get_quantity_value(holdings.quantity).cash
            if cash not in self.accrued_margin_interest:
                self.accrued_margin_interest[cash] = 0
            # Daily rate will be divided by 365.
            self.accrued_margin_interest[cash] += borrowed_value * margin_rate / 365
```

### Example 2: Fixed Dollar Rate

The following algorithm defines custom margin interest rate model that reduces your cash by $1 at the top of each hour.

```python
class CustomFillModelAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(100000)

        security = self.add_equity('SPY', Resolution.DAILY)
        security.set_margin_interest_rate_model(MyMarginInterestRateModel())

    def on_data(self, data: Slice) -> None:
        if not self.portfolio.invested:
            self.set_holdings('SPY', 1)

class MyMarginInterestRateModel:

    def apply_margin_interest_rate(self, margin_interest_rate_parameters: MarginInterestRateParameters) -> None:
        holdings = margin_interest_rate_parameters.security.holdings
        position_value = holdings.get_quantity_value(holdings.quantity)
        position_value.cash.add_amount(-1)
```
