Serving the Quantitative Finance Community

 
User avatar
Amin
Topic Author
Posts: 2572
Joined: July 14th, 2002, 3:00 am

Application of Filtering Principles Towards Trading Stock Prices

January 21st, 2022, 10:17 am

.
Friends, I have previously mentioned on the forum that I have devised my own trading algorithms based on filtering theory applied in a different and innovative way. I am sharing performance of my algorithm on Tesla stock for 40 days from 5th of April 2021 to 30th of May 2021. I have posted graphs that show profits from my trading strategy and the Tesla stock price for 40 days. Title of each of the 40 graphs is the date on that trading day. On the graphs trades are marked and a the blue "+" means entering a buy side of the trade while a red "o" means entering a sell side of the trade. Black lines are profits and green line marked with trades is Tesla stock mid-price.

In these algorithms, I have traded mid-price i.e I buy and sell both on mid-price.The mid-price trading algorithm makes 27000 trades during 40 days and makes a cumulative profit of $411. Tesla stock price is roughly around $700 during this period. One trade lasts on average for slightly more than 30 seconds in my trading strategy. 

I am attaching  40 graphs in jpg files for forty different days of trading mid-price on Tesla stock in next two posts. I have not included any spread profits that we would accumulate on the way. In final analysis mid-price trading profits would play a smaller role than bid-ask spread that we would collect on our 27000 trades. I have not included that in this analysis.

To make a prediction, I have used filtering techniques but in a way nobody has used them before. I am running the filter on 15 second log returns but I am not using classical filtering theory in predicting the returns instead I filter the parameters of the process and then use those parameters to generate a signal. I do not believe anybody has done this before as far as I know. Without a robust prediction technique, it would be totally impossible to profitably make trades on a scale of 15 seconds.

Market is noisy all the time. My algorithm quickly predicts the market for next 15 seconds. If I have already bought a share and my algorithm predicts that market will be up after 15 seconds, I will hold it and make no trade. However if my algorithm predicts that market will go down after 15 seconds, I will immediately sell the share in market at discounted bid-ask spread to sell the inventory I have. Mostly I would make the size of sell order 2X the size of shares traded so that I can simultaneously short the same amount of stock to have a negative position since the algorithm has indicated that price would go down after 15 seconds. You need a great prediction algorithm to predict the noise in the market every 15 seconds. Offsetting the buy inventory and entering a short are usually together in my algorithm but they can be decoupled as well.

After profits from bid-ask spread on limit orders are included, my trading strategy virtually has very little drawdown. After profits from bid-ask spread are included, I do not think there was a single day that strategy made a loss. Though some individual trades can make a loss during the day but over the entire day there is usually no drawdown. This is like high frequency trading but without the need for great infrastructure that is required for HFT. We just automate our program to keep making quick trades and keep earning small spreads. If we can consistently earn this spread, it becomes quite substantial and overall profit is quite high. I believe Renaissance follows similar trading strategies in spirit though I am sure their execution would be very refined as they are very experienced in the market.

Latency required should be just reasonable and should not be extremely high. We are not trading on nano-seconds scale at all. We need to make a trade after an average of 30 seconds. Trade time can vary from 15 seconds to several minutes as guided by the prediction algorithm. We want to be filled quickly but some noise is acceptable and we are not competing to be filled at every order. Some better than normal latency is acceptable.

My algorithm is based on filtering principles, it is very important that all the input variances and variances of parameters are close to reality and usually these variances are found by optimizations on the available data. I have optimized variance values for Tesla stock by playing around with data but I still have to write a proper optimization algorithm that will optimize filter parameter variances for various stocks. If we input bad variances in above analysis, the filter can make large losses but a properly optimized filter usually results in reasonable profits. I will be working in next few days to write the filter variances optimization program. Even for the Tesla stock I have shown, performance will be quite better when variances and other parameters are optimized.

Please bookmark this thread I will continue to post more information regularly.
Last edited by Amin on January 21st, 2022, 10:27 am, edited 1 time in total.
You think life is a secret, Life is only love of flying, It has seen many ups and downs, But it likes travel more than the destination. Allama Iqbal
 
User avatar
Amin
Topic Author
Posts: 2572
Joined: July 14th, 2002, 3:00 am

Re: Application of Filtering Principles Towards Trading Stock Prices

January 21st, 2022, 10:21 am

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image
You think life is a secret, Life is only love of flying, It has seen many ups and downs, But it likes travel more than the destination. Allama Iqbal
 
User avatar
Amin
Topic Author
Posts: 2572
Joined: July 14th, 2002, 3:00 am

Re: Application of Filtering Principles Towards Trading Stock Prices

January 21st, 2022, 10:26 am

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image
You think life is a secret, Life is only love of flying, It has seen many ups and downs, But it likes travel more than the destination. Allama Iqbal
 
User avatar
Amin
Topic Author
Posts: 2572
Joined: July 14th, 2002, 3:00 am

Re: Application of Filtering Principles Towards Trading Stock Prices

January 21st, 2022, 10:43 am

A few notes about the algorithm.

1. I have yet not properly optimized variances and after proper optimization of variances, I would not be surprised if another 100-150 dollars are added to 411 dollars that we currently have.

2. Though I have not done proper optimization, all graphs do not show such profits but we can easily make 10%-20% in two moths of data I had as opposed to more than fifty percent we made for Tesla stock in our experiments. Though again numbers would be better after proper optimization of filter variances according to time series of particular stock.

3.  In real trading more profits would come out of bid-ask spread that we would earn as compared to what we have from trading mid. The Tesla stock had a bid-ask spread of  nine cents on average during this period. If we could make only four cent per trade on average, our total profits would be equal to
=mid-price trading profit on 27000 trades + .04 dollars of spread earned on each of 27000 trades.
=$ 411 + 27000 * .04 $ = 411 + 1080 = $ 1491.
So we could make $1491  on trading a stock for two months that has an average price of $ 700 during this period.
Without a robust prediction technique, it would be totally impossible to profitably make trades on a scale of 15 seconds.

4. My algorithm is based on filtering principles, it is very important that all the input variances and variances of parameters are close to reality and usually these variances are found by optimizations on the available data. I have optimized variance values for Tesla stock by playing around with data but I still have to write a proper optimization algorithm that will optimize filter parameter variances for various stocks. If we input bad variances in above analysis, the filter can make large losses but a properly optimized filter usually results in reasonable profits. I will be working in next few days to write the filter variances optimization program. Even for the Tesla stock I have shown, performance will be quite better when variances and other parameters are optimized.
In reality we would optimize the parameters of the filter every night before trading using all available data for past few weeks and then use the optimized parameters.

 
You think life is a secret, Life is only love of flying, It has seen many ups and downs, But it likes travel more than the destination. Allama Iqbal
 
User avatar
Amin
Topic Author
Posts: 2572
Joined: July 14th, 2002, 3:00 am

Re: Application of Filtering Principles Towards Trading Stock Prices

January 21st, 2022, 11:09 am

For those friends who would ask how I did this filtering and who want to do this on their own, here is some guidance:
I am running the filter on 15 second log returns but I am not using classical filtering theory in predicting the returns instead I filter the parameters of the process and then use those parameters to generate a signal. Filter shifts the parameters quickly according to regime as it is the parameters of time series that we are filtering. I had shared ideas about filtering parameters instead of the variables in a different thread here but you will have to do some intelligent thinking to put all of this together.
https://forum.wilmott.com/viewtopic.php?f=4&t=99702&start=1140

Due to time I had to devote to my research on SDEs, I was not properly able to give time to this project so there are very good possibilities for improvement as the research progresses. Algorithm's failure to filter parameters properly according to time series results in losses many times but mostly losses are minor as compared to profits. 
You think life is a secret, Life is only love of flying, It has seen many ups and downs, But it likes travel more than the destination. Allama Iqbal
 
User avatar
Amin
Topic Author
Posts: 2572
Joined: July 14th, 2002, 3:00 am

Re: Application of Filtering Principles Towards Trading Stock Prices

January 21st, 2022, 11:19 am

If you would like my algorithm for trading stocks and want to use it in your firm or want me to develop similar algorithms for you, please feel free to write me an email at     anan2999(at)yahoo(dot)com
You think life is a secret, Life is only love of flying, It has seen many ups and downs, But it likes travel more than the destination. Allama Iqbal
 
User avatar
Amin
Topic Author
Posts: 2572
Joined: July 14th, 2002, 3:00 am

Re: Application of Filtering Principles Towards Trading Stock Prices

