Last active
May 2, 2024 21:49
-
-
Save whittlem/cf5095169e832cf1f20cc87fffaabea8 to your computer and use it in GitHub Desktop.
Trading using Python — Relative Strength Index (RSI)
This file contains hidden or 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
# data: dictionary { 'dd/mm/yyy': price, 'dd/mm/yyyy': price, ... } | |
def relativeStrengthIndex(data, num): | |
if not isinstance(data, dict): | |
raise Exception('Dictionary input expected') | |
if not isinstance(num, int): | |
raise Exception('Integer input expected') | |
if num < 7 or num > 21: | |
raise Exception('Unusual numeric input detected') | |
if (num > len(data)): | |
raise Exception('Insufficient data for calculation') | |
data_keys=list(data.keys()) | |
data_list=list(data.values()) | |
result = {} | |
last_price = -1 | |
gains_losses_list = [] | |
for x in range(len(data_list)): | |
if (last_price != -1): | |
diff = round((data_list[x] - last_price), 2) | |
if (diff > 0): | |
gains_losses = [ data_list[x], diff, 0 ] | |
elif (diff < 0): | |
gains_losses = [ data_list[x], 0, abs(diff) ] | |
else: | |
gains_losses = [ data_list[x], 0, 0 ] | |
gains_losses_list.append(gains_losses) | |
sum_gains = 0 | |
sum_losses = 0 | |
avg_gains = 0 | |
avg_losses = 0 | |
if (x == num): | |
series = gains_losses_list[-num::] | |
for y in series: | |
sum_gains += y[1] | |
sum_losses += y[2] | |
avg_gains = sum_gains / num | |
avg_losses = sum_losses / num | |
rs = avg_gains / avg_losses | |
rsi = 100 - (100 / (1 + rs)) | |
last_gain_avg = avg_gains | |
last_loss_avg = avg_losses | |
result[data_keys[x]] = round(rsi, 2) | |
if (x > num): | |
current_list = gains_losses_list[-1::] | |
current_gain = current_list[0][1] | |
current_loss = current_list[0][2] | |
current_gains_avg = (last_gain_avg * (num - 1) + current_gain) / num | |
current_losses_avg = (last_loss_avg * (num - 1) + current_loss) / num | |
rs = current_gains_avg / current_losses_avg | |
rsi = 100 - (100 / (1 + rs)) | |
last_gain_avg = current_gains_avg | |
last_loss_avg = current_losses_avg | |
result[data_keys[x]] = round(rsi, 2) | |
last_price = data_list[x] | |
return result | |
data = cbpGetHistoricRates('BTC-GBP', 86400) | |
rsi14 = relativeStrengthIndex(data, 14) | |
print (rsi14) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment