while Loop summation (in python) - python

I'm creating a function (using python) to automatically buy and sell a crypto, and automatically calculate the cumulative profit after each trade was done. I also want to see the profit for each trade in a list, this is how my function looks so far:
def tradingstrat(symbol, open_position = False):
total = 0
trade = []
while True:
#pulling data all the time because of the loop
df = getminutedata(symbol)
#check whether we have an opening position
if not open_position:
buyprice = df.Close[-1]
qty = money/buyprice
print('Bought', qty,"amount of", symbol,"#",buyprice)
open_position = True
break
if open_position:
while True:
#pulling data all the time because of the loop
df = getminutedata(symbol)
sellprice = df.Close[-1]
profit = (sellprice-buyprice)*qty
print('Sell', qty,"amount of", symbol,"#",sellprice)
open_position = False
break
total += profit
trade.append(profit)
print(trade)
print("Cummulative profit:",total)
With this, somehow the profit and cumulative profit always show the same value (as if the cumulative profit value is being reset after each loop), and the profit for each trade is also not appended to the list.
I wonder where did I do wrong? thank you!

def tradingstrat(symbol, open_position = False):
total = 0
trade = []
#check whether we have an opening position
if not open_position:
df = getminutedata(symbol)
buyprice = df.Close[-1]
qty = money/buyprice
print('Bought', qty,"amount of", symbol,"#",buyprice)
else:
df = getminutedata(symbol)
sellprice = df.Close[-1]
profit = (sellprice-buyprice)*qty
print('Sell', qty,"amount of", symbol,"#",sellprice)
total += profit
trade.append(profit)
print(trade)
print("Cumulative profit:",total)
I removed your while loops as you immediately break out of them. I also moved the total += profit and trade.append(profit) inside the loops so they will be updated. Some code reformatting was done as well

Related

is it possible to recheck an index in a list in the same loop again? python

What I'm trying to do is to make the loop goes to every index in the "investments" list then checks if it's equal to "aMoney" variable or not. if the statement is True then the same index of "investments" in "revenue" list data will be added to "totalMoney" variable and goes back again to do next.
My problem is that I want the loop to go back to the False statements to recheck if it's True again and add it to the "totalMoney" variable.
what's happening here is the loop will skip index[0] because 2040 >=/ 3000. but after many loops the condition will be True if we do it again with the new number.
note: Sorting won't work because index[] in first list must go with what same index[] in the second list, no changes.
here is my full code:
numOfProjects = int(7)
aMoney = int(2040)
investments = [3000,2040,3040,5000,3340,4000,7000]
revenue = [500,1000,300,450,2010,650,1500]
totalMoney = int()
totalMoney = aMoney
for j in range(len(investments)):
if(totalMoney >= investments[j]):
totalMoney += revenue[j]
investments[j] + 1
revenue[j] + 1
totalMoney -= aMoney
print("The profit is $", totalMoney)
the output of this code will be $3960
in papers, it should be $4910
because, first round should be
"2040 + 1000 + 300 + 2010 + 650" = 6000
then we go back at what we left
"6000 + 500 + 450" = 6950
6950 - 2040 = 4910
I tried my best explaining the idea, hope it's clear
In python, we don't need to initialise int variables as int(number), just declaring them with the corresponding value suffices. So instead of aMoney = int(2040), just aMoney = 2040 works.
You can use zip to sort the investments and revenue together. Here's a simplified code which does what you need -
initialMoney, currentMoney = 2040, 2040
investments = [3000,2040,3040,5000,3340,4000,7000]
revenue = [500,1000,300,450,2010,650,1500]
data = sorted(zip(investments, revenue))
print(data)
for investment, revenue in data:
if investment <= currentMoney:
currentMoney += revenue
netProfit = currentMoney - initialMoney
print("The profit is $", netProfit)
Output:
[(2040, 1000), (3000, 500), (3040, 300), (3340, 2010), (4000, 650), (5000, 450), (7000, 1500)]
The profit is $ 4910
What you see printed just before profit, is the (investment, revenue) sorted by investment.