January 21st, 2022, 3:07 pm

I had given address of this Wilmott thread on Nuclearphyance and somebody there asked several questions. Since Wilmott readers might have similar questions in mind, I copying my post with questions and answers here for friends.

Q. Why is the testing period only April-May 2021? Is this a backtest, and if so why not use more data?
A. I can definitely use more data but this project started in summers and at that time I bought a large amount of tick-data but two last months of data was downloaded separately and prepared the smaller set according to format that it could be used in initial experiments. Other files were too large and I did not bring them into proper format and it can take several days. Also I am still to write an automated optimization program and I would come back to testing larger data sets after that.

Q. Did you incorporate transaction costs into your model? Because with 27k trades that's going to be a super important factor.
A. For that kind of trades IB charges .35 dollars per trade contract. Assuming I am trading 100 shares, that is .0035 dollars per share per side of trade
27000*.0035 *2= $188 per single stock which is relatively insignificant. All my analysis is for a single share of Tesla stock.

Q. $411 profit on what capital
A. On a single Tesla share traded that is around $700 on average.

Q. "After profits from bid-ask spread on limit orders are included, my trading strategy virtually has very little drawdown"
- Could you explain this more? How are you ensuring you're profiting from the spread?
A. Since I got my mid very right on average, and the average Tesla spread in this period is 8 cents but I suppose that I could materialize only 4 cents when I enter the trades through limit orders. I think experienced market players can easily earn greater spread per trade than 4 cents.

Q. Also what filter principles are you talking about exactly? I'm not familiar with that term in this context.
A. May be this is a bad term but in the relevant last post on original forum I have given some pointers to threads where I have previously discussed these ideas. Please check here: https://forum.wilmott.com/viewtopic.php?f=4&t=99702&start=1140
You think life is a secret, Life is only love of flying, It has seen many ups and downs, But it likes travel more than the destination. Allama Iqbal
 
User avatar
Amin
Topic Author
Posts: 2572
Joined: July 14th, 2002, 3:00 am

Re: Application of Filtering Principles Towards Trading Stock Prices

January 21st, 2022, 3:52 pm

Q. "One trade lasts on average for slightly more than 30 seconds in my trading strategy."
How can you assume in live trading, using real bid/ask prices instead of the mid, that you would get a fill every 30 seconds?

A. For that you have to have a complete strategy. And that is why I suggested in the calculations that I would be getting filled with a spread of 4 cents on average as opposed to prevailing spread of 8 cents. Even then there would be a few times when I would remain unfilled and I would need a strategy to deal with that.
BTW Tesla share was traded usually way more than 10,000 shares per 15 second period during the data analysis time window of two months.
You think life is a secret, Life is only love of flying, It has seen many ups and downs, But it likes travel more than the destination. Allama Iqbal
 
User avatar
Amin
Topic Author
Posts: 2572
Joined: July 14th, 2002, 3:00 am

Re: Application of Filtering Principles Towards Trading Stock Prices

January 25th, 2022, 11:13 am

Friends, I have decided to make my programs for this Tesla Case Study application of filtering theory public. I will be posting my programs here in two to three days.
You think life is a secret, Life is only love of flying, It has seen many ups and downs, But it likes travel more than the destination. Allama Iqbal
 
User avatar
tags
Posts: 3162
Joined: February 21st, 2010, 12:58 pm

Re: Application of Filtering Principles Towards Trading Stock Prices

January 25th, 2022, 10:59 pm

hi Amin
27K trades in 40 days looks like a huge number of trades.
is this a solution for retail investors you are pitching here?
it is not clear to whether brokerage fees are included in your trading performance, is it?
what about slippage, and such trading "inconveniences"?
Thanks.
 
User avatar
bearish
Posts: 5186
Joined: February 3rd, 2011, 2:19 pm

Re: Application of Filtering Principles Towards Trading Stock Prices

January 26th, 2022, 1:55 am

He thinks he can receive the bid/ask spread rather than pay it. That makes the frantic trading very lucrative!
 
User avatar
Amin
Topic Author
Posts: 2572
Joined: July 14th, 2002, 3:00 am

Re: Application of Filtering Principles Towards Trading Stock Prices

January 26th, 2022, 8:54 am

hi Amin
27K trades in 40 days looks like a huge number of trades.
is this a solution for retail investors you are pitching here?
it is not clear to whether brokerage fees are included in your trading performance, is it?
what about slippage, and such trading "inconveniences"?
Thanks.
.
Yes Tagoma, it is a large number of trades but there are people who are doing similar or larger number of trades in many stocks together. If you look at IB's volume tiered commission pricing here : https://www.interactivebrokers.com/en/index.php?f=1590&p=stocks2
It goes like if you trade 
smaller than 300,000 shares per month      commission is    .0035 dollars per share.
300,000 to 3 million shares per month         commission is     .002  dollars per share
3 million to  20 million shares per month     commission is      .0015 dollars per share
20 millions to 1 billion shares per month     commission is       .001 dollars per share
More than one billion  share per month      commission is        .0005 dollars per share

The above pricing is for a single IB trading account which of course can have sub-accounts.

So there are people who are making extremely huge number of trades per month using similar strategies and IB has very discounted commission for them.

I had explained trading costs in questions and answers in a previous post and I will copy the relevant Q&A here.

Q. Did you incorporate transaction costs into your model? Because with 27k trades that's going to be a super important factor.

A. For that kind of trades IB charges .35 dollars per trade contract. Assuming I am trading 100 shares, that is .0035 dollars per share per side of trade
27000*.0035 *2= $188 per single stock which is relatively insignificant. All my analysis is for a single share of Tesla stock.

Of course my analysis is not for retail investors as Wilmott is not a forum for retail investors, it is a forum for professional Quants who would like to know more about such trading strategies.
                                    
Last edited by Amin on January 26th, 2022, 9:03 am, edited 2 times in total.
You think life is a secret, Life is only love of flying, It has seen many ups and downs, But it likes travel more than the destination. Allama Iqbal
 
User avatar
Amin
Topic Author
Posts: 2572
Joined: July 14th, 2002, 3:00 am

Re: Application of Filtering Principles Towards Trading Stock Prices

January 26th, 2022, 8:57 am

He thinks he can receive the bid/ask spread rather than pay it. That makes the frantic trading very lucrative!
.
When you take liquidity, you pay spreads. When you provide liquidity, you earn spreads. If you enter trades through market orders, you have to pay spread and if you enter trades though limit orders, you will earn spread. I think that is how market works.
You think life is a secret, Life is only love of flying, It has seen many ups and downs, But it likes travel more than the destination. Allama Iqbal
 
User avatar
Amin
Topic Author
Posts: 2572
Joined: July 14th, 2002, 3:00 am

Re: Application of Filtering Principles Towards Trading Stock Prices

January 26th, 2022, 6:32 pm

If you look at IB's volume tiered commission pricing herehttps://www.interactivebrokers.com/en/index.php?f=1590&p=stocks2
It goes like if you trade 
smaller than 300,000 shares per month      commission is    .0035 dollars per share.
300,000 to 3 million shares per month         commission is     .002  dollars per share
3 million to  20 million shares per month     commission is      .0015 dollars per share
20 millions to 1 billion shares per month     commission is       .001 dollars per share
More than one billion  share per month      commission is        .0005 dollars per share
.
Sorry, the highest Tier is 100 million and not a billion as I erroneously wrote. Some exchanges also have rebates on adding liquidity.
You think life is a secret, Life is only love of flying, It has seen many ups and downs, But it likes travel more than the destination. Allama Iqbal
 
User avatar
Amin
Topic Author
Posts: 2572
Joined: July 14th, 2002, 3:00 am

Re: Application of Filtering Principles Towards Trading Stock Prices

January 28th, 2022, 4:23 pm

Friends, I am attaching the matlab files for the filtering algorithm I used to track the Tesla mid-price. I will post some notes in the next post. Please note that this program is different from the one used to create above graphs.
.
.
function [] = PlayWithDataNewWilmott()
%copyright: Ahsan Amin, CEO of Infiniti Derivatives Technologies
%IF you would like me to develop far better and advanced versions of this program for you, please
% email me at anan2999(at)yahoo(dot)com
%please enjoy the filtering program below
%You will have to assign appropriate file paths for data and date files.

pathstring="C:\Users\Ahsan\Documents\MATLAB\ReadDates0.txt";
T = readtable(pathstring);
StockDateSeries(1:41)=table2array(T(1:41,1));
StockSymbol0(1)="TSLA"

for nn=2:41


    StockDate0=StockDateSeries(nn);
    if(nn>1)
    StockDate1=StockDateSeries(nn-1);
    Stock1=StocksClassW(StockSymbol0,StockDate1);
    %Returns Variance from every previous day is fed to the filtering function using Stock1 object.
    end
    Stock0=StocksClassW(StockSymbol0,StockDate0);
    

    StockDate0
    %str=input('Look at date');
    if(nn>1)
        [Profit(nn),NoOfTrades(nn)]=SDEParamsFilterAndDoubleStrategyNew02A4paramsOptimMid02LargeW(Stock0.LogReturns,Stock0.StockPrice0Series,Stock1.LRVar,StockDate0);
        AvgSpread(nn)=0.0;
        for mm=2:1560
            AvgSpread(nn)=AvgSpread(nn)+(Stock0.StockAskSeries(mm,1)-Stock0.StockBidSeries(mm,1))/1560;
        end
        AvgSpread(nn)
    end
    TotalProfitYet=sum(Profit(2:nn))
end
TotalProfit=sum(Profit(2:41))

TotalTrades=sum(NoOfTrades(2:41))

TradingProfit=TotalProfit
TotalCommissions=TotalTrades*.0035*2
TotalSpreadEarned=sum(NoOfTrades(:) .* AvgSpread(:))*.5

AvgSpread
end

.
.
function [Profit,NoOfTrades] = SDEParamsFilterAndDoubleStrategyNew02A4paramsOptimMid02LargeW(LogRSeries,PriceSeries,VarLogR,Date0)

Price0=PriceSeries;

a1(1:4)=.000005; %a1-a4 are autoregressive parameters for lag 1-4 periods.
a2(1:4)=.000005;
a3(1:4)=.000005;
a4(1:4)=.000005;

P_a1(1:4)=0.0;  %P_a1-Pa4 is filter variance covariance matrix. 
                %It is considered diagonal in this prototype.That is why all calculations are linear.
P_a2(1:4)=0.0;
P_a3(1:4)=0.0;
P_a4(1:4)=0.0;

    w_Zt=1.0*sqrt(VarLogR);
    w_Zt0=1.0*sqrt(VarLogR);
    w_ZtP=w_Zt;
Zt(1:1561)=0.0;
%Z1(1:1561)=0.0;
LogPrice(1:1561)=0.0;
%for tt0=2:2+Lag-1
for tt0=2:5    
   
    LogPrice(tt0)=log(PriceSeries(tt0,1));
end



Sell=0;
Buy=0;
Profit=0;
Trade=0;
Profit0(1:1561)=0.0;
NoOfTrades=0;
bb=1;
ss=1;
SellTimes(1)=0;
BuyTimes(1)=0;
PositionVolume=0;
for tt=5:1560    
    %LogPrice(tt)=LogPrice(tt-1)+LogRSeries(tt,1);
    LogPrice(tt)=log(PriceSeries(tt,1));
  
    
if(tt>50)
     w_a1=.0075;%.005 earlier
    w_a2=.0035;%.0035
    w_a3=.00125;
    w_a4=.0005;
    
end
if(tt<=50)
    w_a1=.006*2;%.005 earlier
    w_a2=.004*2;%.0035
    w_a3=.002*2;
    w_a4=.001*2;
