I've recently started using quantopian but its not really that intuitive for a newcomer. Im looking to check wether a stock in the stock universe was down the day before and also check if a particular stock is gapping down today. The pipelines make all this so counter intuitive (in my opinion) I've been used to Tradingviews pine script which is way more user friendly and I just simply can't wrap my head around the pipelines and how to properly do what I described.
For example when I try the following I get
import quantopian.algorithm as algo
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.filters import QTradableStocksUS
from quantopian.pipeline.filters.morningstar import Q500US
from quantopian.pipeline.factors import PercentChange
def initialize(context):
"""
Called once at the start of the algorithm.
"""
# Rebalance every day, 1 hour after market open.
schedule_function(ma_crossover_handling, date_rules.every_day(), time_rules.market_open(minutes=1))
set_benchmark(sid(19920))
context.QQQ = sid(19920)
# Create our dynamic stock selector.
algo.attach_pipeline(make_pipeline(), 'pipeline')
def make_pipeline():
"""
A function to create our dynamic stock selector (pipeline). Documentation
on pipeline can be found here:
https://www.quantopian.com/help#pipeline-title
"""
# Base universe set to the QTradableStocksUS
base_universe = Q500US()
pipe = Pipeline(
columns={
'close': USEquityPricing.close.latest,
"open": USEquityPricing.open.latest,
"high": USEquityPricing.high.latest,
"low": USEquityPricing.low.latest,
},
screen=base_universe
)
return pipe
def before_trading_start(context, data):
"""
Called every day before market open.
"""
context.output = algo.pipeline_output('pipeline')
# These are the securities that we are interested in trading each day.
context.security_list = context.output.index
def ma_crossover_handling(context, data):
for stock in context.security_list:
open_orders = get_open_orders()
price_history = history(bar_count=5, frequency='1d', field='price')
close_2_day_ago = price_history[stock][-3] # close two days ago
close_yesterday = price_history[stock][-2] # close of yesterday
open_today = price_history[stock][-1]
gap_percent = (open_today-close_yesterday)/close_yesterday*100
prevday = close_2_day_ago>close_yesterday
close_yesterdayQQQ = price_history[context.QQQ][-2] # close of yesterday
open_todayQQQ = price_history[context.QQQ][-1]
percentgapQQQ =(open_todayQQQ-close_yesterdayQQQ)/close_yesterdayQQQ*100
KeyError: Equity(2 [HWM])
There was a runtime error on line 57.