Back

Check if portfolio has shares or options separately

Hi, is there some method that can tell me when I own some stock or only its options?

I tried to use Portfolio.IsInvested() but it returns TRUE for both, stocks and options, meanwhile, I don't want it give info about options, I want to check if I own the stock only.

Example.

I sell naked put option, then I'm assigned to execute this option, so I have to buy underlying shares. I don't want to own shares, so I need to check and if I own any shares (not options) I want to sell shares. Basically, I need some method that works with shares only and doesn't affect options.

Update Backtest








I think I've found answer to my first question.

if (Portfolio["SPY"].Invested)    // Check if stock is in portfolio, option name will look differently, e.g. "201802010000 SPY"
{
    MarketOrder("SPY", -100);  // Selll stock only and leave the options
}
else if (Portfolio.Invested == false) { }   // Check everything else, stock + options

Although, there is another issue, in some reason options chain doesn't return me options on SPY after 2018-02-28.

Any ideas why?

0


i once searched the same answer for this problem and the quantconnect staff pointed me to the text in the documentation which i do now, so hopefully it helps you when you again will read it because you already read it like me :) :) :)

twice in the documentation:

Portfolio is a dictionary of SecurityHolding classes. These classes track the individual portfolio items profit and losses, fees and quantity held. e.g. Portfolio["IBM"].LastTradeProfit .

&

The Portfolio property is a collection of SecurityHolding objects to provide easy access to the holding properties. The Portfolio class is a Dictionary<Symbol, SecurityHolding> so can be accessed via ticker index: Portfolio["IBM"].IsLong

so when you loop through this key-value-pair you will get...........

https://www.quantconnect.com/docs/algorithm-reference/overview#Overview-Introductionhttps://www.quantconnect.com/docs/algorithm-reference/securities-and-portfolio#Securities-and-Portfolio-Introduction
1

Thanks, I've already figured it out, I could even get list of all assets in my portfolio 

string.Join(";", Portfolio.Select(x => x.Key + "=" + x.Value).ToArray());

Now I'm trying to figure out how to get weekly options, because documentation shows how to do this with SetFilter(), but doesn't explain how to do it with OptionChainProvider

var option = AddOption(UnderlyingTicker);
option.SetFilter(u => u.IncludeWeeklys().Strikes(-2, +2).Expiration(TimeSpan.Zero, TimeSpan.FromDays(10)));

How to do this with OptionChainProvider?

0

search for setfilter maybe it helps you...

algos provided by quantconnect team

https://github.com/QuantConnect/Lean/blob/master/Algorithm.CSharp/OptionChainConsistencyRegressionAlgorithm.cshttps://github.com/QuantConnect/Lean/blob/master/Algorithm.CSharp/OptionExerciseAssignRegressionAlgorithm.cshttps://github.com/QuantConnect/Lean/blob/master/Algorithm.CSharp/OptionOpenInterestRegressionAlgorithm.cshttps://github.com/QuantConnect/Lean/blob/master/Algorithm.CSharp/OptionRenameRegressionAlgorithm.cshttps://github.com/QuantConnect/Lean/blob/master/Algorithm.CSharp/OptionSplitRegressionAlgorithm.cs
0

Ok, seems there is no way to get weekly options from OptionChainProvider, so I changed algorithm to use SetFilter, but it became extremely slow, and now I'm getting error saying that I can't even complete backtesting

