Notebook
In [113]:
import numpy as np
import pandas as pd

from quantopian.pipeline import Pipeline, CustomFactor, CustomClassifier
from quantopian.research import run_pipeline
from quantopian.pipeline.data import Fundamentals  
from quantopian.pipeline.data.psychsignal import stocktwits

from quantopian.interactive.data.psychsignal import stocktwits as stocktwits_i
from odo import odo
In [105]:
weekday_dict =dict(zip(range(7), ['Monday', 'Tuesday', 'Wednesday', 
                                  'Thursday', 'Friday', 'Saturday', 'Sunday']))
In [98]:
start_date = pd.datetime(2018,5,3)
end_date = pd.datetime(2018,5,8)
In [99]:
class CustomSentiment(CustomFactor):
    # Default inputs and window_length
    inputs = [stocktwits.bullish_intensity]
    window_length = 3

    def compute(self, today, asset_ids, out, values):
        if today.weekday() == 0:
            # This should fetch the Saturday Data if it is available
            factor_value = values[-2]
        else:
            factor_value = values[-1]
        
        out[:] = factor_value
In [100]:
def make_pipeline():
    universe = Fundamentals.symbol.latest.eq('AAPL')
    
    return Pipeline(columns={'custom_buillish_intensity': CustomSentiment(),
                             'default_bullish_intensity': stocktwits.bullish_intensity.latest,
                             'asof_date':stocktwits.asof_date.latest
                            }, 
                   screen=universe)
    
In [107]:
results = run_pipeline(make_pipeline(), start_date, end_date)
results['pipeline_weekday'] = results.index.get_level_values(0).map(lambda x: weekday_dict[x.weekday()])
results
Out[107]:
asof_date custom_buillish_intensity default_bullish_intensity pipeline_weekday
2018-05-03 00:00:00+00:00 Equity(24 [AAPL]) 2018-05-02 1.765437 1.765437 Thursday
2018-05-04 00:00:00+00:00 Equity(24 [AAPL]) 2018-05-03 1.814731 1.814731 Friday
2018-05-07 00:00:00+00:00 Equity(24 [AAPL]) 2018-05-06 1.814731 1.947912 Monday
2018-05-08 00:00:00+00:00 Equity(24 [AAPL]) 2018-05-07 1.778633 1.778633 Tuesday

On Monday, the custom sentiment factor is pulling Thursday's data again instead of pulling Saturday's data.

Blaze Results

In [114]:
aapl_sentiment = odo(stocktwits_i[stocktwits_i['symbol']=='AAPL'], pd.DataFrame)
mask = (aapl_sentiment.timestamp > start_date) & (aapl_sentiment.timestamp < end_date)
df = aapl_sentiment.loc[mask, ['timestamp', 'asof_date', 'bullish_intensity']]
df['asof_weekday'] = df.asof_date.map(lambda x: weekday_dict[x.weekday()])
df
Out[114]:
timestamp asof_date bullish_intensity asof_weekday
3163 2018-05-03 10:06:35.410674 2018-05-02 1.765437 Wednesday
3164 2018-05-04 10:06:10.839176 2018-05-03 1.814731 Thursday
3165 2018-05-05 10:06:33.551362 2018-05-04 1.853558 Friday
3166 2018-05-06 10:06:04.266128 2018-05-05 1.969333 Saturday
3167 2018-05-07 10:05:57.384800 2018-05-06 1.947912 Sunday