end
    
    a1(tt)=a1(tt-1);
    a2(tt)=a2(tt-1);
    a3(tt)=a3(tt-1);
    a4(tt)=a4(tt-1);
    P_a1(tt)=P_a1(tt-1)+w_a1^2;
    P_a2(tt)=P_a2(tt-1)+w_a2^2;
    P_a3(tt)=P_a3(tt-1)+w_a3^2;
    P_a4(tt)=P_a4(tt-1)+w_a4^2;
    
    Kk0=( LogRSeries(tt-1,1).*P_a1(tt).*LogRSeries(tt-1,1) + ...
        LogRSeries(tt-2,1).*P_a2(tt).*LogRSeries(tt-2,1) + ...
        LogRSeries(tt-3,1).*P_a3(tt).*LogRSeries(tt-3,1) + ...
        LogRSeries(tt-4,1).*P_a4(tt).*LogRSeries(tt-4,1) +w_ZtP.^2).^(-1);

    
    Xnew=( LogRSeries(tt-1,1).*a1(tt) + LogRSeries(tt-2,1).*a2(tt)+ LogRSeries(tt-3,1).*a3(tt)+ LogRSeries(tt-4,1).*a4(tt));% + ...
    
    %Z1(tt)=LogRSeries(tt,1)-( LogRSeries(tt-1,1).*a1(tt) + LogRSeries(tt-2,1).*a2(tt)+ LogRSeries(tt-3,1).*a3(tt)+ LogRSeries(tt-4,1).*a4(tt));% + ...
    a1Prev(tt)=a1(tt);
    a2Prev(tt)=a2(tt);
    a3Prev(tt)=a3(tt);
    a4Prev(tt)=a4(tt);
    a1(tt)=a1(tt)+ LogRSeries(tt-1,1).*P_a1(tt).*Kk0.*(LogRSeries(tt,1)-Xnew);
    adj=LogRSeries(tt-1,1).*(a1(tt)-a1Prev(tt));
    %adj=0;
    a2(tt)=a2(tt)+ LogRSeries(tt-2,1).*P_a2(tt).*Kk0.*(LogRSeries(tt,1)-Xnew-adj);
    adj=adj+LogRSeries(tt-2,1).*(a2(tt)-a2Prev(tt));
    %adj=0;
    a3(tt)=a3(tt)+ LogRSeries(tt-3,1).*P_a3(tt).*Kk0.*(LogRSeries(tt,1)-Xnew-adj);
    adj=adj+LogRSeries(tt-3,1).*(a3(tt)-a3Prev(tt));
    %adj=0;
    a4(tt)=a4(tt)+ LogRSeries(tt-4,1).*P_a4(tt).*Kk0.*(LogRSeries(tt,1)-Xnew-adj);
    
    Zt(tt)=LogRSeries(tt,1)-( LogRSeries(tt-1,1).*a1(tt) + LogRSeries(tt-2,1).*a2(tt)+ LogRSeries(tt-3,1).*a3(tt)+ LogRSeries(tt-4,1).*a4(tt));% + ...
    
    if(tt>=5)
        w_ZtP2=w_ZtP^2;
    end
    
   sigma0=.98;  %TSLA
   sigma1=+.15;
   sigma2=+.04;
   sigmab0=.5*1.5;  %TSLA
   sigmab1=+.15/2*1.5;
   sigmab2=+.04/2*1.5;
   alpha0=.02;
   
   sigma0=.96;  %TSLA
   sigma1=+.15;
   sigma2=+.04;
   sigmab0=.5*1.5;  %TSLA
   sigmab1=+.15/2*1.5;
   sigmab2=+.04/2*1.5;
   alpha0=.04;
  
    %w_ZtP2=alpha0*w_ZtP2+sigma0*abs(Zt(tt)).^2+sigma1*abs(Zt(tt-1)).^2+sigma2*abs(Zt(tt-2)).^2;%+ ...
    w_ZtP2=alpha0*w_ZtP2+sigmab0*LogRSeries(tt,1).^2+sigmab1*LogRSeries(tt-1,1).^2+sigmab2*LogRSeries(tt-2,1).^2+ ...
                       +sigma0*abs(Zt(tt)).^2+sigma1*abs(Zt(tt-1)).^2+sigma2*abs(Zt(tt-2)).^2;
        %sigma3*abs(Zt(tt-3)).^2;

    
    w_ZtP=sqrt(w_ZtP2) ;
    %w_ZtP=w_Zt0;
    P_a1(tt)=(1-LogRSeries(tt-1,1).*P_a1(tt).*Kk0.*LogRSeries(tt-1,1)).*P_a1(tt);
    P_a2(tt)=(1-LogRSeries(tt-2,1).*P_a2(tt).*Kk0.*LogRSeries(tt-2,1)).*P_a2(tt);
    P_a3(tt)=(1-LogRSeries(tt-3,1).*P_a3(tt).*Kk0.*LogRSeries(tt-3,1)).*P_a3(tt);
    P_a4(tt)=(1-LogRSeries(tt-4,1).*P_a4(tt).*Kk0.*LogRSeries(tt-4,1)).*P_a4(tt);
    %P_b2(tt)=(1-Zt(tt-2).*P_b2(tt).*Kk0.*Zt(tt-2)).*P_b2(tt);
    
Fp(tt)=a1(tt)*LogRSeries(tt,1)+a2(tt)*LogRSeries(tt-1,1)+a3(tt)*LogRSeries(tt-2,1)+a4(tt)*LogRSeries(tt-3,1);

Mul=.110/1.8;%/1.6;
%Mul=.110/1.7;
Up1=w_Zt0*Mul;
Down1=-w_Zt0*Mul;
Up0=w_Zt0*Mul;
Down0=-w_Zt0*Mul;

PProfitLimit=.00045;%Optimal .00045 for MSFT
PStopLimit=-.0005;
PProfit=0;
if((Sell==1) && (Trade==1))
    PProfit=log(SellPrice)-log(Price0(tt));

end
if((Buy==1) && (Trade==1))
    PProfit=log(Price0(tt))-log(BuyPrice);
end

if((Buy==1)&&(Sell==1)&&(Trade==1))
    tt
    str=input('There is an error');
end


if(((Fp(tt)>Up1)||(PProfit>=PProfitLimit)||(PProfit<=PStopLimit))&& ((Sell==1) && (Buy==0)&&(Trade==1))) %
    Buy=0;
    Sell=0;
    Trade=0;
    BuyPrice=Price0(tt);
    Profit=Profit+(SellPrice)-(BuyPrice);
    NoOfTrades=NoOfTrades+1;
    if(BuyTimes(bb)<tt)
    bb=bb+1;
    BuyTimes(bb)=tt;
    Pricebb(bb)=Price0(tt);
    end
    PositionVolume=PositionVolume+1;
end
if(((Fp(tt)<Down1)||(PProfit>=PProfitLimit)||(PProfit<=PStopLimit)) && ((Sell==0) && (Buy==1)&&(Trade==1))) %
    Sell=0;
    Buy=0;
    Trade=0;
    SellPrice=Price0(tt);
    Profit=Profit+(SellPrice)-(BuyPrice);
    NoOfTrades=NoOfTrades+1;
    if(SellTimes(ss)<tt)
    ss=ss+1;
    SellTimes(ss)=tt;
    Pricess(ss)=Price0(tt);
    end
    
    PositionVolume=PositionVolume-1;
    
end
if(((Fp(tt)<Down0)) && (Sell==0) && (Buy==0) && (Trade==0))%&&(WSum0(tt,1)>Up00)
    Buy=0;
    Sell=1;
    Trade=1;
    SellPrice=Price0(tt);
    if(SellTimes(ss)<tt)
    ss=ss+1;
    SellTimes(ss)=tt;
    Pricess(ss)=Price0(tt);
    end
    PositionVolume=PositionVolume-1;
end


if(((Fp(tt)>Up0)) && (Sell==0) && (Buy==0) &&(Trade==0))%&&(WSum0(tt,1)<Down00)
    Sell=0;
    Buy=1;
    Trade=1;
    BuyPrice=Price0(tt);

    if(BuyTimes(bb)<tt)
    bb=bb+1;
    BuyTimes(bb)=tt;
    Pricebb(bb)=Price0(tt);
    end
    PositionVolume=PositionVolume+1;
end
    
  Profit0(tt)=Profit;  
  PositionVolume0(tt)=PositionVolume;  
    
end

clf;

plot((5:1560),PositionVolume0(5:1560),'g')
%str=input('Look at stock positions'); %should remain between -1 and +1 since a new trade is not started until previous trade is closed.


yyaxis right
plot((5:1560),Profit0(5:1560),'k')


yyaxis left
plot((5:1560),Price0(5:1560),'g')


hold on
    yyaxis left
    plot(BuyTimes(2:bb),Pricebb(2:bb),'b+','MarkerSize',3);

    yyaxis left
    plot(SellTimes(2:ss),Pricess(2:ss),'ro','MarkerSize',2);
hold off

StockDate=datetime(Date0,'InputFormat','dd\MM\yyyy');
str1=string(StockDate, "yyyy-MM-dd");
yyaxis left
title(sprintf('Profit And Tesla Stock Mid-Price Graph on %s',str1));
xlabel('Time in units of 15 seconds')
ylabel('Mid-Price(Green)')

yyaxis right
ylabel('Trading Profit on Mid Price(Black)')

    