System.Exception: Algorithm took longer than 10 minutes on a single time loop.
at QuantConnect.Isolator.ExecuteWithTimeLimit (System.TimeSpan timeSpan, System.Func`1[TResult] withinCustomLimits, System.Action codeBlock, System.Int64 memoryCap) [0x002a0] in <5448ca931fb447388c7bffc05443eea6>:0
at QuantConnect.Lean.Engine.Engine.Run (QuantConnect.Packets.AlgorithmNodePacket job, QuantConnect.Lean.Engine.AlgorithmManager manager, System.String assemblyPath) [0x0079e] in Lean.Engine.AlgorithmManager manager, System.String assemblyPath) [0x0079e] in <3ff2ad2a80484d7084ba3bb2da668bae>:0

The code.

using System.Drawing;
using System.Threading;
using System.Threading.Tasks;

namespace QuantConnect
{
public partial class QCUMartingalePositionSizing : QCAlgorithm
{
const string iSymbol = "SPY";
const string iChart = "Deals";

DateTime iTime;

Symbol iAssetSource = QuantConnect.Symbol.Create(iSymbol, SecurityType.Equity, Market.USA);
Symbol iOptionSource = QuantConnect.Symbol.Create(iSymbol, SecurityType.Option, Market.USA);

public override void Initialize()
{
SetCash(10000);
SetStartDate(2017, 1, 1);
SetEndDate(DateTime.Now.Date);
SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage);

var asset = AddEquity(iSymbol, Resolution.Minute);
var option = AddOption(iSymbol);

option.SetFilter(u => u
.IncludeWeeklys()
.Strikes(-5, +5)
.Expiration(TimeSpan.Zero, TimeSpan.FromDays(10)));

var chart = new Chart(iChart);
var seriesStock = new Series("Stock", SeriesType.Line, 0);

chart.AddSeries(seriesStock);

AddChart(chart);
}

public override void OnData(Slice slice)
{
if (IsMarketOpen(iSymbol) == false)
{
return;
}

if (IsNewBar(TimeSpan.FromHours(1)) == false)
{
return;
}

if (Portfolio[iSymbol].Invested)
{
MarketOrder(iSymbol, -100);
}

if (Portfolio.Invested == false)
{
OptionChain chain;

if (slice.OptionChains.TryGetValue(iOptionSource, out chain))
{
var price = Securities[iSymbol].Price;

var otmCalls =
from c in chain
where c.Right == OptionRight.Call
where c.Strike - price < 5 && c.Strike - price > 1
where (c.Expiry - Time).TotalDays < 35 && (c.Expiry - Time).TotalDays > 0
select c;

var otmPuts =
from c in chain
where c.Right == OptionRight.Put
where price - c.Strike < 5 && price - c.Strike > 1
where (c.Expiry - Time).TotalDays < 35 && (c.Expiry - Time).TotalDays > 0
select c;

var contractCall = otmCalls
.OrderBy(o => o.Expiry)
.ThenByDescending(o => o.Strike - price)
.FirstOrDefault();

var contractPut = otmPuts
.OrderBy(o => o.Expiry)
.ThenByDescending(o => price - o.Strike)
.FirstOrDefault();

if (contractCall != null)
{
MarketOrder(contractCall.Symbol, -1);
}

if (contractPut != null)
{
MarketOrder(contractPut.Symbol, -1);
}
}
}
}

protected decimal GetBalance(bool equity = false)
{
var balance = 0m;

if (equity)
{
balance += Portfolio.TotalUnrealizedProfit;
}

return
balance +
Portfolio.TotalProfit -
Portfolio.TotalFees;
}

public bool IsNewBar(TimeSpan interval, int points = 1)
{
var date = Securities[iSymbol].LocalTime;

if ((date - iTime).TotalSeconds > interval.TotalSeconds * points)
{
iTime = new DateTime(date.Ticks - date.Ticks % interval.Ticks, date.Kind);
return true;
}

return false;
}
}
}
0

with that you could go to the support if you want........you made something very very slow!

try to put some time informations in the code to check where that stuff dies.........

0

It's slow not because of my code...

First of all, the code above hangs out when I try to backtest on a period of about one year with weekly options. If I remove "includeWeeklys", or set date range to about 50 days, test starts. Initial problem with SetFilter is that it's not using rolling window and tries to accumulate all info in a single variable which leads to memory overflow, this is why you need to either set very restrictive conditions to leave only 10-20 options in a chain, or set very short period of testing.

Nevertheless, being slow is not the only issue of SetFilter, it just doesn't return requested data. I tried to simplify code as much as possible, removed all conditions and requested option chain for SPY for last 15 days. Just in case, SPY gives options every 3 days in a week, so for 15 days I should get 6 option chains. SetFilter returned nothing.

Backtest attached.

0


Advantage of OptionChainProvider over SetFilter is that you always request only recent data, so it's always fresh and doesn't cause memory overflow. Unfortunately, it doesn't return weekly options. 

0

Update Backtest





0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Loading...

This discussion is closed