## Pre-existing component

Hello,
I am just curious as to whether QC has pre-programmed derivative calculators and if there is a way to plot these derivative functions over or under the backtest result.

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.

What do you mean exactly by 'pre-programmed derivative calculators' ? Derivative such as data that derives from something else? Or derivative in the calculus sense, the instantaneous rate of change of a variable?
1

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.

Sure this can be done. For example, let's say we want to plot the price of a put option together with the price of the stock option for a certain day.

We can derive the value of the put option using Black-Scholes with the following code:

 /* * Example of how to use Put pricing with Black-Scholes in an algorithm * by: Jean-Paul van Brakel */ public class BasicTemplateAlgorithm : QCAlgorithm { // ticker to be used private readonly string _ticker = "AAPL"; // number of periods to be used in volatility calculation private static int _vol_periods = 14; private readonly RollingWindow PriceHistory = new RollingWindow(_vol_periods); // define option maturity date private readonly DateTime _maturityDate = new DateTime(2015, 1, 16); // third friday of the month //Initialize the data and resolution you require for your strategy: public override void Initialize() { //Start and End Date range for the backtest: SetStartDate(2015, 1, 1); SetWarmup(TimeSpan.FromDays(_vol_periods)); SetEndDate(2015, 1, 2); //Cash allocation SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, _ticker, Resolution.Minute); //Initialise plot Chart plotter = new Chart("DerivativePlot", ChartType.Stacked); plotter.AddSeries(new Series("Price", SeriesType.Line)); plotter.AddSeries(new Series("Put price", SeriesType.Line)); AddChart(plotter); } //Data Event Handler: New data arrives here. public void OnData(TradeBars data) { PriceHistory.Add(data[_ticker]); if (!PriceHistory.IsReady) return; // specify option settings here: double price = (double)PriceHistory[0].Close; double strike = 110; // strike price of option double rate = 0.05; // risk-free rate of return to use in calculation // recalculate annualised time to maturity double maturity = (BlackScholes.CountWeekDays(data.Time,_maturityDate)/250); double[] _p_history = new double[PriceHistory.Count]; for (int i = 0; i < PriceHistory.Count; i++) // copy close (you can change this to your liking) _p_history[i] = (double)PriceHistory[i].Close; // approximate volatility with historical volatility of the underlying double volatility = BlackScholes.HistoricalVolatility(_p_history); double yield = 0.01; // approximation to the annualised dividend yields(%) for AAPL // calculate Black-Scholes option value for a European PUT (also approximation to American PUT) double _optionPrice = BlackScholes.blsPut(price, strike, rate, maturity, volatility, yield); if (data.Time >= StartDate) { Plot("DerivativePlot", "Price", price); Plot("DerivativePlot", "Put price", _optionPrice); } // put your actual trading logic here: if (!Portfolio.HoldStock) { Order(_ticker, -100); } } }

For this to work, you also need to add the class BlackScholes which I've put together. Simply clone the project below and you're ready to go.

To see the resulting plot of both the stock price and the put option price, clone the algorithm and backtest it. Then on the right side you can click on the plot DerivativePlot. This will show the plot of both the stock and derivative price.

I hope this is close to what you are looking for.

Good luck!
2

Meant derivative in the mathematical sense, Sorry for not making that clear haha.

I got my hands on a recent edition calculus textbook and although I am aiming to learn stochastic calculus by next year before attempting anything serious, I'd like to try applying derivatives (math sense) to my trading system. Such as, using moving averages and those like such to either smooth out candlestick data for derivative calculation and plot the derivative as a function in order to see when horizontal tangents lines occur and base decisions of such observations.

If pre-existing mathematical derivative value indicators or shortcuts exist, I would appreciate being brought to speed.

---------------------------All math below this

I am aware of the fact that certain natural phenomenon such as sound waves and particle movement have patterns of movement/change that can be modeled by altering pre-existing
0

*functions that show repetition of patterns like those found in the natural world such as tan(x). If anyone could shed some light on this topic, I'd be grateful.
0

Derivatives are continuous by definition. You can, however, always calculate discrete "change in differences" if that's what you are after.

You can simply calculate such a change as:

$$\frac{df}{dt}=\frac{f_2-f_1}{t_2-t_1}$$

For some function (e.g. moving average) $$f$$ and times $$t_1$$ and $$t_2$$. You can then achieve a better approximation by making $$\Delta t = t2-t1$$ smaller.
1

An important thing to note is that security price evolution is a stochastic process, and as such, regular discrete approximations such as finite differences rarely yield continuous functions which make them mathematically hard to use. An initial first filtering step is almost always required for this kind of approach in order to smoother your function $$f$$ before taking the finite differences.

An alternative is to crack open that stochastics calculus textboox :)

Another option you could use is a TheilSen linear regression, it uses the median of slopes in a set of points to determine the slope of the regression line. Here's a quick example for you. Hope this helps!

EDIT: You may get smoother results by first performing an initial filtering step, maybe an averaging scheme of some sort.
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.

Would you consider this to be a decent resource?
http://efinance.org.cn/cn/FEshuo/stochastic.pdf

also, I am aware that stock market behavior requires much higher level math like partial diff equations to model properly. Unfortunately, I have limited knowledge resources because of my late start.

Thank you for your code and introducing me to the TheilSen regression. It's very interesting stuff and I'm almost excited to tackle the task of tailoring it into my strategy.

On a final note, by filtering step / averaging scheme, do you mean something along the lines of running a moving average on (hloc/3) to "smooth out" the curve?
0

@NicholasCaffrey Just wondering, how would you apply stochastic calculus to normal stocks? Stochastic calculus is a technique to derive the prices of derivatives and other instruments, because they allow for a (reasonable) model of the markets. I don't see how that can be of any help to predict the future movements of stocks any more than a basic linear regression (which might correspond to the slope in the $$S_t = S_0 e^{\mu t + \sigma W_t}$$ differential).
1

I haven't read that paper, but glossing over the index it seems to have lots of good things in there.

By filtering I mean a preprocessing step before using finite differences. This could be a moving average of various types, or something more complex. You could certainly use an averaging scheme on each bar before feeding it into the moving average as well. I've also seen implementations that augment the weight of each data point based on it's standard deviation from a short term mean. It can become increasingly complex.

I recommend plotting your various techniques for filtering/averaging and see if they make sense for your application, since that's the 'function' you'll be taking the derivative of.

If you're making the jump into a more stochastic analysis, you'd want to use Ito's lemma.

One final thing, I think you meant OHLC/4 as a bar averaging scheme, dividing by 3 would give an answer that is 1/3 larger than the current price.
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.

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.