所以我在AmazonEC2(t2.micro(实例上运行了这个python脚本,我注意到性能非常差,我想这可能是因为我在其中进行的I/O,但它"非常差"。随着时间的推移,完成轮询PriceForTickerSymbol FUNCTION需要越来越长的时间;readData FUNCTION;平均DoIt函数;让我们看看我们是如何完成功能的。
我试着插入打印语句,看看发生了什么,当我检查CPU使用率时,它是99%。我有更好的方法来做这个代码吗?和/或指出我在这里做错了什么。
from datetime import datetime
import smtplib
import time
import imaplib
import email
import time
import robin_stocks as r
import shutil
from datetime import timedelta
# -------------------------------------------------
#
#
# ------------------------------------------------
running = False
counter = 0
currOpen = 0.00
currHigh = 0.00
currLow = 0.00
currClose = 0.00
#shorterVal = 5 # for daily data seems to work fine
#longerVal = 10 # for daily data seems to work fine
shorterVal = 10
longerVal = 20
shorterAvg = []
longerAvg = []
dohlcACv = []
cursor = -1
inPosition = False
boughtPrice = 0.00
soldPrice = 0.00
profit = 0.00
alreadyExperiencedDeathCross = False
numOfLosses = 0
numOfWins = 0
tickerSymb = "aapl"
# -----------------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------
def getLoggedIntoRH():
try:
#
#
login = r.login("jimom","2") ###############
#
except Exception as e:
print(str(e))
# -----------------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------
def pollingPriceForTickerSymbol(i):
try:
#
global tickerSymb
#
resp2 = r.stocks.get_stock_historicals(tickerSymb,"5minute", "week")
#
f = open("4reel.txt", "w")
for x in range(len(resp2)):
tempString = ""
for key in resp2[x]:
if "begins" in key:
tempString2 = str(resp2[x][key]) + ","
if "open" in key:
tempString3 = str(resp2[x][key]) + ","
if "high" in key:
tempString4 = str(resp2[x][key]) + ","
if "low" in key:
tempString5 = str(resp2[x][key]) + ","
if "close" in key:
tempString6 = str(resp2[x][key]) + "," + str(resp2[x][key]) + ","
if "volume" in key:
tempString7 = str(resp2[x][key]) + "n"
tempString = tempString2 + tempString3 + tempString4 + tempString5 + tempString6 + tempString7
f.write(tempString)
#print(key, '->', resp2[x][key])
f.close()
#
return resp2
#
except Exception as e:
print(str(e))
# -----------------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
# -----------------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------
def readData():
#
try:
file1 = open('4reel.txt', 'r')
Lines = file1.readlines()
for line in Lines:
dohlcACv.append(line.strip())
#
except Exception as e:
print(str(e))
# -----------------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------
def averagesDoIt():
#
try:
#
for x in range(len(dohlcACv)):
if x < longerVal:
longerAvg.append(0.00)
else:
sum = 0.00
for y in range(x):
temp = dohlcACv[y].split(",")
#print(temp[0])
#print(temp[1])
#print(temp[2])
#print(temp[4])
if y in range(x-longerVal, x):
sum = round(sum + round(float(temp[4]), 2), 2)
add = round(sum / longerVal, 2)
longerAvg.append(add)
#
#
#
for x in range(len(dohlcACv)):
if x < shorterVal:
shorterAvg.append(0.00)
else:
sum = 0.00
for y in range(x):
temp = dohlcACv[y].split(",")
#print(temp[0])
#print(temp[1])
#print(temp[2])
#print(temp[4])
if y in range(x-shorterVal, x):
sum = round(sum + round(float(temp[4]), 2), 2)
add = round(sum / shorterVal, 2)
shorterAvg.append(add)
#
except Exception as e:
print(str(e))
# -----------------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------
def isThereACrossOver():
#
try:
for z in range(len(dohlcACv)):
if shorterAvg[z] == 0.00 or longerAvg[z] == 0.00:
pass
else:
if shorterAvg[z] > longerAvg[z]:
print("golden crossover matey")
#
except Exception as e:
print(str(e))
# -----------------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------
def letsSeeHowWeDid(z):
#
try:
global inPosition, profit, alreadyExperiencedDeathCross, numOfLosses, numOfWins, boughtPrice, soldPrice
#
if shorterAvg[z] == 0.00 or longerAvg[z] == 0.00:
pass
else:
if inPosition:
#temp = dohlcACv[z].split(",")
#currPrice = round(float(temp[1]), 2)
currPrice = r.stocks.get_latest_price(tickerSymb, "bid_price", True)
currPrice = round(float(currPrice[0]), 2)
if currPrice > ((boughtPrice * 0.015) + boughtPrice):
inPosition = False
numOfWins = numOfWins + 1
soldPrice = currPrice
print("sold @ " + str(soldPrice) + " " + str(datetime.now()))
#print("z = " + str(z))
profit = profit + (soldPrice - boughtPrice)
elif currPrice < (boughtPrice - (boughtPrice * 0.010)):
inPosition = False
numOfLosses = numOfLosses + 1
soldPrice = currPrice
print("sold @ " + str(soldPrice) + " " + str(datetime.now()))
#print("z = " + str(z))
profit = profit + (soldPrice - boughtPrice)
else:
pass
if shorterAvg[z] > longerAvg[z] and not inPosition and alreadyExperiencedDeathCross:
#print("golden crossover matey")
inPosition = True
alreadyExperiencedDeathCross = False
#temp = dohlcACv[z].split(",")
#boughtPrice = round(float(temp[1]), 2)
boughtPrice = r.stocks.get_latest_price(tickerSymb, "ask_price", True)
boughtPrice = round(float(boughtPrice[0]), 2)
print("buy @ " + str(boughtPrice) + " " + str(datetime.now()))
#print("z = " + str(z))
if shorterAvg[z] < longerAvg[z]:
#print("golden crossover matey")
alreadyExperiencedDeathCross = True
#
except Exception as e:
print(str(e))
# -----------------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------
while True:
if not running:
getLoggedIntoRH()
running = True
#
else:
time.sleep(1.0)
counter = counter + 1
if counter == 5:
pollingPriceForTickerSymbol("ssss")
#
readData()
#
averagesDoIt()
#
letsSeeHowWeDid(len(dohlcACv) - 1)
#
counter = 0
try:
f2 = open("status.txt", "w")
f2.write("n")
f2.write("n")
f2.write("PnL = " + str(profit))
f2.write("n")
f2.write("n")
f2.write("number of wins = " + str(numOfWins))
f2.write("n")
f2.write("number of losses = " + str(numOfLosses))
f2.write("n")
f2.write("total number of trades = " + str(numOfLosses + numOfWins))
f2.write("n")
f2.write("n")
if (numOfLosses + numOfWins) == 0:
f2.write("Wins percentage = N/A ")
f2.write("n")
f2.write("n")
else:
f2.write("Wins percentage = " + str(numOfWins / (numOfLosses + numOfWins)))
f2.write("n")
f2.write("n")
if inPosition:
f2.write("We are currently in a position")
else:
f2.write("no open positions")
f2.write("n")
f2.close()
except Exception as e:
print(str(e))
问题是我忘记清除变量列表dohlcACv
,因为它的大小越来越大;所以使用
clear()
我名单上的帮助我解决了这个问题。