function Out = Backtest_Straddles(symbol,rw,sc)
% This function gives the historical probability of the stock price
% moving more than what it costs to purchase a straddle
% ( A call and put at the same strike and expiration). This is purely
% based on Historical Data. Obviously, The costs could be higher due to
% other events such as earnings releases etc.
% Users should also note the level of VIX during the time period of
% backtest.(Beyond the usage of this simple program)
% The function downloads the data from YAHOO and calculates the Probability
% Inputs: symbol, Rolling window parameter, RW and Straddle Cost, SC
% Outputs: A structure with the following fields
% 1. Profit Probability for the given Straddle Costs
% 2. Probability Matrix for a range of Percentiles
% 3. Histogram Matrix which gives the number of elements in each bin
% 4. Rolling Window Data
% 5. Data
% Optionally user can turn on plots(see section titled plots)
% Usage: Out = Backtest_Straddles('CNH',30,4)
%% Calculation Engine
% Let us get some data starting from 01/01/2006. Please change this.
Data = hist_stock_data('01012006',datestr(today,'mmddyyyy'),symbol);
% Take ABSOLUTE values of rolling window difference between the
% first day and rw+1 day
rwData = abs(Data.AdjClose(1:end-rw) - Data.AdjClose(rw+1:end));
%% Calculate Historical Probability given the Straddle Costs
Out.Profit_Probability = length(find(rwData > sc))./length(rwData);
disp(['Historically, There is a ' num2str(Out.Profit_Probability * 100) ' % ' ...
'Probability that the Stock will move more than ' num2str(sc) ...
'$ Over the next ' num2str(rw) ' days']);
%% Calculate Historical Probability for a range of Percentiles
p = 10:10:100;
prctiles = prctile(rwData,p);
Out.ProbMatrix = [100-p' prctiles'];
%% Use histc command to calculate the number of elements in each bin
edges = min(rwData):max(rwData);
[n_elements,bins] = histc(rwData,edges);
Out.HistMatrix = [n_elements edges'];
Out.rwData = rwData;
Out.Data = Data.AdjClose;
%% Miscellaneous PLOTs
% Set the following variable to 1 to see some plots
doPlot = 1;
if(doPlot)
subplot(2,1,1)
plot(Out.ProbMatrix(:,1),Out.ProbMatrix(:,2),'-*')
xlabel('Percentage')
ylabel('Dollar Movement Over the given period')
title('Percentage of time, the stock has moved more than a given amount (LONG Straddle)')
axis tight
grid on
subplot(2,1,2)
cumHist = cumsum(Out.HistMatrix(:,1))./length(Out.Data);
cumHist(end)=1;
plot(cumHist * 100,Out.HistMatrix(:,2),'-*')
xlabel('Percentage')
ylabel('Dollar Movement Over the given period')
title('Alternative view: Percentage of time that the stock moved less than a given amount (SHORT Straddle)')
axis tight
grid on
end