Hey guys, new to pipeline and python, mind helping me out?
Here's my code and the error I get is saying that I have an invalid syntax on the "pipe =" line
from quantopian.pipeline import Pipeline
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.filters.morningstar import Q1500US
from quantopian.pipeline.factors import MovingAverageConvergenceDivergenceSignal
from quantopian.pipeline.data import morningstar
import talib
import numpy as np
import pandas as pd
def initialize(context):
# The algo will go long on the number of stocks set here
context.num_stocks_to_buy = 15
# Rebalance every day at market open
schedule_function(rebalance,
date_rule=date_rules.every_day(),
time_rule=time_rules.market_open())
def before_trading_start(context):
"""
Called before the start of each trading day.
"""
def create_weights(context, stocks):
"""
Takes in a list of securities and calculates
the portfolio weighting percentage used for each stock in the portfolio
"""
if len(stocks) == 0:
return 0
else:
# Buy only 0.95 of portfolio value to avoid borrowing
weight = .95/len(stocks)
return weight
def handle_data(context, data):
"""
Code logic to run during the trading day.
handle_data() gets called every price bar. In this algorithm,
rather than running through our trading logic every price bar, every day,
we use scheduled_function() in initialize() to execute trades 1x per day
"""
prices = data.current(context.stocks, fields = "price", bar_count = 1, frequency = "1d"
pipe = Pipeline()
attach_pipeline(pipe, 'my_pipeline')
pipe.add(prices, 'Prices')
pipe.add(pe_ratio, "PE Ratio")
pipe.add(eps_growth, "EPS Growth")
eps_growth = morningstar.fundamentals.earnings_ratios.diluted_eps_growth.latest
pe_ratio = morningstar.fundamentals.valuation_ratios.pe_ratio.latest
net_margin = morningstar.fundamentals.operation_ratios.net_margin.latest
current_ratio = morningstar.fundamentals.operation_ratios.current_ratio.latest
rev_growth = morningstar.fundamentals.operation_ratios.revenue_growth.latest
pipe.set_screen(fundamentals.valuation.market_cap > 100000000)
pipe.set_screen(fundamentals.valuation_ratios.pe_ratio < 15)
pipe.set_screen(fundamentals.valuation_ratios.pe_ratio > 0)
pipe.set_screen(fundamentals.earnings_ratios.diluted_eps_growth > 20)
pipe.set_screen(fundamentals.operation_ratios.current_ratio > 1.5)
pipe.set_screen(fundamentals.operation_ratios.net_margin > 5)
pipe.set_screen(fundamentals.operation_ratios.revenue_growth > 20)
output = pipeline_output('my_pipeline')
context.my_universe = output.sort('EPS Growth', ascending=False).iloc[:300]
update_universe(context.my_universe.index)
def MACD(prices, fastperiod=12, slowperiod=26, signalperiod=9):
'''
Function to return the difference between the most recent
MACD value and MACD signal. Positive values are long
position entry signals
optional args:
fastperiod = 12
slowperiod = 26
signalperiod = 9
Returns: macd - signal
'''
macd, signal, hist = talib.MACD(prices,
fastperiod=fastperiod,
slowperiod=slowperiod,
signalperiod=signalperiod)
return macd[-1] - signal[-1]
def rebalance(context, data):
# Track cash to avoid leverage
cash = context.portfolio.cash
pricess = data.history(context.portfolio.positions, fields="price", bar_count=40, frequency="1d")
macd = pricess.apply(MACD, fastperiod=12, slowperiod=26, signalperiod=9)
# Exit all positions that have fallen out of the top rankings
for stock in context.portfolio.positions:
if stock not in context.my_universe.index or macd[stock] < 0:
if stock in data:
order_target(stock, 0)
cash += context.portfolio.positions[stock].amount
log.info("Exiting security: %s" % stock)
# Create weights for each stock
weight = create_weights(context, context.my_universe.index)
# Rebalance all stocks to target weight of overall portfolio
for stock in context.my_universe.index:
if weight != 0 and stock in data and macd[stock] > 0:
notional = context.portfolio.portfolio_value * weight
price = data[stock].price
numshares = int(notional / price)
# Growth companies could be trading thin: avoid them
if cash > price * numshares and numshares < data[stock].volume * 0.2:
if stock in data:
order_target_percent(stock, weight)
cash -= notional - context.portfolio.positions[stock].amount
log.info("Placing order: %s" % stock)