I am trying to buy and sell SPY using simple moving average (sma) triggers. However, the context.sma_short and context.sma_long vectors being created with the pipeline data include a large number of securities. Could someone tell me how to simply select the sma for SPY? Would it involve selecting the row for SPY out of the "results" data frame that is created? Is there a way to filter the Pipeline output by SID/Ticker? I have seen Pipeline output filtered by other factors such as market cap before using pipe.set_screen().
Thank you! :)
import numpy as np
import pandas as pd
from scipy import stats
from pytz import timezone
import datetime
import math
import time
import functools
import random
import itertools
from statsmodels.stats.moment_helpers import cov2corr, corr2cov, se_cov
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import morningstar
from quantopian.pipeline.factors import SimpleMovingAverage, Latest, EWMSTD, EWMA
from quantopian.pipeline import CustomFactor
def initialize(context):
context.stock=symbol('SPY')
context.buy_flag=False
context.sell_flag=False
pipe = Pipeline()
pipe = attach_pipeline(pipe, name='pipeline')
context.sma_short= SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=50)
pipe.add(context.sma_short, "sma_short")
context.sma_long= SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=100)
pipe.add(context.sma_long, "sma_long")
schedule_function(trading, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(hours=1))
def before_trading_start(context,data):
results = pipeline_output('pipeline')
print results.head(5)
if context.sma_short > context.sma_long and context.portfolio.positions_value == 0:
context.buy_flag=True
else:
context.buy_flag=False
if context.sma_short < context.sma_long and context.portfolio.positions_value>0:
context.sell_flag=True
else:
context.sell_flag=False
def trading(context, data):
if context.buy_flag == True:
order_value(context.stock, context.portfolio.cash)
if context.sell_flag == True:
order_target(context.stock, 0)
def handle_data(context, data):
record(positions=context.portfolio.positions_value,
cash=context.portfolio.cash,
buy_flag=context.buy_flag,
sell_flag=context.sell_flag)