Hi all,
I have been enjoying testing out and playing with the existing framework in Quantopian. It seems to suit my needs well, but I am having some difficulties implementing simple tasks (adjusting to the source code is a bit tricky).
Anyway, I have a day trading algorithm that allows me to read in from a properly formatted csv file and execute trades. The algorithm was working very well for me, except recently I changed how I populate my backlog of stocks. Now there is infrequent spacing between listed stocks (I.E. there might only be a stock every 3 days). I do not want to hold my last stock until the next trade, but I could not find a way access dates outside of this list of stocks that corresponds to my universe.
How can the code be tweaked such that I may read in from a properly formatted CSV, buy the stock at the following days opening price (as I am currently doing) and sell at that days close?
Thanks!
import pandas as pd
def initialize(context):
# import the custom CSV data file
fetch_csv("ProperlyFormatted.csv",
pre_func=preview,
post_func=preview,
date_column='date',
universe_func=my_universe)
# Create a variable to track the date change
context.yesterday = None
context.holdingStock = None
# my_universe returns a set of securities that define your universe.
def my_universe(context, fetcher_data):
my_stocks = set(fetcher_data['sid'])
context.count = len(my_stocks)
return my_stocks
# see a snapshot of your CSV for debugging
def preview(df):
log.info(' %s ' % df.head())
return df
def handle_data(context,data):
# bam. copied someone else's code and it uses closing price
# out of the box!
if get_datetime().date() == context.yesterday: return
context.yesterday = get_datetime().date()
# basic idea, for each day, find out which stock we need to buy from the csv, then buy it. on the next day, sell everything we have and try to buy that day's stock. in this way, we only hold on to a stock for a day at most
print "Holding %s" % context.holdingStock
# if we're holding something, try to sell all of it
if(context.holdingStock is not None):
try:
# sell 100% of this stock
order_target_percent(context.holdingStock, 0)
print "Sold %s" % context.holdingStock.symbol
except:
pass
for stock in data:
print "%s %s" % (str(data[stock]['day']), str(get_datetime().date()))
# if the stock in the loop isn't to be traded for the day, skip
if str(data[stock]['day']) != str(get_datetime().date()):
continue
try:
# use 100% of our money to buy the stock
order_target_percent(stock, 1)
context.holdingStock = stock
print "Bought %s" % stock.symbol
break # ordered one for today, that's enough
except:
print "Couldn't order %s" % stock.symbol
P.S. ~~ ProperlyFormatted is a csv containing a list of stock names and dates.