Skip to content

Commit

Permalink
Model Interest Paid on Leveraged Assets
Browse files Browse the repository at this point in the history
Implements IMarginInterestModel interface to model interest paid on leveraged assets.
Implements a ConstantMarginInterestModel to model a constant interest paid.
Modifies SecurityPortfolioManager and AlgorithmManager to enable the margin interest modelling.
Adds MarginInterestTests to test the implementation
Ref: issue QuantConnect#32
  • Loading branch information
AlexCatarino committed Jun 29, 2016
1 parent aed2136 commit 6cf5eb7
Show file tree
Hide file tree
Showing 7 changed files with 403 additions and 2 deletions.
102 changes: 102 additions & 0 deletions Common/Orders/MarginInterest/ConstantMarginInterestModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using System;
using QuantConnect.Securities;
using System.Linq;

namespace QuantConnect.Orders.MarginInterest
{
/// <summary>
/// Provides an order margin interest model that always returns the same margin interest.
/// </summary>
public class ConstantMarginInterestModel : IMarginInterestModel
{
private const int _daysPerYear = 365;
private readonly decimal _marginInterestRate;
private decimal _totalInterestPaid;

/// <summary>
/// Total interest paid during the algorithm operation across all securities in portfolio.
/// </summary>
public decimal TotalInterestPaid
{
get
{
return _totalInterestPaid;
}
}

/// <summary>
/// Initializes a new instance of the <see cref="ConstantMarginInterestModel"/> class with the specified <paramref name="marginInterestRate"/>
/// </summary>
/// <param name="marginInterestRate">The constant annual margin interest rate used by the model</param>
public ConstantMarginInterestModel(decimal marginInterestRate)
{
_marginInterestRate = marginInterestRate;
_totalInterestPaid = 0m;
}

/// <summary>
/// Gets the margin interest associated with the total loan in our portfolio.
/// This returns the cost of the borrowed money in the account currency
/// </summary>
/// <param name="securities">Securities collection for the portfolio summation</param>
/// <param name="applicationTimeUtc">Time margin interest payment is made</param>
/// <param name="totalMarginUsed">Total amount of margin used</param>
public decimal PayMarginInterest(SecurityManager securities, DateTime applicationTimeUtc, decimal totalMarginUsed)
{
if (totalMarginUsed == 0)
{
return 0m;
}

var totalHoldingsValue = securities.Values.Sum(x => x.Holdings.HoldingsValue);
if (totalHoldingsValue <= 0)
{
return 0m;
}

var holdingDays = int.MaxValue;

foreach (var security in securities)
{
// If market was opened this date, check if previous day(s) were closed
if (security.Value.Exchange.DateIsOpen(applicationTimeUtc))
{
var past = 1;
while (!security.Value.Exchange.DateIsOpen(applicationTimeUtc.AddDays(-past)))
{
past++;
}
holdingDays = Math.Min(holdingDays, past - 1);
}
else
{
holdingDays = -1;
}
}

holdingDays++;

var factor = _marginInterestRate / _daysPerYear * holdingDays;
var marginInterest = totalMarginUsed * factor;

_totalInterestPaid += marginInterest;

return marginInterest;
}
}
}
40 changes: 40 additions & 0 deletions Common/Orders/MarginInterest/IMarginInterestModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using QuantConnect.Securities;
using System;

namespace QuantConnect.Orders.MarginInterest
{
/// <summary>
/// Represents a model the simulates margin interest
/// </summary>
public interface IMarginInterestModel
{
/// <summary>
/// Total interest paid during the algorithm operation across all securities in portfolio.
/// </summary>
decimal TotalInterestPaid { get; }

/// <summary>
/// Gets the margin interest associated with the total loan in our portfolio.
/// This returns the cost of the borrowed money in the account currency
/// </summary>
/// <param name="securities">Securities collection for the portfolio summation</param>
/// <param name="applicationTimeUtc">Time margin interest payment is made</param>
/// <param name="totalMarginUsed">Total amount of margin used</param>
decimal PayMarginInterest(SecurityManager securities, DateTime applicationTimeUtc, decimal totalMarginUsed);
}
}
2 changes: 2 additions & 0 deletions Common/QuantConnect.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@
<Compile Include="Orders\Fees\IFeeModel.cs" />
<Compile Include="Orders\Fills\ImmediateFillModel.cs" />
<Compile Include="Orders\Fills\IFillModel.cs" />
<Compile Include="Orders\MarginInterest\ConstantMarginInterestModel.cs" />
<Compile Include="Orders\MarginInterest\IMarginInterestModel.cs" />
<Compile Include="Orders\MarketOnCloseOrder.cs" />
<Compile Include="Orders\MarketOnOpenOrder.cs" />
<Compile Include="Orders\OrderField.cs" />
Expand Down
32 changes: 30 additions & 2 deletions Common/Securities/SecurityPortfolioManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using System.Linq;
using QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Orders.MarginInterest;