Profit
NoOfTrades
%str=input('Look at graph');
end
.
.
.
classdef StocksClassW
   properties
      StockSymbol=0;
      StockDate;
      
      StockPriceSeries(1561,1)=0;
      StockPrice0Series(1561,1)=0;
      StockBidSeries(1561,1)=0;
      StockAskSeries(1561,1)=0;
      StockVolumeSeries(1561,1)=0;
      StockReturnSeries(1561,1)=0;
      LogReturns(1561,1)=0;
      TotalVolume=0;
      LRMean;
      LRVar;
      LRSD;
      
   end
   methods
       % function obj=StocksClass()
       %     obj.StockSymbol=StockSymbol0;
       % end
       function obj=StocksClassW(StockSymbol0,StockDate0)
           StockSymbol0
            obj.StockSymbol=StockSymbol0;
            obj.StockDate=datetime(StockDate0,'InputFormat','dd\MM\yyyy');
            str1=string(obj.StockDate, "yyyy_MM_dd");
            str0="C:\Users\Ahsan\Documents\Project0\DailyData\";
            pathstring=str0+ str1 + '\' + str1 + '_' + string(obj.StockSymbol);
            T = readtable(pathstring);
            
            obj.StockBidSeries(1:1561,1)=table2array(T(1:1561,4));
            %obj.StockAskSeries(1:1561,1)=table2array(T(1:1561,3));
            obj.StockAskSeries(1:1561,1)=table2array(T(1:1561,5));
            obj.StockPrice0Series(1:1561,1)=.5*obj.StockBidSeries(1:1561,1)+.5*obj.StockAskSeries(1:1561,1);
            obj.StockVolumeSeries(1:1561,1)=table2array(T(1:1561,6));
            
            obj.LogReturns(1)=0;
            for nn=2:1561
                obj.LogReturns(nn,1)=log(obj.StockPrice0Series(nn,1))-log(obj.StockPrice0Series(nn-1,1));
            end
            
            obj.TotalVolume=sum(obj.StockVolumeSeries(:,1));
            
            obj.LRMean=sum(obj.LogReturns(:,1))/1560;
            obj.LRVar=sum((obj.LogReturns(:,1).^2-obj.LRMean.^2))/1560;
            obj.LRSD=sqrt(obj.LRVar);
       
       end
      
   end
end
.
.
.
For files below, add them to special directories and use the calling routine accordingly in the program where these files are called.
You will also need the 41 text files of Tesla Stock data of market prices, bid prices, ask prices, volume all 15 secs apart for 41 different dates in a zip file.
TeslaFiles.zip
(810.55 KiB) Downloaded 135 times
You will also need the following date file to read relevant dates in the program to fetch the data from files to computer memory.
ReadDates0.zip
(222 Bytes) Downloaded 136 times
When you run this program, the following should be the final output

TotalProfitYet =
     3.933149999999953e+02
TotalProfit =
     3.933149999999953e+02
TotalTrades =
       22422
TradingProfit =
     3.933149999999953e+02
TotalCommissions =
     1.569540000000000e+02
TotalSpreadEarned =
     2.127602830128225e+03
AvgSpread =
  Columns 1 through 3
                   0   0.185461538461541   0.185173076923080
  Columns 4 through 6
   0.181967948717951   0.171044871794874   0.141076923076926
  Columns 7 through 9
   0.175474358974355   0.163942307692309   0.215878205128208
  Columns 10 through 12
   0.241987179487182   0.180538461538463   0.198416666666668
  Columns 13 through 15
   0.195685897435900   0.167794871794873   0.199076923076925
  Columns 16 through 18
   0.173820512820515   0.157724358974360   0.172102564102566
  Columns 19 through 21
   0.178910256410257   0.182532051282054   0.150647435897440
  Columns 22 through 24
   0.173532051282053   0.203500000000002   0.181474358974359
  Columns 25 through 27
   0.212910256410258   0.196057692307696   0.184333333333334
  Columns 28 through 30
   0.254365384615386   0.271557692307694   0.221467948717949
  Columns 31 through 33
   0.180846153846156   0.222769230769233   0.193557692307694
  Columns 34 through 36
   0.243602564102567   0.155814102564104   0.160942307692309
  Columns 37 through 39
   0.178942307692311   0.169506410256412   0.162455128205131
  Columns 40 through 41
   0.157891025641026   0.134775641025641
You think life is a secret, Life is only love of flying, It has seen many ups and downs, But it likes travel more than the destination. Allama Iqbal