python for loop only updates 2 of 3 variables?

I want to use 3 variables in one for loops.
This is what I tried:
def loop_player_listbox():
global bol_loop, count
bol_loop = True
while True:
time.sleep(1)
str_libo_p = listbox.get(0,tk.END)
str_libo_r = listboxr.get(0,tk.END)
str_libo_price = listboxprice.get(0,tk.END)
for i,r,p in itertools.product(str_libo_p, str_libo_r, str_libo_price):
text_playername = wait.until(EC.element_to_be_clickable((By.XPATH,('/html/body/main/section/section/div[2]/div/div[2]/div/div[1]/div[1]/div[1]/div/input'))))
text_playername.click()
time.sleep(1)
text_playername.clear()
time.sleep(1)
text_playername.click()
text_playername.send_keys(i)
user_input_max_price = p
try:
choose_player = wait.until(EC.element_to_be_clickable((By.XPATH,("//span[#class='btn-text' and contains(text(),'"+i+"')]")))) and wait.until(EC.element_to_be_clickable((By.XPATH,("//span[#class='btn-subtext' and contains(text(),'"+r+"')]"))))
choose_player.click()
count = 0
while count < 5:
while True:
# some unimportant code
# set speed
# some unimportant code
# set max BIN price
while True:
#user_input_max_price = input('Enter max buy now price (>250):')
user_input_max_price = p
if user_input_max_price.isdigit():
int_user_input_max_price = int(user_input_max_price)
if int_user_input_max_price > 250:
break
else:
print('Max buy now price must be >250')
continue
else:
continue
# set max price
# some unimportant code
# Buy until 100 players were bought
while count < 5:
# some unimportant code
count +=1
The problem is, variable r and p do update after count = 5.
But i is always only showing the first item from my listbox and does not update. Every time my loop is coming back to the line for i,r,p ... I see in debug that only the variables r and p updated.
I have no idea why. While searching for how to combine more than one forloops I found itertoolsand so I used it.
Maybe anyone sees whast wrong?
Changed from itertools to zip fixed the issue.
for i,r,p in zip(str_libo_p, str_libo_r, str_libo_price):

How can I improve the time complexity of this algorithm for finding the max stock price?

I am currently passing the sample tests and 2 of the other 10 cases so 4 out of 12. However, I don't make it through all of the data. I am getting a Terminated due to timeout error which means that my solution isn't fast enough.
def stockmax(prices):
total = 0
for index, price in enumerate(prices):
if index < len(prices) - 1:
section = max(prices[index+1:])
if prices[index] < section:
total += section - prices[index]
return total
I tried to do everything in only one loop. But how exactly can speed this type of question up. I also tried to cut some lines of the code but it is equally as inefficient.
def stockmax(prices):
total = 0
for index, price in enumerate(prices):
if index < len(prices) - 1 and prices[index] < max(prices[index+1:]):
total += max(prices[index+1:]) - prices[index]
return total
Though it passes the same amount of test cases.
I also tried to use heapq but it passes the same test cases and fails due to time.
def stockmax(prices):
total = 0
for index, price in enumerate(prices):
if index < len(prices) - 1:
section = heapq.nlargest(1,prices[index+1:])[0]
if prices[index] < section:
total += section - prices[index]
return total
https://www.hackerrank.com/challenges/stockmax/topics/dynamic-programming-basics
for details on the problem.
https://hr-testcases-us-east-1.s3.amazonaws.com/330/input09.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1538902058&Signature=3%2FnfZzPO8XKRNyGG0Yu9qJIptgk%3D&response-content-type=text%2Fplain
for a link of some test cases but will expire after a while.
Problem
Your algorithms have become so good at predicting the market that you now know what the share price of Wooden Orange Toothpicks Inc. (WOT) will be for the next number of days.
Each day, you can either buy one share of WOT, sell any number of shares of WOT that you own, or not make any transaction at all. What is the maximum profit you can obtain with an optimum trading strategy?
For example, if you know that prices for the next two days are prices = [1,2], you should buy one share day one, and sell it day two for a profit of 1. If they are instead prices = [2,1], no profit can be made so you don't buy or sell stock those days.
Function Description
Complete the stockmax function in the editor below. It must return an integer that represents the maximum profit achievable.
stockmax has the following parameter(s):
prices: an array of integers that represent predicted daily stock prices
Input Format
The first line contains the number of test cases t.
Each of the next t pairs of lines contain:
The first line contains an integer n, the number of predicted prices for WOT.
The next line contains n space-separated integers prices [i], each a predicted stock price for day i.
Constraints
1 <= t <= 10
1 <= n <= 50000
1 <= prices [i] <= 100000
Output Format
Output lines, each containing the maximum profit which can be obtained for the corresponding test case.
Sample Input
3
3
5 3 2
3
1 2 100
4
1 3 1 2
Sample Output
0
197
3
Explanation
For the first case, you cannot obtain any profit because the share price never rises.
For the second case, you can buy one share on the first two days and sell both of them on the third day.
For the third case, you can buy one share on day 1, sell one on day 2, buy one share on day 3, and sell one share on day 4.
Clearly, for any price we can buy, we would want to sell it at the highest price. Fortunately, we are given that highest price. So, iterating backwards, we know the highest future price seen at any point we visit in our travel "back in time."
Python code:
def stockmax(prices):
n = len(prices)
highest = prices[n - 1]
m = [0] * n
# Travel back in time,
# deciding whether to buy or not
for i in xrange(n - 2, -1, -1):
# The most profit buying stock at this point
# is what we may have made the next day
# (which is stored in m[i + 1])
# and what we could make if we bought today
m[i] = m[i + 1] + max(
# buy
highest - prices[i],
# don't buy
0
)
# Update the highest "future price"
highest = max(highest, prices[i])
return m[0]
If you can use Numpy, then something similar to the below should be rather quick (I believe it's the same idea as the answer from #גלעד ברקן).
import numpy as np
with open('.../input09.txt') as fd:
numtests = int(fd.readline().strip())
counter = 0
numvals = 0
vals = None
steps = None
for line in fd:
if (counter % 2 == 0) :
numvals = int(line.strip())
else:
vals = np.fromstring(line, dtype=int, sep=' ', count=numvals)
assert len(vals) == numvals
cum_max = np.maximum.accumulate(vals[::-1])
np.roll(cum_max, -1)
cum_max[len(cum_max) - 1] = 0
delta = (cum_max - vals)
print('#', counter + 1, 'sum:', np.sum(delta * (delta > 0)))
counter += 1
it runs almost instantly on tests from the input09.txt.
Here is my solution written in ruby.
The solution obtained perfect score.
def solution(a)
gain = 0
i = a.count - 1
min = false
mi = false
while i > 0
s = a.delete_at(i)
unless min
mi = a.index(a.min)
min = a[mi]
end
g = s - min
gain = g if g > gain
i -= 1
min = false if i == mi
end
gain
end

why wont this program terminate?

I am trying to teach myself python and have no experience write code. For my first attempt I am trying to write a program that applies the snowball principle to debt reduction, but also adds in an extra set amount each payment. I can get the first debt to clear(it goes to a negative but it exits the loop). My second step wont exit the loop and I have looked at topics that dealt with nested loops but they did not help. Could someone please show me where I went wrong?
#Temp fixed number for testing use rawinput for actual program.
#name the debt
debt1 = "CC A"
#currnet balnace
balance1 = float(5000)
#APR
annualInterestRate1 = float(.1499)
#Currnet Monthly Payment
minMonthlyPayment1 = float(200)
# Exta Payment
boosterPayment = float(337)
print "The balance on ",debt1," is ",balance1
debt2 = "CC B"
balance2 = float(1000)
annualInterestRate2 = float(.1499)
minMonthlyPayment2 = float(200)
print "The balance on ",debt2," is ",balance2
debt3 = "ICCU"
balance3 = float(6000)
annualInterestRate3 = float(.0879)
minMonthlyPayment3 = float(130)
print "The balance on ",debt3," is ",balance3
debt4 = "Car"
balance4 = float(8000)
annualInterestRate4 = float(.0699)
minMonthlyPayment4 = float(200)
print "The balance on ",debt4," is ",balance4
debt5 = "Truck"
balance5 = float(15000)
annualInterestRate5 = float(.0439)
minMonthlyPayment5 = float(333)
#nubmer of payments made durning the debt reduction. Used as the index.
numPay = 0
save = 0
#For Debt1 with an APR greater then 0
intPayment1 = round(balance1*(annualInterestRate1/12),2)
while balance1 >= 0:
#payment with intrest
payment1 = minMonthlyPayment1 - intPayment1 + boosterPayment
#subtact payment from balance
balance1 -= payment1
#count Number of payments
numPay += 1
print numPay
print balance1
#For Debt2 with an APR greater then 0
#Figures monthly charge based on given APR
intPayment2 = round(balance2*(annualInterestRate2/12),2)
#Monthly payment minus intrest
standPay2 = minMonthlyPayment2 - intPayment2
while balance2 >= 0:
#payment while debt1 is being paid
#need a way to pay the payments while the other debt is being figured
backPay = numPay
while backPay >= 0:
balance2 -= standPay2
backPay += 1
#payment with intrest takes 100 away for savings
payment2 = minMonthlyPayment2 - intPayment2 + (boosterPayment-100)
#subtact payment from balance
balance2 -= payment2
#count Number of payments
numPay += 1
#keep track of how much is going to savings
save += 100
print numPay
print balance1
print save
Take a look at this loop:
while backPay >= 0:
balance2 -= standPay2
backPay += 1
Here, backPay in increased in each iteration, so the condition backPay >= 0 will always be true.
Not sure what the code is intended to do, but probably you have to do backPay -= 1 instead. However, note that since the number of iterations of the loop is known beforehand, and you are just adding a fixed number in each iteration, you could just as well replace the loop with a simple multiplication.

When calling an array only the first element is used?

When calling QuarterlySales into the DetermineRate procedure it only uses the first number in the array every time the loop goes around. I think I have it indexed properly. Also it only prints out 9 numbers when it should print out 10.
def FillQuarterlySales(QuarterlySales):
#declare local variables
Index = 0
QuarterlySales = [0] * 10
#Loading the array
QuarterlySales = [21487, 22450, 7814, 12458, 4325, 9247, 18125, 5878, 16875, 10985]
#Determine the quarterly sales based on the index
return QuarterlySales
def DetermineRate(QuarterlySales):
#declare local variables
Rate = float()
Index = 0
Counter = 0
Rates = [Index] * 9
for Index in range (9):
if QuarterlySales[Counter] < 5000:
Rate = 0
elif QuarterlySales[Counter] < 10000:
Rate = 0.04
elif QuarterlySales[Counter] < 15000:
Rate = 0.08
elif QuarterlySales[Counter] < 20000:
Rate = 0.12
else:
Rate = 0.15
#end if
Rates[Index] = Rate
#end for
return Rates
There is no error code but when I print out rates to make sure they are correct the array is filled with the same number. This is happening anywhere I call QuarterlySales throughout the program as well.
It's because you use Counter to index QuarterlySales instead of Index.
But your question shows some inexperience with python, so let's try to address some other issues, too.
Rates = [Index] * 9
...
QuarterlySales = [0] * 10
This looks like you're trying to do allocation in advance, which is almost always unnecessary in python. Certainly for lists of only ten elements, it hurts more than it helps.
Instead do this:
Rates = []
...
QuarterlySales = []
and then just use the .append() method to add sequential data elements to the list.
For example:
def DetermineRate(QuarterlySales):
Rates = []
for sales in QuarterlySales:
if sales < 5000:
Rates.append(0.)
elif sales < 10000:
Rates.append(0.04)
elif sales < 15000:
Rates.append(0.08)
elif sales < 20000:
Rates.append(0.12)
else:
Rates.append(0.15)
return Rates

Categories

Resources