namespace QuantConnect.Securities
{
Expand Down Expand Up @@ -48,6 +49,11 @@ public class SecurityPortfolioManager : IDictionary<Symbol, SecurityHolding>, IS
/// </summary>
public CashBook UnsettledCashBook { get; private set; }

/// <summary>
/// Models the margin interest paid on leveraged assets
/// </summary>
public IMarginInterestModel MarginInterestModel { get; set; }

/// <summary>
/// The list of pending funds waiting for settlement time
/// </summary>
Expand All @@ -59,7 +65,7 @@ public class SecurityPortfolioManager : IDictionary<Symbol, SecurityHolding>, IS
// Record keeping variables
private readonly Cash _baseCurrencyCash;
private readonly Cash _baseCurrencyUnsettledCash;

/// <summary>
/// Initialise security portfolio manager.
/// </summary>
Expand All @@ -71,6 +77,7 @@ public SecurityPortfolioManager(SecurityManager securityManager, SecurityTransac

CashBook = new CashBook();
UnsettledCashBook = new CashBook();
MarginInterestModel = new ConstantMarginInterestModel(0m);
_unsettledCashAmounts = new List<UnsettledCashAmount>();

_baseCurrencyCash = CashBook[CashBook.AccountCurrency];
Expand Down Expand Up @@ -384,6 +391,17 @@ public decimal TotalFees
}
}

/// <summary>
/// Total interest paid during the algorithm operation across all securities in portfolio.
/// </summary>
public decimal TotalInterestPaid
{
get
{
return MarginInterestModel.TotalInterestPaid;
}
}

/// <summary>
/// Sum of all gross profit across all securities in portfolio.
/// </summary>
Expand All @@ -392,7 +410,7 @@ public decimal TotalProfit
get
{
return (from position in Securities.Values
select position.Holdings.Profit).Sum();
select position.Holdings.Profit).Sum() - TotalInterestPaid;
}
}

Expand Down Expand Up @@ -584,6 +602,16 @@ public List<SubmitOrderRequest> ScanForMarginCall(out bool issueMarginCallWarnin
return marginCallOrders;
}

/// <summary>
/// Pay interest on the borrowed funds (margin interest)
/// </summary>
/// <param name="time">Time margin interest is payed</param>
public void PayMarginInterest(DateTime time)
{
var marginInterestPayment = MarginInterestModel.PayMarginInterest(Securities, time, TotalMarginUsed);
_baseCurrencyCash.AddAmount(-marginInterestPayment);
}

/// <summary>
/// Applies a dividend to the portfolio
/// </summary>
Expand Down
8 changes: 8 additions & 0 deletions Engine/AlgorithmManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ public void Run(AlgorithmNodePacket job, IAlgorithm algorithm, IDataFeed feed, I
var nextMarginCallTime = DateTime.MinValue;
var settlementScanFrequency = TimeSpan.FromMinutes(30);
var nextSettlementScanTime = DateTime.MinValue;
var nextMidnight = DateTime.MinValue;

var delistingTickets = new List<OrderTicket>();

Expand Down Expand Up @@ -358,6 +359,13 @@ public void Run(AlgorithmNodePacket job, IAlgorithm algorithm, IDataFeed feed, I
break;
}

// perform overnight updates
if (time >= nextMidnight)
{
algorithm.Portfolio.PayMarginInterest(time);
nextMidnight = time.Date.AddDays(1);
}

// perform margin calls, in live mode we can also use realtime to emit these
if (time >= nextMarginCallTime || (_liveMode && nextMarginCallTime > DateTime.UtcNow))
{
Expand Down

0 comments on commit 6cf5eb7

Please sign in to comment.