Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
measuring money flows?

In the context of Quantopian, is there any way to estimate money flows? For example, during the 2007-2008 financial crisis, I figure that money was flowing quickly out of stocks and into more secure investments. As the market has recovered, money has been flowing back into the market, right? I'd like to write an algorithm that would illustrate the relative flow in and out of the market, over the 2007-2013 time frame. Any guidance?

Thanks,

Grant

15 responses

It looks like WSJ has Dow Jones money flow data by sector. The daily historical tables go back to August 2010.

In the same section the WSJ has a list of individual stocks with the highest outflow of money and the largest inflow of money. These two charts are updated every 15 minutes and are available as a tab-delimited text file. The daily historical record for these tables goes back to May 2007.

ICI has an interesting spreadsheet of monthly mutual fund money flow from 2007 onward. It is broken down by region (world/domestic) and asset type (equity/bond).

This might be useful to validate the Dow Jones data.

The US Treasury Dept has a nice monthly CSV file of Cross-Border Portfolio Financial Flows going back to 1978.

When using this dataset keep in mind that it is 2 month lagged (e.g. they don't release April data until June).

Thanks Dennis,

Would there be any way to use the Quantopian dataset to obtain the indicator? Admittedly, I have not done my homework here, but I figure that there ought to be some way to show that, for example, during the 2007-2008 crisis, investors shifted out of stocks and into bonds/cash/etc. The indicator should be pretty dramatic for this time period, and might shed some light on how the market behaves when there is fear, uncertainty and doubt (FUD).

Grant

As it stands I think the Quantopian dataset only uses unsigned volume (e.g. it doesn't indicate which direction the money is going).

However money out-flow is very likely to depress the trading price (since there is more supply than demand).

Using this assumption it is possible to roughly estimate the money flow from the OHLCV dataset provided by Quantopian.

You could then calculate the money flow indicator for bellweather securities (SPY, BND, UUP, GLD) and that would give you a sense of enthusiasm for stocks, bonds, cash and gold. You could probably do the same for different sector ETFs.

http://www.investopedia.com/terms/m/moneyflow.asp
http://en.wikipedia.org/wiki/Money_flow_index
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:chaikin_money_flow

Thanks Dennis,

The Wikipedia site provides "steps to calculate the Money flow index over N days" that can be implemented in Quantopian straightforwardly.

Grant

Dennis,

Here's my first crack at computing the money flow index, for SPY & BND. I haven't checked the code line-by-line, but it sorta yields the anticipated behavior. If you find bugs or identify improvements, please let me know.

Grant

The custom data plot looks very convincing. Nice job.

Here is a strategy that goes "all in" either SPY or BND depending on which MFI indicator is bigger. The code is flexible enough to use other daily rebalancing schemes if desired.

Here is a version of the "all in" strategy that is tailored for small accounts. It starts with $10k and enforces a 3 day waiting period after any sell order. To achieve the waiting period it either goes all in SPY or waits in cash.

Another change is the use of a smoothing function on the MFI indicator. In this case I'm using an exponential average with decay of 10%. In other words the new MFI value only has a 10% impact on the previous remembered MFI value.

My previous version stayed out of the market about 50% of the time. Here is a version (still tailored for small accounts) that switches between SPY and BND. In addition to the 3 day waiting period (following a sell) this version also enforces a 1 day waiting period after a buy.

Thanks Dennis,

Glad to see that you had some fun with it!

Grant

Hello Dennis,

I tweaked the code a bit so that with a single call to the batch transform, the MFI over a range of N would be returned as a matrix. Each column corresponds, respectively, to a sid:

context.stocks = [sid(8554),sid(33652)] # SPY & BND  

So, columns 0 & 1 correspond to the MFI's for SPY & BND, respectively.

Each row of the returned matrix corresponds to the MFI computed over N days. Row 0 corresponds to 1 day, row 1 to 2 days, and so on, up to a maximum of W_L-1 days (where W_L is the length of the trailing window used by the batch transform).

This way, if one wanted to write a trading algorithm that compared, say, MFI(N=30 days) to MFI(N=60 days), only a single call would be required to the batch transform. In general, it facilitates more complex analyses of the MFI versus N.

Grant

Thanks Dennis, Grant

Thanks for the great work on this algorithm. I seem to be getting a error message every time I try to build the algorithm posted by Dennis on the 24th June 2013. The error message reads as follows:-

KeyError: 'high'
There was a runtime error on line 28.

Any ideas on how I can resolve?

Bevan

A money flow index (MFI) Pipeline custom factor was published here:

https://www.quantopian.com/posts/ta-lib-for-pipeline

Here's the code (I haven't checked and tested it):


class MFI(CustomFactor):  
    """  
    Money Flow Index

    Volume Indicator

    **Default Inputs:**  USEquityPricing.high, USEquityPricing.low, USEquityPricing.close, USEquityPricing.volume

    **Default Window Length:** 15 (14 + 1-day for difference in prices)

    http://www.fmlabs.com/reference/default.htm?url=MoneyFlowIndex.htm  
    """     

    inputs = [USEquityPricing.high, USEquityPricing.low, USEquityPricing.close, USEquityPricing.volume]  
    window_length = 15

    def compute(self, today, assets, out, high, low, close, vol):

        # calculate typical price  
        typical_price = (high + low + close) / 3.

        # calculate money flow of typical price  
        money_flow = typical_price * vol

        # get differences in daily typical prices  
        tprice_diff = (typical_price - np.roll(typical_price, 1, axis=0))[1:]

        # create masked arrays for positive and negative money flow  
        pos_money_flow = np.ma.masked_array(money_flow[1:], tprice_diff < 0, fill_value = 0.)  
        neg_money_flow = np.ma.masked_array(money_flow[1:], tprice_diff > 0, fill_value = 0.)

        # calculate money ratio  
        money_ratio = np.sum(pos_money_flow, axis=0) / np.sum(neg_money_flow, axis=0)

        # MFI  
        out[:] = 100. - (100. / (1. + money_ratio))