0% found this document useful (0 votes)
77 views9 pages

S15 Bull Test

The document contains log entries and configuration details for an algorithmic trading strategy. It modifies buying power based on available funds and refreshes stop losses daily. It executes new trades at 10:00 AM, assigns stop losses at 10:05 AM, and checks log files at 10:10 AM. The strategy adds an additional level for a total of 5 levels for "milking". It initializes context variables, schedules functions to execute trades daily and refresh stops, and includes a handle_data function to manage positions based on price thresholds and cancel/replace stop orders as thresholds are crossed.

Uploaded by

partha_665590810
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views9 pages

S15 Bull Test

The document contains log entries and configuration details for an algorithmic trading strategy. It modifies buying power based on available funds and refreshes stop losses daily. It executes new trades at 10:00 AM, assigns stop losses at 10:05 AM, and checks log files at 10:10 AM. The strategy adds an additional level for a total of 5 levels for "milking". It initializes context variables, schedules functions to execute trades daily and refresh stops, and includes a handle_data function to manage positions based on price thresholds and cancel/replace stop orders as thresholds are crossed.

Uploaded by

partha_665590810
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

1

"""

Modified with Buying Power based on Available Fund on 4/26/2017, which is 10 times

Modified log for refresh_stocks on 10/4/2016

Printing Global Stock List

Printing Context

Execute NEW trade at 10:00 AM Daily, Assign Stop Loss at 10:05 AM , Check Log file at 10:10 AM

Refresh existing Portfolio Stop Loss at 9:32 AM

Add 1 more levels for milking total of 5 levels

"""

# Libraries imported for use in algorithm are below

import datetime # For manipulating time within the algorithm

import numpy as np # For conducting numerical calculations

import heapq # For sorting the share priority dictionary

# Global data lists used for various purposes within the algorithm are below

Global_Stock_List = []

def initialize(context):

############### Make Adjustments To Variables Below ##################

context.Daily_Volume_Threshold = 100000 # Set Minimum Daily Volume Level Here

context.Minute_Volume_Threshold = 0 # Set Minimum Prior Minute Volume Level Here

context.Min_Price_Threshold = 10 # Set Minimum Price Level Here

context.Max_Price_Threshold = 550 # Set Maximum Price Level Here

context.Step_1_Percent = 0.004 # Set Step One Percentage For Milking

context.Step_1_New_Stop = 0.0002 # Set New Stop Level For Step One

context.Step_2_Percent = 0.006 # Set Step Two Percentage For Milking

context.Step_2_New_Stop = 0.0005 # Set New Stop Level For Step Two

context.Step_3_Percent = 0.009 # Set Step Three Percentage For Milking

context.Step_3_New_Stop = 0.001 # Set New Stop Level For Step Three


2

context.Step_4_Percent = 0.0125 # Set Step Four Percentage For Milking

context.Step_4_New_Stop = 0.0015 # Set New Stop Level For Step Four

context.Step_5_Percent = 0.015 # Set Step Five Percentage For Milking

context.Step_5_New_Stop = 0.002 # Set New Stop Level For Five Four

Hours_After_Open = 0 # Set number of hours after open to commence the trade

Minutes_After_Open = 30 # Set number of minutes after open to commence the trade

#####################################################################

set_long_only() ### Set long only

# Code to benchmark to compare algorithm results

set_benchmark(symbol('SPY')) # Set to SPY

# Setting slippage and commission to 0 as control for future adjustment

set_slippage(slippage.FixedSlippage(spread=0.00))

set_commission(commission.PerShare(cost=0.00, min_trade_cost=0.0))

# Pull in the data from the CSV stored in a URL

fetch_csv(https://docs.google.com/spreadsheets/d/e/2PACX-1vS3fgFw3AoYVqLdLG3NFLhAUBqD0JyDLLIgSsmLlmKZ4cw46qhMTGKHaBdd-w8t2bEnxT-
9AS3wawsT/pub?gid=0&single=true&output=csv',

date_column = 'Date',

date_format = '%m/%d/%y')

