1

Considering the price and amount of an asset which I have purchased previously, I would like to buy more now while the price is higher.

However, I want the profit percentage of this new amount I buy plus the amount I have previously bought to be greater than a defined minimum (0.5%). The profit percentage is calculated using a weighted average that is found using the price and quantity I have already purchased at, and the price and maximum quantity I can buy now.

Therefore, I need code that can calculate the maximum quantity I can buy now at the current price, and still maintain an overall profit percentage of at least 0.5%

This code works, but I need it to be faster when I set precision to anything greater than 2, and the highest I would use is 8. How can I make this code faster when I use a higher precision value?

import time

initial_buy_quantity = 643
initial_buy_price = 1.23
current_buy_price = 1.26
current_sell_price = 1.26
current_profit = (1 - (initial_buy_price / current_sell_price)) * 100
min_profit_percent = 0.5
precision = 3

print("Initial buy quantity " + str(initial_buy_quantity))
print("Initial buy price " + str(initial_buy_price))
print("Current profit %: " + str(current_sell_price))

start_time = time.time()
temp_quantity = 0
temp_profit = 0
step = 10 ** (-1 * precision)
iters = 0

while temp_profit < min_profit_percent:
    iters += 1
    temp_quantity += step
    total_quantity = initial_buy_quantity + temp_quantity 
    total_value = (initial_buy_price * initial_buy_quantity) + (current_buy_price * temp_quantity) 
    avg_price = total_value / total_quantity   
    temp_profit = (1 - (initial_buy_price / avg_price)) * 100

print("Iterations: " + str(iters))
print("Duration in seconds: " + str(time.time() - start_time))
print("Max quantity I can buy now and maintain my min profit %: " + str(temp_quantity))
print("Weighted avg price: " + str(avg_price))

print("Profit when buying new quantity: " + str(temp_profit))

Duration when precision is 3: 0.23786091804504395 seconds

Duration when precision is 6: 2.476567268371582 seconds

Dingo
  • 109
  • 8
  • The simple solution would be to multi thread your application. This might be of some use https://stackoverflow.com/questions/18828314/speed-up-python-scripts-for-loop – Madison Courto Dec 24 '18 at 05:10

1 Answers1

1

This is root-finding (the zero of temp_profit-min_profit_percent as a function of temp_quantity); there’s no reason to do it via linear search. The normal wrapper to use is scipy.optimize.brentq, although rolling your own bisection search is easy and already much faster than a linear search (at the same precision).

Davis Herring
  • 36,443
  • 4
  • 48
  • 76