Back to Community
1st algo - Any suggestions

Ok the logic is here:

  1. fetch_csv from google drive
  2. Using fetch_csv data, when signal == 1 buy next open , 1 minute after open
  3. Sell position after 'n' day hold at 3 minutes before market close

My attempt at this is below, I am running into date time error on line:

# convert time to EST time
exchange_time = get_datetime('US/Eastern')

and also unassigned signal attribute on line:

def buy(context,data):
if signal == 1 and not context.bought:

Can anyone run this over and offer some guidance?

from quantopian.algorithm import calendars  
import pandas as pd  
from pytz import timezone  
import datetime  

# Preview the inported data frame  
def preview(df):  
    log.info(df.head())  
    return df

def time_lag(df):  
    # Correct look-ahead bias in mapping data to times  
    df = df.tshift(1, freq='D')  
    log.info(' \n %s ' % df.head())  
    return df

def initialize(context):  
    # Robinhood settings  
    set_long_only()  
    set_commission(commission.PerShare(cost=0, min_trade_cost=0))  
    context.allocation = 0.95 # Robinhood requires either limit orders or a 5% margin on orders.  
    # Fetch CSV from external source  
    fetch_csv('https://docs.google.com/spreadsheets/d/1EoT-AXs4wY88_kEsOkaYVX1KCpnovu4FwUZC1FTw9DQ/pub?gid=262287766&single=true&output=csv',  pre_func = preview, post_func=time_lag, usecols=['signal'], date_column = 'Date', symbol='signal')  
    # Set Symbol to buy  
    context.etf = symbol('UPRO')  
    context.last_rebalance = None  
    context.next_rebalance = None  
    context.holding_period = 5 #define holding period in days  
    # Set times to buy and sell  
    schedule_function(buy, date_rules.every_day(), time_rules.market_open(minutes=1),  
    half_days=True, calendar=calendars.US_EQUITIES)  
    schedule_function(sell, date_rules.every_day(), time_rules.market_close(minutes=3),  
    half_days=True, calendar=calendars.US_EQUITIES)  
    schedule_function(record_vars,  
                  date_rules.every_day(),  
                  time_rules.market_close())  
def handle_data(context, data):  
    current_signal = data.current('signal', 'signal')  
    print current_signal  
    if context.etf in data.fetcher_assets:  
        record(signal=data.current(context.etf,  
                                           'signal'))  
        print context.etf  
    # Get the current exchange time in EST timezone:  
    exchange_time = pd.Timestamp(get_datetime()).tz_convert('US/Eastern')

    # Get all open orders.  
open_orders = get_open_orders()

# Set buy rule, if 'signal' == 1 from fetch_csv enter  buy next open  
def buy(context,data):  
    if (current_signal == 1) not in open_orders and data.can_trade(context.etf):  
        order_target_percent(context.etf, context.allocation)  
    security = (symbol('UPRO'))  
    order_share = context.portfolio.positions[symbol('UPRO')].amount  
    print("check order_share=",security.symbol," share=",order_share)  
    context.last_rebalance = exchange_time  
    context.next_rebalance = context.last_rebalance + \  
    datetime.timedelta(days=context.holding_period)  
# Sell after fixed 'n' days  
def sell(context,data):  
#time to sell after 5 days and exit position  
    if context.last_rebalance is not None and exchange_time >= context.next_rebalance:  
            order_target_percent(context.etf,0.0)  
def record_vars(context, data):

  # Check how many long and short positions we have.  
  longs = 0  
  for position in context.portfolio.positions.itervalues():  
    if position.amount > 0:  
      longs += 1

  # Record our variables.  
  record(leverage=context.account.leverage, long_count=longs)  

8/22/2017 edited post to reflect change in exchange_time variable

2 responses

Should signal on your line with an error be current_signal? Also the indention on the exchange_time line doesn't match any function.

Ok i fixed exchange_time

    # Get the current exchange time in EST timezone:  
    exchange_time = pd.Timestamp(get_datetime()).tz_convert('US/Eastern')  

I call this later when I am buying:

    context.last_rebalance = exchange_time  
    context.next_rebalance = context.last_rebalance + \  
    datetime.timedelta(days=context.holding_period)  

Idea was to begin a count of trading days so that I could sell at a fixed number of trading days later...

These are my build errors now:

57  Warning Local variable 'exchange_time' is assigned to but never used  
64  Warning Undefined name 'signal'  
69  Warning Undefined name 'exchange_time'  
78  Warning Undefined name 'exchange_time'  

Still not sure why getting these.... also for signal.... I have a signal column in my fetch_csv data frame, wouldnt this suffice? even if i change it to current_signal I obtain same issue, anyone cast another eye over it?

current_signal:

def handle_data(context, data):  
    current_signal = data.current('signal', 'signal')  
    print current_signal  

I then want to use it later for the trading logic:

def buy(context,data):  
    if (current_signal == 1) not in open_orders and data.can_trade(context.etf):  
        order_target_percent(context.etf, context.allocation)  
    security = (symbol('UPRO'))  
    order_share = context.portfolio.positions[symbol('UPRO')].amount  
    print("check order_share=",security.symbol," share=",order_share)  
    context.last_rebalance = exchange_time  
    context.next_rebalance = context.last_rebalance + \  
    datetime.timedelta(days=context.holding_period)  

There was a runtime error.
NameError: global name 'current_signal' is not defined