quantopian / pyfolio

Portfolio and risk analytics in Python
https://quantopian.github.io/pyfolio
Apache License 2.0
5.52k stars 1.74k forks source link

pos.get_percent_alloc not working correctly with short positions (?) #197

Closed jkrauss82 closed 8 years ago

jkrauss82 commented 8 years ago

The function mentioned in the subject is making values absolute before calculating their relative weight in the portfolio. However this leads to incorrect weights for short positions when assuming that you actually increase your cash when short selling a stock.

As I take from the positions example in tears.py

index 'AAPL' 'MSFT' cash 2004-01-09 13939.3800 -14012.9930 711.5585 2004-01-12 14492.6300 -14624.8700 27.1821 2004-01-13 -13853.2800 13653.6400 -43.6375

the rationale of pyfolio might be different (I assume you do not want to be leveraged by 21 times in the AAPL position for this example, actually get_percent_alloc returns 0.486304 for this position). However, in reality (e. g. on Interactive Brokers) it does not work that way - what is your view on that matter?

a-campbell commented 8 years ago

I think you are correct. We should be using the net liquidation value (net_liquidation = longs - abs(shorts) + cash) as the denominator in get_percent_alloc. Currently, I think we are double counting shorts.

We should also probably change that positions example to depict a more likely scenario where cash reflects the presence of short positions under the assumption of < 3x leverage.

Thanks for the heads up!

humdings commented 8 years ago

@jkrauss82 Take a look at pos.get_long_short_pos, that should calculate the long and short allocations how you are expecting.

jkrauss82 commented 8 years ago

Well actually I got it working simply by removing the .abs() in line 37 of pos.py. The way we create our input data then works fine for the rest of the process and percentage values come out correct.

I am not familiar with all of the pyfolio code so I do not know if other functions depend on pos.get_percent_alloc and depend on the old way?

twiecki commented 8 years ago

Closed with https://github.com/quantopian/pyfolio/pull/201. Thanks for reporting @jkrauss82.