Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Drawdown example

I have tried to write a couple programs but haven't really been able to fully grasp how all the pieces fit together. I have tried reading a lot of the documentation and examples online etc... But I quickly get lost... It seems they start with super simple examples but quickly get complicated. Also, I see lots of little differences with how they go about programming something that is basically the same thing. I understand there are lots of ways to skin a cat... But this causes me to just get confused. As far as I am concerned, I don't really care at this point what the "best" way is. Even the "worst" way is better than "no" way at this point which is where I am currently at.

I am trying to keep things simple to start, as I learn and progress, I can "improve" and learn why I should do things one way vs the other.

Ok... So I simply want to make a graph of the "drawdown" for Tesla. At this point, I would like to simply hard code "Tesla" and if i want to see drawdown for apple... Then I can backspace a couple times and type in Apple.

As I understand, I may need to place an order to actually produce a graph of drawdown. If this is the case then I would like to simply say I buy 1 share on X date. For example, I buy 1 share on July 2nd, 2019. Then If I want to change the date... I can simply backspace a few times and type in a new date.

One problem I keep running into is that I find only a piece of the code I need. For example just the piece to show drawdown but I can never figure out how to combine the pieces of code together to make it all work.

I know if someone provided the solution, I could study it and begin to understand how all this works. Again, keep it simple for me, just the basic minimum I need to add a plot of drawdown. Thank you.

8 responses

Quantopian has two distinct environments. There is the 'Notebooks' environment (also called 'research') and there is the 'Algorithm' environment ( alo called the IDE). Notebooks are based on Jupyter interactive python and are best for visualizing and analyzing data. Algorithms are really meant to test trading strategies.

If one just wants to simply draw a graph and easily (and quickly) change some data then notebooks are the way to go. There are several methods to get both prices and returns which are in the quantopian.research module. Additionally, there is a handy (under appreciated) module called empyrical which has a number of portfolio metric calculations including max_drawdown. Info on these packages are in the docs and here.

So, one first needs to import the methods one wants to use. Next fetch the prices and returns. Then calculate the running max drawdown. And finally, plot the results. Something like this

# Import some methods we will be needing  
from quantopian.research import get_pricing, returns  
from empyrical import max_drawdown

# First let's make a place where we can easily set the stock and dates we want to check  
stock = 'TSLA'  
start_date = '1-1-2020'  
end_date = '9-1-2020'

# Next let's get both the stock close prices and daily returns over the dates  
stock_prices = get_pricing(stock, start_date, end_date, fields='price')  
stock_returns = returns(stock, start_date, end_date, price_field='price')

# To get the max drawdown use the empyrical drawdown method  
# Apply it over an expanding window of stock_returns  
stock_drawdown = stock_returns.expanding().apply(max_drawdown)

# Now plot these. Setting secondary_y=True adds a second Y axis for returns  
stock_prices.plot()  
stock_returns.plot(secondary_y=True)  
stock_drawdown.plot(secondary_y=True)

Attached is a notebook with the above code. You can change the 'stock' and the dates and then re-run the notebook to view the updated graph of drawdown.

Hope that helps and is something to continue building on.

Disclaimer

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 Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian 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.

@Dan , Thanks , find it useful :)

@Dan, Thanks your example is great!! and very simple which I love. The max drawdown is helpful. However, what would be even more helpful would be a graph of the drawdown like in the picture in the link below. I have been digging around and it does not appear that empyrical has this. However, it seems that it may be easy to modify some of the code to graph this. But I don't know enough to do this. I am thinking I can use:

stock_drawdown = stock_returns.expanding().apply(my_drawdown)

and make a function that tracks the max return and min return and subtracts them or something like that if that makes since.

see these graphs for example:

https://acrinv.com/drawdowns-help-visualize-losses/

@ Russell Turner

I have been digging around and it does not appear that empyrical has this

from empyrical import max_drawdown , roll_max_drown

max_drawdown : takes the biggest drawdown in your chosen period
roll_max_drawdown : is the same thing as "stock_returns.expanding().apply(my_drawdown)" but in Jupyter Notebook (outside of Quantopian & Research) .

Note : In "roll_max_drawdown" you have to add the "window" argument ...

Hope It helps.

I saw the roll_max_drawdown... but doesn't that only calculate the max_drawdown in a particular window? I basically want to see all the drawdowns big and small... not just the "big" (ie: the max drawdown). For example I want to be able to see that the stock drawdown is 2% then 10% then back to 0% then down to 5%... etc... did you look at the graph in the link I provided above? Here is another example (second to last graph):

http://econompicdata.blogspot.com/2016/02/

It is exactly the rule of the "roll_max_drown" it gives the drawdown depending on the window size.

The "max_drawdrown" gives the overall drawdown

I don't think I that is what I want. By window size it means like 1 week or 1 month or whatever window i choose right? So the roll_max_drawdown is only going to plot one max drawdown for each week or one make drawdown for each month. This is not what I want. I have been doing some more digging and I think it is actually called an underwater chart when it is displayed the way I want to see it. I see that:

pyfolio.create_returns_tear_sheet(returns, positions=None, transactions=None, live_start_date=None, cone_std=(1.0, 1.5, 2.0), benchmark_rets=None, bootstrap=False, turnover_denom='AGB', header_rows=None, return_fig=False)

looks like it provides this... I am going to try to see if i can figure out how to use that in the code provided above by Dan Whitnable

Ok so I tried this:

# Import some methods we will be needing  
from quantopian.research import get_pricing, returns  
import pyfolio as pf

# First let's make a place where we can easily set the stock and dates we want to check  
stock = 'TSLA'  
start_date = '1-1-2020'  
end_date = '9-1-2020'

# Next let's get both the stock close prices and daily returns over the dates  
stock_prices = get_pricing(stock, start_date, end_date, fields='price')  
stock_returns = returns(stock, start_date, end_date, price_field='price')

# drawdown graph (underwater chart) plus lots of other neat stuff  
pf.create_returns_tear_sheet(stock_returns)

This seems to mostly work. It makes an underwater chart of drawdown just like i wanted, It provides lots of other neat information too. However, there is an error that says:

TypeError: 'zipline.assets._assets.Equity' object is not iterable

I don't know what this means.

I have attached the notebook.