-
-
Save anthonymorast/85e68090cae53b2923d9def907c7d1a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def calculate_profits(trades, ticker, base_dir): | |
# iterate buy/sell lists | |
sell_idx = 0 | |
buy_idx = 0 | |
avg_price = 0 | |
total_profit = 0 | |
ret = 0 | |
buy_count = 0 | |
trade_count = 0 | |
with open(base_dir + "trades/{}.trades".format(ticker.upper()), 'w') as f: | |
while buy_idx < len(trades["buy_indices"]): | |
# get average price of all buys before a sell | |
avg_price += trades["buy_prices"][buy_idx] | |
buy_count += 1 # in case we buy more than once before a sell | |
# is the next sell before the next buy? what's our next trade | |
if (buy_idx + 1) < (len(trades["buy_indices"])) and \ | |
sell_idx < (len(trades["sell_indices"])) and \ | |
trades["sell_indices"][sell_idx] < trades["buy_indices"][buy_idx + 1]: | |
# sell all shares at sell point | |
price = avg_price / buy_count | |
profit = (trades["sell_prices"][sell_idx] - price) * buy_count | |
ret += profit / price # % return | |
total_profit += profit | |
trade_count += 1 | |
f.write("Selling {} shares at {} with an avg price of {} for a return of {} and profit of {}. (indicies buy/sell: {}/{})".format( | |
buy_count, trades["sell_prices"][sell_idx], price, profit/price, profit, trades["buy_indices"][buy_idx], trades["sell_indices"][sell_idx])) | |
f.write("\n") | |
# reset variables | |
buy_count = 0 | |
avg_price = 0 | |
sell_idx += 1 | |
buy_idx += 1 | |
if sell_idx < len(trades["sell_indices"]) and buy_count > 0: | |
# sell any remaining shares | |
price = avg_price / buy_count | |
profit = (trades["sell_prices"][sell_idx] - price) * buy_count | |
ret += profit / price # % return | |
total_profit += profit | |
trade_count += 1 | |
f.write("Selling {} shares at {} with an avg price of {} for a return of {} and profit of {}. (indicies buy/sell: {}/{})".format( | |
buy_count, trades["sell_prices"][sell_idx], price, profit/price, profit, trades["buy_indices"][buy_idx-1], trades["sell_indices"][sell_idx])) | |
f.write("\n") | |
if trade_count > 0: | |
ret /= trade_count | |
return ret, total_profit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment