How would you usually use order_target_percent using Mean Reversion?

Can I speak with your superior. I dont think you get the issue and you have used already alot of my time. You are not even responding to my posts. 



YOUR COURSE TEACHES:



RAW = SHARE AMOUNT (NO NEED FOR REBALANCE)

LOGS = CASH WEIGHTS (NEED TO REBALANCE)



I AM USING NOT USING LOGS AND IM REBALANCING AND IM USING A RATIO BASED ON CASH.



THIS IS AGAINST YOUR TEACHINGS!!!



Kindly let me have a meeting with your course designer.



Much thanks.

Hello Jane,



Please, make your script links public so anybody in our team can access them.



Thanks,



José Carlos

https://drive.google.com/file/d/1BtU2QZvX1BGVmGFTE6WX02SZArFSdYFp/view?usp=sharing



 

Any progress? Or just another excuse?

Hi Jane,



Thanks for your patience and posting your query on the community. Since this is a huge thread, let me take time to explain the strategy and implementation in detail. I hope that the various questions posted in this and other thread gets answered.



In this post, I'll try to answer the difference between raw prices and log prices and how you can use the correct order methods and the brief meaning of those methods. Request you to please read the complete thread. 



Why does pairs trading strategy work?

In a pairs trading strategy, we simultaneously buy one asset and sell another asset in most cases. The view in pairs trading strategy is that the spread between the two assets will revert back to the mean. If the spread doesn't revert back to the mean then we may incur losses.



In what quantity you should buy or sell the asset?



There are two methods to figure that out.


  1. Raw prices



    In raw prices, you run the regression of prices. The slope of the regression line will give you the hedge ratio. Let's say the equation is Apple - 2 * Facebook.



    When you go long on the spread then you will buy 1 share of Apple and sell 2 shares of Facebook.



    This order placement can be achieved in blueshift by the following two lines of code.

     
