Notebook
In [99]:
from quantopian.pipeline.data.sentdex import sentiment
from quantopian.pipeline.filters.morningstar import Q1500US, Q500US
from quantopian.pipeline.filters import StaticAssets
from quantopian.research import run_pipeline
from quantopian.pipeline import Pipeline, CustomFactor, CustomFilter
from quantopian.pipeline.data.builtin import USEquityPricing
import numpy as np
from quantopian.pipeline.factors import (
    AverageDollarVolume, RollingLinearRegressionOfReturns,
)
from quantopian.pipeline.data import morningstar
from quantopian.pipeline.filters.morningstar import IsPrimaryShare
import talib
import matplotlib.pyplot as plt
import math
In [53]:
class past_volatility(CustomFactor):
    inputs = [USEquityPricing.close]
    window_length = 3
    
    def compute(self, today, assets, out, values):  
        def RSI(close, timeperiod=2):  
            if np.isnan(close).any():
                return np.nan
            return talib.RSI(close, timeperiod=timeperiod)  
        
        results = np.apply_along_axis(RSI, 0 ,values)  
        out[:] = results[-1]  
        
def make_pipeline():
    pipe = Pipeline()
    my_sec_filter = StaticAssets([symbols('SPY')])
    rsi = past_volatility()
    pipe.add(rsi, 'rsi')
    pipe.set_screen(my_sec_filter)
    return pipe
    
In [58]:
result = run_pipeline(make_pipeline(), start_date='2002-04-01', end_date='2017-06-29')
prices = get_pricing(symbols('SPY'), start_date='2002-04-01', end_date='2017-06-29')
In [69]:
data = result.rsi.unstack()
In [157]:
data['ForwardOneDayReturn'] = ((prices.close_price.shift(-11) - prices.open_price) / prices.open_price).shift(-1)
In [158]:
data.columns = ['RSI', 'ForwardOneDayReturn']
In [159]:
data.head()
Out[159]:
RSI ForwardOneDayReturn
2002-04-01 00:00:00+00:00 100.00000 -0.008159
2002-04-02 00:00:00+00:00 75.00000 -0.010980
2002-04-03 00:00:00+00:00 0.00000 0.002224
2002-04-04 00:00:00+00:00 0.00000 -0.018117
2002-04-05 00:00:00+00:00 11.19403 -0.008449
In [160]:
data.loc[data.RSI < 40, ['ForwardOneDayReturn']].plot.hist()
Out[160]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f349d02dd50>
In [161]:
data.loc[data.RSI < 40, ['ForwardOneDayReturn']].plot()
Out[161]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f349634a750>
In [162]:
data.loc[data.RSI < 40, ['ForwardOneDayReturn']].mean()
Out[162]:
ForwardOneDayReturn    0.004175
dtype: float64
In [163]:
data.loc[data.RSI < 40, ['ForwardOneDayReturn']].var()
Out[163]:
ForwardOneDayReturn    0.001477
dtype: float64
In [164]:
data.loc[data.RSI < 40, ['ForwardOneDayReturn']].mean() / math.sqrt(data.loc[data.RSI < 40, ['ForwardOneDayReturn']].var())
Out[164]:
ForwardOneDayReturn    0.108608
dtype: float64
In [ ]: