def algo3(): print("algo 3:\nrandomly buy/sell every x minutes") if (a.marketIsOpen()): num2Buy = 20 # of unique stocks to buy numShares = 10 # of shares of each stock to buy symbols = a.getVolatilePennies(5, 'up') pos = a.getPos() # symbols = a.getPennies(1,'up') min2wait = 5 if (int(a.marketTime()[4]) % min2wait == 0): if (random.randint(0, 1)): #buy from symbols list a.createOrder("buy", random.randint(1, numShares), symbols[random.randint(0, len(symbols) - 1)], "market", "day") else: #sell from positions list rndStk = pos[random.randint( 0, len(pos) - 1)] #get a random stock that's held a.createOrder("sell", random.randint(1, int(rndStk["qty"])), rndStk["symbol"], "market", "day")
def algo2(): print("algo 2:\nbuy on the hour\nsell on the half hour\nrepeat") if (a.marketIsOpen()): num2Buy = 20 # of unique stocks to buy numShares = 10 # of shares of each stock to buy symbols = a.getVolatilePennies(5, 'up') # symbols = a.getPennies(1,'up') thisMin = int(a.marketTime()[4]) #get market minute if (thisMin == 0): #buy on the hour print("Buying Random...") a.buyRandom(num2Buy, symbols, numShares) elif (thisMin == 30): #sell on half hour print("Selling All...") a.sellAll(0) else: print("Market is Closed")
def algo12(): #TODO: fix sellAll instances so that it will only record in the event that we actually made trades f = open("algo12.txt", "r") #contains json info regarding trading j = a.json.loads(f.read()) f.close() symb = j['symb'] d = j["periodDateStart"].split("-") periodStartDate = date(int(d[0]), int(d[1]), int(d[2])) periodStartVal = float(j["periodPortStart"]) d = j["lastTradeDate"].split("-") lastTradeDate = date(int(d[0]), int(d[1]), int(d[2])) lastSellPrice = float(j["lastSellPrice"]) maxPrice = 0 # minPrice = 100000 #may be used later in trying to get the best buy currentPrice = 0 shares2buy = 0 buyPrice = 0 period = 10 #length of period (d) sellUp = 5 sellUpDn = 3 sellDn = 16 # buyDnUp = 1 portGain = 20 portLoss = 25 timeFromClose = 300 #seconds from close to start analyzing to buy timeSinceStart = 300 #seconds from start to analyze to sell (before infrequent checking) shortTime = 2 medTime = 20 longTime = 60 * 10 while True: #while the market is still alive print("\nMarket is alive") print("Today is " + str(date.today()) + ", the period start date is " + str(periodStartDate)) print("Day " + str(nwd(periodStartDate, date.today()) - 1) + " of " + str(period)) while (nwd(periodStartDate, date.today()) - 1 < period): #while within the period print("We're within the period.") [openTime, closeTime] = a.openCloseTimes(str( date.today())) #get the open and close times of today while (a.marketIsOpen() and date.today() > lastTradeDate): #while the market is open on a given day (that we haven't traded yet) print("\nMarket is open, and no trades made yet") print("Time is: " + str(a.dt.now())) if ( a.getShares(symb) > 0 ): #only check to sell if we have shares in the first place print("We have shares") buyPrice = a.getBuyPrice( symb) #set var to avoid lots of redundant calls while ((a.dt.now() - openTime).seconds < timeSinceStart): #while we're near the open time currentPrice = a.getPrice( symb) #set var to avoid lots of redundant calls print( str((a.dt.now() - openTime).seconds) + "s since open | stock change " + str(round((currentPrice / buyPrice - 1) * 100, 2)) + "%") #check frequently to sell if (currentPrice > buyPrice * (1 + sellUp / 100)): #if the stock price has reached the sell limit print("Stock has reached limit - up " + str( round(100 * (currentPrice / buyPrice - 1), 2) + "%")) maxPrice = max(maxPrice, currentPrice) if (currentPrice <= maxPrice * (1 - sellUpDn / 100)): print("Sell up conditions met.") if (a.sellAll(0)): #set trade flag lastTradeDate = date.today() lastSellPrice = currentPrice j['lastTradeDate'] = str(lastTradeDate) j['lastSellPrice'] = lastSellPrice time.sleep( shortTime) #we're excited, so check often else: time.sleep(medTime) #only check every so often if (lastTradeDate < date.today()): portVal = float(a.getAcct()['portfolio_value']) print("Checking portfolio status") if (portVal > periodStartVal * (1 + portGain / 100) or portVal < periodStartVal * (1 - portLoss / 100)): print("Portfolio won or lost - " + str(round(portVal / periodStartVal, 2)) + "%") if (a.sellAll(0)): periodStartDate = a.date.today() periodStartVal = portVal lastTradeDate = a.date.today() lastSellPrice = a.getPrice(symb) j['lastTradeDate'] = str(lastTradeDate) j['lastSellPrice'] = lastSellPrice j['periodStartDate'] = periodStartDate j['poeriodPortStart'] = periodStartVal #record the end of the period data portVal = float(a.getAcct()['portfolio_value']) print("Portfolio Value: $" + str(round(portVal, 2))) f = open("alpacaPortValues.txt", "a") f.write("\n" + str(date.today()) + "," + str(portVal)) f.close() print("Starting period over.") break else: print("Portfolio change: " + str( round((portVal / periodStartVal - 1) * 100, 2)) + "%") else: break if (lastTradeDate < date.today()): print("No trades made yet today.") while (a.timeTillClose() <= timeFromClose): #while we're close to the end of the day print("Close to closing | " + str(a.dt.now()) + " / " + str(closeTime)) #buy if no shares held, or sell if it reaches the sellUp % method currentPrice = a.getPrice(symb) maxPrice = 0 if (a.getShares(symb) == 0): print("No shares held. Buying.") #include buyDnUp & minPrice here shares2buy = int( float(a.getAcct()['buying_power']) / currentPrice) print( a.createOrder("buy", shares2buy, symb, "market", "day")) lastTradeDate = a.date.today() j['lastTradeDate'] = str(lastTradeDate) break elif (currentPrice >= a.getBuyPrice(symb) * (1 + sellUp / 100)): print("Shares still held, and price is going up") while (currentPrice >= maxPrice * (1 - sellUpDn) and a.timeTillClose() > shortTime * 2): print("Time left: " + str(a.timeTillClose( )) + "s | Stock change: " + str( round(currentPrice / a.getBuyPrice(symb), 2) - 1) + "%") currentPrice = a.getPrice(symb) maxPrice = max(maxPrice, currentPrice) time.sleep(shortTime) if ( currentPrice >= maxPrice * (1 - sellUpDn) ): #if the price is still up (hasn't started dropping yet), then wait till next morning to sell print( "Price is still up, but market is closing. Will continue tomorrow." ) else: if (a.sellAll(0)): lastTradeDate = a.date.today() lastSellPrice = currentPrice j['lastTradeDate'] = str(lastTradeDate) j['lastSellPrice'] = lastSellPrice break time.sleep(medTime) #if we're at any other time of the day #check slow - only sell if (lastTradeDate < a.date.today() and a.getShares(symb) > 0): if (a.getPrice(symb) >= a.getBuyPrice(symb) * (1 + sellUp / 100)): print("Price going up") maxPrice = 0 while (currentPrice >= maxPrice * (1 - sellUpDn / 100)): currentPrice = a.getPrice(symb) maxPrice = max(maxPrice, currentPrice) print("Current Price: " + str(currentPrice) + ", Max Price: " + str(maxPrice)) time.sleep(shortTime) if (a.sellAll(0)): lastSellPrice = currentPrice lastTradeDate = a.date.today() j['lastTradeDate'] = str(lastTradeDate) j['lastSellPrice'] = lastSellPrice break time.sleep( min(longTime, abs(a.timeTillClose() - timeFromClose)) ) #in case we're too close to the closing time, we don't want to overrun it else: break # set values and wait for the market to open again print("Done trading for the day.") f = open("algo12.txt", "w") f.write(a.json.dumps(j)) f.close() maxPrice = 0 currentPrice = 0 shares2buy = 0 print("Current Time: " + str(a.marketTime())) print("Will resume in " + str(a.timeTillOpen()) + " seconds") time.sleep(a.timeTillOpen()) #sell all at end of period and reset values print("End of period. Selling all and resetting.") if (a.sellAll(0)): #sell everything at the end of the period #record the end of the period data portVal = float(a.getAcct()['portfolio_value']) print("Portfolio Value: $" + str(round(portVal, 2))) f = open("alpacaPortValues.txt", "a") f.write("\n" + str(date.today()) + "," + str(portVal)) f.close() #record the trading info lastTradeDate = date.today() j['lastTradeDate'] = str(lastTradeDate) j['periodDateStart'] = str(date.today()) j['periodPortStart'] = a.getAcct()['portfolio_value'] maxPrice = 0 currentPrice = 0 shares2buy = 0 f = open("algo12.txt", "w") f.write(a.json.dumps(j)) f.close() print("Current Time: " + str(a.marketTime())) print("Will resume in " + str(a.timeTillOpen()) + " seconds") time.sleep(a.timeTillOpen()) '''
def algo10(): symb = 'SD' #ticker symbol length = 10 #days to hold out for sellUp = 9 #sell if the stock is up this far sellDn = 19 #sell if the stock falls this far # startPortfolio = float(a.getAcct()["portfolio_value"]) #portfolio balance at the beginning startPortfolio = 100.0 portfolioGain = 20 #if portfolio value gains by this %, sell and wait till end of period portfolioLoss = 50 #if portfolio value falls by this %, sell and wait till end of period buyPrice = a.getBuyPrice(symb) #init last buy price sellPrice = 0 #init last sell price sharesHeld = a.getShares(symb) #get current held shares of the stock # startDate = date(2020,4,27) marketTime = a.marketTime() #do this to reduce number of API calls startDate = date(marketTime[0], marketTime[1], marketTime[2]) #date of initial investments today = date(marketTime[0], marketTime[1], marketTime[2]) #date to be contiuously updated # filename = "/srv/http/portfolio.json" #used on the serve to display public data while ((today - startDate).days <= length): #while within the period # marketTime = a.marketTime() # today = date(marketTime[0],marketTime[1],marketTime[2]) #set today print("Day " + str((today - startDate).days) + " of " + str(length)) #show the current day # f = open(filename,'w') #open the json file to write to # f.write(a.json.dumps({"portfolioIncrease":float(a.getAcct()["portfolio_value"])/startPortfolio, "period":length,"daysIn":(today-startDate).days})) #write the json data for the server # f.close() #close the json file tradeMade = 0 #reset daily trade counter if (a.marketIsOpen()): #check portfolio value if (float(a.getAcct()["portfolio_value"]) >= ((1 + portfolioGain / 100) * startPortfolio)): sellPrice = a.getPrice(symb) a.sellAll(0) tradeMade = 1 print("Win Time: " + str(today - startDate) + " days") sharesHeld = a.getShares(symb) break elif ((float(a.getAcct()["portfolio_value"]) <= (1 - portfolioLoss / 100)) and (sharesHeld > 0)): print( "Portfolio Failed at " + str(a.marketTime()) + " - Current Value: " + a.getAcct()["portfolio_value"]) #let me know what happened sellPrice = a.getPrice(symb) a.sellAll(0) tradeMade = 1 sharesHeld = a.getShares(symb) #check stock value sharesHeld = a.getShares(symb) #get currently held shares stockVal = a.getPrice(symb) # get the stock's current value if ( a.getShares(symb) == 0 and stockVal >= sellPrice ): #if we don't have shares, and and the price has increased since the last sale, buy buyPrice = int( float(a.getAcct()['buying_power']) / stockVal) #set "buy price", this is actually shares to buy print(a.createOrder("buy", buyPrice, symb, "market", "day")) #may have to make a limit buy buyPrice = float( a.getBuyPrice(symb)) #get actual price bought at elif ( sharesHeld > 0 and (stockVal >= (1 + sellUp / 100) * buyPrice or stockVal <= (1 - sellDn / 100) * buyPrice) ): #if shares are held and their value is sufficiently different to sell if (not tradeMade): #if a trade hasn't been made yet today if (today == startDate): #on the first day we buy #buy as much as we can afford if (sharesHeld == 0): #if no shares held, buy some sharesHeld = int( float(a.getAcct()['buying_power']) / a.getPrice(symb) ) #set # of shares to purchase based on price and current buying power print( a.createOrder( "buy", sharesHeld, symb, "market", "day")) #may have to make a limit buy buyPrice = float(a.getBuyPrice( symb)) #get actual price bought at sharesHeld = a.getShares( symb) #get actual shares held tradeMade = 1 #indicate that a trade has been made today else: #it's not the first day anymore #check portfolio value if (float(a.getAcct()["portfolio_value"]) >= ((1 + portfolioGain / 100) * startPortfolio) ): #if portfolio reached target gain sellPrice = a.getPrice(symb) #get appx sell price a.sellAll(0) #sell everything tradeMade = 1 #set the flag print("Win Time: " + str(today - startDate) + " days") sharesHeld = a.getShares( symb ) #update to actual shares held (should be 0) break #stop the loop elif ((float(a.getAcct()["portfolio_value"]) <= (1 - portfolioLoss / 100)) and (sharesHeld > 0)): #if portfolio lost :( print( "Portfolio lost too much. Selling out until we recover." ) sellPrice = a.getPrice(symb) #get appx sell price a.sellAll(0) #sell everything sharesHeld = a.getShares( symb) #get the shares held tradeMade = 1 #set the flag #check stock value stockVal = a.getPrice( symb) # get the stock's current value sharesHeld = a.getShares(symb) #update shares held if ( sharesHeld == 0 and stockVal >= sellPrice ): # if we don't have shares and the price has increased from the last sale (i.e. has recovered from a slide) buyPrice = int( float(a.getAcct()['buying_power']) / stockVal) #this is actually shares to buy print( a.createOrder( "buy", buyPrice, symb, "market", "day")) #may have to make a limit buy buyPrice = float(a.getBuyPrice( symb)) #get actual price bought at elif ( sharesHeld > 0 and (stockVal >= (1 + sellUp / 100) * buyPrice or stockVal <= (1 - sellDn / 100) * buyPrice) ): #if we have shares and it's greater or less than our initial buying price print("Lost the stock :/") if stockVal <= ( 1 - sellDn / 100) * buyPrice else print( "Won the stock :)") a.sellAll(0) #sell everything else: #market closed print("Done trading for the day.") time.sleep(60 * 15) print( str(a.marketTime()) + " - portfolio Value: " + a.getAcct()["portfolio_value"]) print(str(round(timeTillOpen() / 60, 2)) + " minutes till open.") time.sleep(60 * 30) if timeTillOpen() > (60 * 30) else time.sleep(60 * 5)
def algo8(): print( "algo 8:\nbuy a bunch of volatile stocks\nif stock return > portfolio return + some %, sell the stock, buy a new random one\nif portfolio return >= 2x target %, sellAll & stop for the day\nif portfolio return reached target %, but has since gone down, sellAll & stop for the day\nif portfolio return <= max allowed loss, then sellAll & stop for the day" ) openTime = int( a.marketTime() [3]) #this assumes the script is running before market is open startPortVal = a.getAcct()["last_equity"] maxPrice = 1 symbols = a.getVolatilePennies(maxPrice, 'up') percDiff = 2 #only sell if stock's return is this % higher than portfolio current gain/loss % targetPerc = 2 #shoot for this portfolio gain/day absMinPerc = 5 #biggest loss amount that we want at any point during the day (avoids major crashes) wait2start = 60 * 5 #wait this long (s) after open to start trading #wait for market to settle to start trading # while(a.marketTime()[3]<(openTime+wait2start)): # print("Market is open. Trading in "+str(round((wait2start-(a.marketTime()[3]-openTime))/60,2))+" minutes.") # time.sleep(60) if (a.marketIsOpen()): maxPrice = 1 #should be 1,2, or 5 usually symbols = a.getVolatilePennies(maxPrice, 'up') uniqueAvailable = len(symbols) num2Buy = int( uniqueAvailable * 3 / 4 ) # of unique stocks to buy - don't grab all from list, this should avoid too many repeats min2hold = 15 #minnumber to go down to before selling all and restarting waitTime = 5 #time to wait (s) between checking again perc2selldn = 20 # sell at this % loss targetPercMet = 0 # set flag if the target % has been met while (timeTillClose() >= 60): #go until ~1 min before market closes cashOnHand = float( a.getAcct()["cash"]) * 0.5 #avaiable cash to buy with numShares = int(cashOnHand / maxPrice / num2Buy) # of shares of each stock to buy pos = a.getPos() #get held positions portPerc = (float(a.getAcct()["equity"]) / float(startPortVal) - 1) * 100 #get % change of portfolio if (len(pos) >= min2hold): #as long as we have more than the minimum for e in pos: diff = float(e["current_price"]) - float( e["avg_entry_price"]) #check the gain/loss perc = diff / float( e["avg_entry_price"]) * 100 #get % change if (perc >= 3 / 4 * (portPerc + percDiff) or perc <= -3 / 4 * perc2selldn ): #show the info when it gets close to sell time print(e["symbol"] + " - " + str(round(perc, 2)) + "%") if ((perc >= (portPerc + percDiff) or perc <= -perc2selldn )): #if it meets the criteria to sell print( a.createOrder("sell", e["qty"], e["symbol"], "market", "day")) #sell that bitch a.buyRandom(1, symbols, numShares) #and buy a new random one else: #if we fall below minimum a.sellAll(0) #throw it all away a.buyFromTop(num2Buy, symbols, numShares) #and buy from the top again print("\n" + str(len(pos)) + " stocks held - Portfolio change: " + str(round(portPerc, 2)) + "% - " + str(timeTillClose()) + " seconds till close\n") if (portPerc >= 2 * targetPerc ): #if twice target % is reached, stop for the day a.sellAll() print("Target met x2! We done good. Done for the day.") break elif (portPerc >= targetPerc): #if target % is met, set the flag print("Target gain met! Seeing if we can go higher...") targetPercMet = 1 elif ( targetPercMet and portPerc < targetPerc ): #if the flag is set, but the portfolio % is now less, stop for the day a.sellAll() print( "We did well, but we done lost it. Done trading for the day." ) break elif ( portPerc <= -absMinPerc ): #if portfolio % is sucking balls, just give up for the day a.sellAll() print( "We lost it today. Calling it quits before too much is gone." ) break else: print("Market is closed.") print("Done trading for the day. See you tomorrow!")
def algo7(): print( "algo 7:\nbuy a bunch of volatile stocks\nif total portfolio value increased by X%, sell and hold there\nif total value decreased by Y%, sell aand hold there\nrepeat daily" ) #if it doesn't reach that by a certain time, then have secondary (and tertiary?) % to get to #if it's mostly negative by a certain time, then cut losses openTime = int( a.marketTime() [3]) #this assumes the script is running before market is open startPortVal = a.getAcct()["last_equity"] primaryPerc = 2 #sell everything if the porfolio reaches this gain time1 = openTime + 3600 * 2 #by this time (2hrs after open) secondaryPerc = primaryPerc / 2 #in case portfolio gain doesn't reach the primary percent time2 = openTime + int(3600 * 3.5) #by this time (3.5 hrs after open) tertiaryPerc = secondaryPerc / 2 time3 = openTime + 3600 * 4 #break even time downPerc = 1 #sell if the portfolio drops below this percent after a certain time timeDn = openTime + 3600 * 5 #currently not used - time2 is used in its place absMinPerc = 5 #biggest loss amount that we want at any point during the day wait2start = 60 * 15 #wait this long (s) after open to start trading #wait for market to settle to start trading # while(a.marketTime()[3]<(openTime+wait2start)): # print("Market is open. Trading in "+str(round((wait2start-(a.marketTime()[3]-openTime))/60,2))+" minutes.") # time.sleep(60) if (a.marketIsOpen()): cashOnHand = float(a.getAcct()["cash"]) #avaiable cash to buy with maxPrice = 1 #should be 1,2, or 5 usually symbols = a.getVolatilePennies(maxPrice, 'up') uniqueAvailable = len(symbols) num2Buy = int( uniqueAvailable * 3 / 4 ) # of unique stocks to buy - don't grab all from list, this should avoid too many repeats numShares = int(cashOnHand / maxPrice / num2Buy) # of shares of each stock to buy min2hold = min( num2Buy, 15) #minnumber to go down to before selling all and restarting waitTime = 5 #time to wait (s) between checking again perc2sellup = 12 # sell at this % gain perc2selldn = 20 # sell at this % loss while (timeTillClose() >= 60): #go until ~2 min before market closes pos = a.getPos() #get held positions if (len(pos) >= min2hold): #as long as we havee more than the minimum for e in pos: diff = float(e["current_price"]) - float( e["avg_entry_price"]) #check the gain/loss perc = diff / float( e["avg_entry_price"]) * 100 #get % change if (diff > 0 or perc <= -3 / 4 * perc2selldn ): #show the info when it gets close to failing print(e["symbol"] + " - " + str(round(perc, 2)) + "%") if ((perc >= perc2sellup or perc <= -perc2selldn )): #if it meets the criteria to sell print( a.createOrder("sell", e["qty"], e["symbol"], "market", "day")) #sell that bitch if (perc <= -perc2selldn ): #if it failed, rebuy a random stock a.buyRandom(1, symbols, numShares) else: #if we fall below minimum a.sellAll(0) #throw it all away a.buyFromTop(num2Buy, symbols, numShares) #and buy from the top again portPerc = (float(a.getAcct()["equity"]) / float(startPortVal) - 1) * 100 print("\n" + str(len(pos)) + " stocks held - Portfolio change: " + str(round(portPerc, 2)) + "% - " + str(timeTillClose()) + " seconds till close\n") if (portPerc >= primaryPerc): a.sellAll(0) print("Done trading for the day! We reached the mark.") break elif (portPerc >= secondaryPerc and int(a.marketTime()[3]) >= time1): a.sellAll(0) print("Done trading for the day! We got second best.") break elif (portPerc >= tertiaryPerc and int(a.marketTime()[3]) >= time2): a.sellAll(0) print( "Done trading for the day! We did okay, better than nothing." ) break elif (round(portPerc, 2) == 0 and int(a.marketTime()[3]) >= time3): a.sellAll(0) print("Done trading for the day! We broke even.") break elif ((portPerc <= -downPerc) and int(a.marketTime()[3]) >= timeDn): print() a.sellAll(0) print("Done trading for the day. We lost some today.") break elif (portPerc <= -absMinPerc): a.sellAll(0) print("Done trading for the day. We lost a fair amount today.") break time.sleep(waitTime) a.sellAll(0) print("Market is Closed.") '''