# Set Timing Rules Of Scheduled Functions Below

# The function below schedules the trade of the daily predictions

schedule_function(execute_trade,

date_rules.every_day(),

time_rules.market_open(hours=Hours_After_Open, minutes=Minutes_After_Open))

# The function below schedules the ordering of the initial stop loss orders

schedule_function(order_initial_stops,

date_rules.every_day(),
3

time_rules.market_open(hours=Hours_After_Open, minutes=Minutes_After_Open+5))

# The function below is for logging data at end of day

schedule_function(log_new_stocks,

date_rules.every_day(),

time_rules.market_open(hours=0, minutes=40))

# The function below refreshes the initial stops every morning

schedule_function(refresh_stops,

date_rules.every_day(),

time_rules.market_open(hours=0, minutes=2))

def handle_data(context, data):

##### Pulls in neccesary context data and stores as variables ####

Step_1_Percent = context.Step_1_Percent

Step_1_New_Stop = context.Step_1_New_Stop

Step_2_Percent = context.Step_2_Percent

Step_2_New_Stop = context.Step_2_New_Stop

Step_3_Percent = context.Step_3_Percent

Step_3_New_Stop = context.Step_3_New_Stop

Step_4_Percent = context.Step_4_Percent

Step_4_New_Stop = context.Step_4_New_Stop

Step_5_Percent = context.Step_5_Percent

Step_5_New_Stop = context.Step_5_New_Stop

Step_Dictionary = {} # Create empty dictionary for assessing the step up of each stock

for stock in context.portfolio.positions: #Iterates through each stock in the portfolio

orders = get_open_orders(stock) # determines if each stock in the portfolio has an open order

Cost_Basis = context.portfolio.positions[stock].cost_basis # Determine cost basis of each stock in the portfolio

Current_Price = data.current(stock, 'price') # Determine current price of each stock

if Current_Price >= (Cost_Basis + Cost_Basis*Step_1_Percent) and Current_Price < (Cost_Basis + Cost_Basis*Step_2_Percent): # measure for step 1 increase
4

Step_Dictionary[stock] = 1 # append to dictionary with step 1 as value

if orders: # Check if open orders exist for the stock

for ordering in orders: # for any open order

cancel_order(ordering) # cancel open order

elif Current_Price >= (Cost_Basis + Cost_Basis*Step_2_Percent) and Current_Price < (Cost_Basis + Cost_Basis*Step_3_Percent): # measure for step 2 increase

Step_Dictionary[stock] = 2 # append to dictionary with step 2 as value

if orders: # Check if open orders exist for the stock

for ordering in orders: # for any open order

cancel_order(ordering) # cancel open order

elif Current_Price >= (Cost_Basis + Cost_Basis*Step_3_Percent) and Current_Price < (Cost_Basis + Cost_Basis*Step_4_Percent): # measure for step 3 increase

Step_Dictionary[stock] = 3 # append to dictionary with step 3 as value

if orders: # Check if open orders exist for the stock

for ordering in orders: # for any open order

cancel_order(ordering) # cancel open order

elif Current_Price >= (Cost_Basis + Cost_Basis*Step_4_Percent): # measure for step 4 increase

Step_Dictionary[stock] = 4 # append to dictionary with step 4 as value

if orders: # Check if open orders exist for the stock

for ordering in orders: # for any open order

cancel_order(ordering) # cancel open order

elif Current_Price >= (Cost_Basis + Cost_Basis*Step_5_Percent): # measure for step 5 increase

Step_Dictionary[stock] = 5 # append to dictionary with step 5 as value

if orders: # Check if open orders exist for the stock

for ordering in orders: # for any open order

cancel_order(ordering) # cancel open order

else: # if no step up

Step_Dictionary[stock] = 0 # append with step 0

for stock, value in Step_Dictionary.items(): # Iterate through stock and values in step dictionary

Cost_Basis = context.portfolio.positions[stock].cost_basis # Determine cost basis of each stock in the portfolio