order_target(symbol('AAPL', 1)
order_target(symbol('FB', -2)

We are using the order target method. This method will place the order for 1 share of Apple if we already don't own the share. If our portfolio already has 1 share of Apple then no order will be placed.

So if these codes are in the rebalance function and you call rebalance function every day then no fresh order will be placed. But the position of 1 share long on Apple will be maintained. You can read more about order_target_function here.

The implementation of the raw price method is covered in detail in the course. This can be accessed from the following link: https://quantra.quantinsti.com/startCourseDetails?cid=55&section_no=8&unit_no=5&course_type=paid&unit_type=Document

2. Log prices

The second method is using log prices instead of raw prices. When you use log prices then the spread is the market value. If the spread is below then you need to buy Apple shares whose value is equal to 1.5 times Facebook shares. For example, you can buy $150 of apple shares and sell $100 worth of Facebook shares

spread = Apple - 1.5 * Facebook

How you can achieve this in blueshift?

You need to use order_target_value
 
order_target_value(symbol('AAPL'),150)
order_target_value(symbol('FB'),-100)

The target value function targets a specific dollar amount of asset. Using this method if there is a change in the market value of Apple, let's say from 150 to 130 dollars and you call this method again then an extra $20 worth of Apple will be purchased. In this case, we can say that portfolio is rebalanced every time the order_target_value method is called as the portfolio market value of the asset is constantly changing over a period of time.


Will the results from these two methods be the same?

The returns from these two methods will be different as in one method you are using raw prices and determining the hedge ratio from it. And in the other, we are calculating the market value to hedge in each instance. Therefore, the results would vary and differ from each other.


Would it be possible that the results could be bad from the pairs trading strategy?

Yes, pairs trading is not a risk-free strategy and could result in a loss if the spread doesn't revert back to mean. In that case, the results could be impacted.

Please refer to the sample code on implementing the pairs trading strategy using log prices here and the raw prices available in the course.

I hope this helps.

Thanks
Ishan
 

BTW THAT SAMPLE CODE IS COMPLETLY WRONG!!!



context.quantity = 0.5 



So if it was equal to 1 therefore:

order_target_percent(context.security_1, -context.quantity) Would mean you are buying that stock with 100% of your equity.





You need to take your time and look at the issues Im bring forward.





total =model.params[0]context.quantity+context.quantity

Place the order

if long_entry and context.position == 0:

print(f"{get_datetime()} Long Spread")

Take long position in the spread

order_target_percent(context.security_1, context.quantity/total)

order_target_percent(context.security_2, -model.params[0]*context.quantity/total)

context.position = 1

elif short_entry and context.position == 0:

print(f"{get_datetime()} Short Spread")

Take short position in the spread

order_target_percent(context.security_1, -context.quantity/total)

order_target_percent(context.security_2, model.params[0]*context.quantity/total)

context.position = -1





This would be correct.

Hi Jane



The sample code sent is not completely wrong. The context.quantity variable is set to 0.5 and not 1. It works perfectly fine if the hedge ratio is less than or equal to 1.



For example, if the hedge ratio is 0.5, the order target percent code will resolve to the following

 

order_target_percent(context.security_1, 0.5)
order_target_percent(context.security_2, -0.25)

This is perfectly valid order placement logic. 

If you expect the hedge ratio to be less than 2, you can change the context.quantity to 0.25 and so on.


If you want to set this dynamically then the correct code will be below.

1. You need to take the absolute of model.params[0]
2. There is no need for variable context.quantity


# Total portfolio allocation
portfolio = np.abs(model.params[0])+1

security_1_percentage = 1.0/portfolio
security_2_percentage = model.params[0]/portfolio

# Place the order
if long_entry and context.position == 0:
    print(f"{get_datetime()} Long Spread")
    # Take a long position in the spread
    order_target_percent(context.security_1, security_1_percentage)
    order_target_percent(context.security_2, -security_2_percentage)
    context.position = 1

elif short_entry and context.position == 0:
    print(f"{get_datetime()} Short Spread")
    # Take a short position in the spread
    order_target_percent(context.security_1, -security_1_percentage)
    order_target_percent(context.security_2, security_2_percentage)
    context.position = -1
Thank you!

YOUR LOGIC WAS COMPLETELY WRONG!!!

see link below:

https://www.basic-math-explained.com/new-community/images/fraction33.jpg



In the previous comments even your coworkers are using a total for a denominator. 



THIS IS ELEMENTARY MATHEMATHCS



Kindly speak to a superior like Mr Ghosh or simply read the chat over. 

OR LEARN BASIC MATH



You need math to be a decent programmer. AND THIS IS BASIC STUFF!!!



You aren’t gracious enough to admit when you are wrong. This is why you are taking over a month to solve an issue you are supposed to know about.

Sad state of affairs but I’m hopeful you learn how to deal with customers and improve your product quality and customer relations.





Also your corrected model is what I’m using!!! and if you READ THE CHAT YOULL SEE THAT.



Mr. Carlos is checking this, because its working without logs better that with logs using the calculations for fractions.

THE QUESTION IS WHY!!!


From your recent reply, we believe that you don't have any questions on log prices and raw prices, how to apply them and order_target_percent method. You are using the code for log prices which can be found here. And don’t have any further questions on the code for log prices in the previous link.

Please refer to below two answers on better clarity on the difference in performance with logs and without logs.

Will the results from logs or without logs be the same? Or is one method better than the other?
The returns from these two methods will be different as in one method you are using raw prices and determining the hedge ratio from it. And in the other, we are calculating the market value to hedge in each instance. Since these two are different approaches, the results would vary and differ from each other. We can’t conclude if any method is superior to another.

Would it be possible that the results could be bad from the pairs trading strategy?
Yes, pairs trading is not a risk-free strategy and could result in a loss if the spread doesn't revert back to the mean. In that case, the results could be bad.

Thanks

 

You dont listen. Its sad tbh. Im repeating the same thing over and over. This is why I asked for a meeting but you cancelled last minuite.





ILL COPY AND PASTE WHAT A IM SAYING OVER



"I am using raw prices and rebalancing and using a calculation for weights that is expecting or uses cash value!



Therefore this should not work the way it’s working.



When I use log prices it performs terribly. I’m asking why is this."

Is Jose Carlos Gonzales Tanaka stil working on it?

Hello Jane, 

I'm unable to understand the following:

"I am using raw prices and rebalancing and using a calculation for weights that is expecting or uses cash value!

Therefore this should not work the way it’s working.

----
Can you please clearly state your question, specifying what you did, what you expected and what actually happened (contrary to your expectation)

Regarding the question:

When I use log prices it performs terribly. I’m asking why is this.

As explained by Mr Ishan, pairs trading is not a risk-free strategy and can make losses when the spread doesn't revert to the mean. I'm pasting his exact explanation below
----

Would it be possible that the results could be bad from the pairs trading strategy?
Yes, pairs trading is not a risk-free strategy and could result in a loss if the spread doesn't revert back to the mean. In that case, the results could be bad.

----
It should be noted that we don't provide a service of checking your entire code or correcting/commenting on your code. Instead, if you have a problem understanding the concept explained in the course or unable to understand a piece of code presented in the course material, we are always here to explain and clarify that to you.

It should also be noted that the Blueshift has a 'full backtest' functionality which generates transactions and round trips. (you can perform a full backtest by clicking on the 'New Backtest' button on the right top). Studying the tear sheets of the full backtest along with transactions and round trips will give you a complete understanding of the backtest results of your strategy. 

Thank you

Im not asking you for synthax error or runtime error. Im asking you for help with a specific issue which is a concept you teach in your mean reversion course. (Raw vs Log Prices for input and getting share amount vs cash value in asset weights) Logic errors occur when there is a fault in the logic or structure of the problem.



Pasting a previous post AGAIN for the umpteenth time.




08 Aug 2022

On your course you say that I need to use log prices to create a spread that rebalances and gives weights in cash value. ATM THIS IS NOT HAPPENING.



I am using raw prices and rebalancing and using a calculation for weights that is expecting or uses cash value!



Therefore this should not work the way it’s working.





Are you capable of solving this? 

I have several points on your questions, but let's save it for later. First the question itself.



Your question, as I read from the above, is quite vague. Using OLS regression with raw prices will give you a hedge ratio. Using OLS with log prices will give you another. You should treat the former as a ratio of units of stocks, and the second as ratio of dollar value. There is a subtle and interesting theory behind it. If you are not clear why these ratios behave this way, please ask a separate question and I will explain. Of course you are free to use these ratios in whichever way you please, and depending on the assets and time-frame and rest of your strategy, the performance can range from spectacular to disastrous in either cases. Financial markets is driven on a lot by randomness, and a strategy based on theory can perform very badly and one with theorical blunders can perform exceptionally well (at least for a while).



On the other points -


  1. I see you asked many questions (that is awesome) and most of the questions you asked are not very clear (that is not good at all). Usually, it is best to ask "I want to do X (a very specific and relevant thing), how do I do it?" or "I understood about X (again, a very specific thing) this , am I correct?". Asking question like "I did this, why this works (or does not)?" is vague and requires someone to understand what you did, review your work in details and try to spot the errors if any. There are many different reasons why a strategy works in a certain way. Usually, these way of asking questions are considered poor phrasing and reduces probability of receiving a satisfactory answer. Avoid abbreviation (ATM) and proof-read your question to make sure it conveys what you want to ask. If you are not a native English speaker, ask help from your friends. Anyone (including your fellow learners) can answer your questions in this forum. Getting an answer here is not your entitlement, but a privilege. Asking badly phrased questions will increase the chance your question getting unsatisfactory (or even no) answers. If you do not receive a good answer, try to rephrase your question (e.g. I did X, I expected Y as a result, but I got Z, with details of X,Y and Z and concise description/resources to replicate your observation). Following up with "??" is considered spamming, and we do not tolerate spams on this forum.


  2. Remember this is a community forum, not a customer service portal. Be respectful of the people you interact with here. Do not use derogatory tone or words/phrases. Do not use capital letters or multiple question marks (in most English-speaking communities, these are considered rude gestures in case you are not aware). Be appreciative of the answers you receive and efforts put in by the answerer.  I have seen you have violated these norms in multiple places on this forum. Consider this as your first and final warning. If we see a repeat of these sort of behaviours in the future, you will be banned from this community.

     

My question is about understanding why the code I sent is performing well without logs for price input when the calculations for weights are in cash. It shouldn’t perform better than with logs. So I sent the code and Im waiting on the overview. I can’t see a reason why it’s doing this this is why Im talking to you for the last 2 months.

Your assumption "it should'nt perform better then(sic, should be than?) with logs" is wrong. If you do not understand why it is wrong - read my comments above carefully again. There is no guarantee if you do things in the X way, it will always do better than if you do it in the Y way in financial markets, even if X is theoretically correct and Y is the wrong way to do things.



If you can prove that Y performs consistently (meaning across periods covering all scenarios of underlying risks and many different stocks pairs) better than X, then congratulations! You have probably discovered a new theory or at any rate have a publishable research paper material (this is how we reject old theories and propose new ones).



Analyze your strategy that is performing better and try to understand the sources of the performance. One reason it can do better is that you have a wrong hedge ratio (i.e. you are not hedged correctly, and have residual exposure), but the market moved in the favour of your exposure during the period of test. To analyze the sources of profit and loss, for example, you can run a backtest, download the performance data, and compare beta/correlation of the profit/loss to the spread and to the individual stocks to confirm. If the profit/loss is highly correlated to the spread, that means you are running the pair trade in a correct way (even if it performs worse, pair trading is a view on the directionality of the spread). Else if it is correlated to the stock X or Y, you are doing it wrong (even if it is performing better) and you probably got lucky.



It is important to understand the source of your profit and loss to develop a robust strategy. If you are not sure how to do this, please ask a separate question (frame it as I want to do X, how do I do it). That is a good question to ask. Asking someone to do it for you is a wrong question to ask and will not get you much in reply or results.

Its not an assuption. my process or concept is based on your theory you have in your mean reversion course. 



You use log prices for cash weights and raw for share amount. 



I need a rational behind the huge disparity in the performance from the people who theory is coming from.



This is what we call a logical error. And Im asking you to find it, because I am not seeing it. If you are saying you wont then say that but the last message from Mr Carlos indicates that he is capable and trying. But it would be nice if he could respond or give feed back.

I am not sure you are really reading my answers. 


  1. "You use log prices for cash weights and raw for share amount. " that is correct. If you are not sure what is the theory behind, please ask a separate question


  2. Does the #1 mean using one or the other (or whatever you have done in your strategy) will necessary perform always better or worse than the other? In other words - does performance of a particular strategy over a particular period proves a theory wrong (or right?) The answer is no. The "logical error" is to assume a performance of a particular stratey over a particular period proves a theory wrong. To know why, read the above comments again carefully. It also explains how to prove the theory wrong if you really wanted to. You need to run a lot of tests over a lot of time periods and for lot of stocks and their aggregate performane has to be better in one case over the other in a statistically significant way.


  3. How can you explain why one is performing better than the other - see the above comment explaining one possible reason (imperfect hedge -> unbalanced exposure -> getting lucky). Analyze the sources of profit/loss.



    4. How to estimate source of profit/loss - again see the above comment. Ask a separate question if you are not clear on the procedure.



    I am sure Mr Carlos is capable, and all others who have replied to you before. But that is not a good use of their time and not a good way for you to learn. To learn and to really understand, you must do it yourself. Your comments above show you still have a gap in understanding. Doing the exerise under 4 will clear things more than any answers or readymade work can do. Feel free to ask for help and guidance but you have to carry out your own work. We can tell you how to do it, but we cannot do it for you. If you really wanted to get it done by others, I suggest you reach out a market risk consultant or general quant consultant.

Thanks for your attempt at helping, however ill wait till Mr Carlos responds with his findings



Also you said "You need to run a lot of tests over a lot of time periods and for lot of stocks and their aggregate performane has to be better in one case over the other in a statistically significant way".- Yes I have, and they were all consistent in proving contrary to theory. This is a fundamental issue that must be understood and corrected. This not an assumption. The code is from your blog and the theory is from the course I paid for all am asking is why does its performance prove contrary to what is being taught.



If this is not something you are willing to do please say that. But understand that Mr Carlos is currenlty working on this.

http://epchan.blogspot.com/2013/11/cointegration-trading-with-log-prices.html



Here is another source that confirms your teaching.



The issue therefore is with the code. Im asking where in the logic is causing the issue. Its not a synthax or runtime error.