Shares_Owned = context.portfolio.positions[stock].amount # determine quantity of stocks owned

if stock in context.portfolio.positions: # Ensure stock is owned


5

if Shares_Owned > 0: # second filter to ensure stocks are owned and positive

if value == 0: # if no step up

pass # do nothing

elif value == 1: # if step up to step 1

order(stock, -Shares_Owned, style=StopOrder((Cost_Basis*(1+Step_1_Percent))*(Cost_Basis*(1-Step_1_New_Stop))))

elif value == 2: #if step up to step 2

order(stock, -Shares_Owned, style=StopOrder((Cost_Basis*(1+Step_2_Percent))*(Cost_Basis*(1-Step_2_New_Stop))))

elif value == 3: # if step up to step 3

order(stock, -Shares_Owned, style=StopOrder((Cost_Basis*(1+Step_3_Percent))*(Cost_Basis*(1-Step_3_New_Stop))))

elif value == 4: # if step up to step 4

order(stock, -Shares_Owned, style=StopOrder((Cost_Basis*(1+Step_4_Percent))*(Cost_Basis*(1-Step_4_New_Stop))))

elif value == 5: # if step up to step 5

order(stock, -Shares_Owned, style=StopOrder((Cost_Basis*(1+Step_5_Percent))*(Cost_Basis*(1-Step_5_New_Stop))))

def execute_trade(context, data):

############## This Section Pull In the Variables From Context #############

Daily_Volume_Threshold = context.Daily_Volume_Threshold

Minute_Volume_Threshold = context.Minute_Volume_Threshold

Buying_Power = context.account.available_funds*10

Min_Price_Threshold = context.Min_Price_Threshold

Max_Price_Threshold = context.Max_Price_Threshold

############################################################################

# Determine how much cash is available for trading before making decisions

#Starting_Cash = context.portfolio.cash

Starting_Cash = context.account.available_funds+Buying_Power

#Starting_Cash = context.portfolio.cash

#print Starting_Cash

print "Starting Cash"

print Starting_Cash

Available_Funds = context.account.available_funds
6

print "Available_Funds"

print Available_Funds

Buying_Power = context.account.buying_power

print "Buying Power"

print Buying_Power

Cushion = context.account.cushion

print "Cushion"

print Cushion

#Credit_Utilized = context.portfolio.positions_value

Share_Quantity = {} # Create empty dictionary to store share quantity from CSV

Cash_Used = [] # Create empty list for monitoring cash availability

for stock in data.fetcher_assets: # Iterate through all stock on csv file

if stock not in Global_Stock_List: # Ensure stock is not already purchased

Share_Quantity[stock] = data.current(stock, 'Shares') # pull stock specific shares from csv and append to the Share Quantity Dictionary

Share_Priority = {} # Create empty dictionary to store share priority from csv

for stock in data.fetcher_assets: #Iterate through all stocks on csv file

if stock not in Global_Stock_List: # Ensure stock is not already purchased

Share_Priority[stock] = data.current(stock, 'Sort') # Append share priority to the Share Priority Dictionary.

# Organize the share priority dictionary

Daily_Quantity = len(Share_Priority)

#print len(Share_Priority)

Sorted_Priority = heapq.nsmallest(Daily_Quantity, Share_Priority, key=Share_Priority.get)

#print len(Sorted_Priority)

Partial_Flag = 0 # Reset Partial Flag to 0 Every Day

for stock in Sorted_Priority:

shares = int(Share_Quantity[stock])

Daily_Volume = data.history(stock, 'volume', 2, '1d') # pull prior day volume for each stock.

print "Stock"

print stock

print "Previous Days Volumn"


7

print Daily_Volume[-1]

print "Latest Days Volumn"

print Daily_Volume[0]

Minute_Volume = data.history(stock, 'volume', 2, '1m') # pull prior minute volume for each stock.

print "Stock"

print stock

print "Latest Minute Volumn"

print Minute_Volume[0]

print "Previous Minute Volumn"

print Minute_Volume[-1]

Last_Price = data.history(stock,'price', 15,'1m')[0] # pull last price 15 minutes prior for each stock

log.info(Last_Price)

print "Price at 9:30AM"

print Last_Price

Price = data.current(stock, 'price') # pull price history of each stock

print "Price at 9:45AM"

log.info(Price)

print Price

# Check that the stock to trade meets the price and volume requirements

if Daily_Volume[-2] >= Daily_Volume_Threshold and Minute_Volume[0] >= Minute_Volume_Threshold and Price >= Min_Price_Threshold and Price <=
Max_Price_Threshold:

Total_Cost = Price * shares # Estimate the cash needed for the pending trade

#print Total_Cost

Cash_Used.append(Total_Cost) # append daily cash used list for measuring cumulative cash

#print np.sum(Cash_Used)

if Starting_Cash - np.sum(Cash_Used) >= 0: # Ensure there is cash for trade

#if data.can_trade(stock): # Make sure stock is capable of trading per Q

order(stock, shares) # order selected stock at share amount in csv file

elif Starting_Cash - np.sum(Cash_Used) < 0: # If not enough cash for full trade, follow steps below

Cash_Deficiency = Starting_Cash - np.sum(Cash_Used) # Estimate cash deficiency

Partial_Cost = Total_Cost - abs(Cash_Deficiency) # Determine partial cost

Partial_Shares = Partial_Cost / Price # Determine partial shares to buy


8

if Partial_Flag == 0: # Ensure the flag is set to buy

if Starting_Cash <= 5.00: # Don't do anything if there is less than $5

pass

else:

if data.can_trade(stock): # Ensure the stock can trade

order(stock, Partial_Shares) # Order the partial shares

Partial_Flag = Partial_Flag + 1 # Set the flag to not buy for rest of day

def order_initial_stops(context, data):

SLPercent = {} # Create empty dictionary to store SLPercent values

for stock in data.fetcher_assets: # Iterate through all stocks in csv file

if stock in context.portfolio.positions: # determine if stock is owned

if stock not in Global_Stock_List: # determine if stock is not in global list

SLPercent[stock] = data.current(stock, 'SLPercent') # append SLPercent to dictionary

for stock, percent in SLPercent.items(): # iterate through the slpercent dictionary

Price_Paid = context.portfolio.positions[stock].cost_basis # find price paid for each stock

Stop_Price = Price_Paid - percent*Price_Paid # calculate stop loss price

Shares_Owned = context.portfolio.positions[stock].amount # determine shares owned

order(stock, -Shares_Owned, style=StopOrder(Stop_Price)) # place initial stop loss

def refresh_stops(context, data):

Step_1_Percent = context.Step_1_Percent

SLPercent = {} # Create empty dictionary

for stock in data.fetcher_assets: # iterate through all stocks in csv

if stock in context.portfolio.positions: # determine if stock is owned

SLPercent[stock] = data.current(stock, 'SLPercent') # append dictionary

for stock, percent in SLPercent.items(): # iterate through dictionary

Price_Paid = context.portfolio.positions[stock].cost_basis # determine price paid

Stop_Price = Price_Paid - percent*Price_Paid # calculate stop loss

Shares_Owned = context.portfolio.positions[stock].amount # determine shares owned

# Ensure stock has not reached any step up phase

if data.current(stock, 'price') < Price_Paid + Price_Paid*Step_1_Percent:


9

order(stock, -Shares_Owned, style=StopOrder(Stop_Price)) # refresh the stop loss

def log_new_stocks(context, data): # Function for logging new stocks each day

for stock in data.fetcher_assets: # Iterate through all stocks in CSV

Global_Stock_List.append(stock) # Append global stock list with all new and prior stocks

#print Global Stock List

print "Global_Stock_List"

print Global_Stock_List

#print log order initial stop

print "Context"

print context,data

leverage=context.account.leverage # Set variable for leverage

record(leverage=leverage) # Display leverage on Quantopian chart

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy