I have this pandas code, but it's very slow. How could i optimize it? Meaning that when i run it, it takes around 4 seconds to do so. This code i call down here is what i call over and over as and it should be as fast as possible that it currently isn't... anyone got an idea?
self.dataframe = pd.DataFrame(columns=list(['O' ,'H' ,'L' ,'C' ,'RSI', 'Upper Band', 'Lower Band']))
BinanceHistoricalUrl = "https://api.binance.com/api/v1/klines?"
BinanceHistoricalPayload = {'symbol' : 'BTCUSDT','interval': '1m','limit': 100}
HistoricalRequestData = requests.get(url=BinanceHistoricalUrl, params=BinanceHistoricalPayload).json()
Lenght = len(HistoricalRequestData)
for i in range(Lenght):
O = HistoricalRequestData[i][1]
O = "{:.4f}".format(O)
O = float(O)
H = HistoricalRequestData[i][2]
H = "{:.4f}".format(H)
H = float(H)
L = HistoricalRequestData[i][3]
L = "{:.4f}".format(H)
L = float(L)
C = HistoricalRequestData[i][4]
C = "{:.4f}".format(C)
C = float(C)
# Volume = HistoricalRequestData[0]["priceData"][i]['volume']
# Volume = "{:.4f}".format(Volume)
# Volume = float(Volume)
self.dataframe = self.dataframe.append({'O': O, 'H' : H, 'L' : L, 'C' : C}, ignore_index=True)
make_RSI(self.dataframe)
make_bollinger_bands(self.dataframe)
RSI = self.dataframe['RSI'][99]
RSI = float(RSI)
UppBoll = self.dataframe['Upper Band'][99]
UndBoll = self.dataframe['Lower Band'][99]
previouscloseprice = self.dataframe['C'][99]
MA = self.dataframe['20 Day MA'][99]
DistanceUppBoll = UppBoll - MA
DistanceUppBoll = float(DistanceUppBoll)
DistanceUndBoll = UndBoll - MA
DistanceUndBoll = float(DistanceUndBoll)
self.dataframe = self.dataframe.iloc[0:0]
def make_RSI(dataframe):
delta = dataframe['C'].diff()
dUp, dDown = delta.copy(), delta.copy()
dUp[dUp < 0] = 0
dDown[dDown > 0] = 0
RolUp = dUp.rolling(14).mean()
RolDown = dDown.rolling(14).mean().abs()
RS = RolUp / RolDown
dataframe['RSI'] = 100 - (100/(1+RS))
def make_bollinger_bands(dataframe):
dataframe['20 Day MA'] = dataframe['C'].rolling(window=20).mean()
dataframe['20 Day STD'] = dataframe['C'].rolling(window=20).std()
dataframe['Upper Band'] = dataframe['20 Day MA'] + (dataframe['20 Day STD'] * 2)
dataframe['Lower Band'] = dataframe['20 Day MA'] - (dataframe['20 Day STD'] * 2)
Your code is not really reproducible. Let's do some order
# first import libraries
import pandas as pd
import requests
#define functions
def make_RSI(dataframe):
delta = dataframe['C'].diff()
dUp, dDown = delta.copy(), delta.copy()
dUp[dUp < 0] = 0
dDown[dDown > 0] = 0
RolUp = dUp.rolling(14).mean()
RolDown = dDown.rolling(14).mean().abs()
RS = RolUp / RolDown
dataframe['RSI'] = 100 - (100/(1+RS))
def make_bollinger_bands(dataframe):
dataframe['20 Day MA'] = dataframe['C'].rolling(window=20).mean()
dataframe['20 Day STD'] = dataframe['C'].rolling(window=20).std()
dataframe['Upper Band'] = dataframe['20 Day MA'] + (dataframe['20 Day STD'] * 2)
dataframe['Lower Band'] = dataframe['20 Day MA'] - (dataframe['20 Day STD'] * 2)
#############
# your code #
############
BinanceHistoricalUrl = "https://api.binance.com/api/v1/klines?"
BinanceHistoricalPayload = {'symbol' : 'BTCUSDT','interval': '1m','limit': 100}
#get data
HistoricalRequestData = requests.get(url=BinanceHistoricalUrl,
params=BinanceHistoricalPayload)\
.json()
# put on a dataframe
dataframe = pd.DataFrame(HistoricalRequestData)
# consider only columns from 1 to 4(included)
dataframe = dataframe[dataframe.columns[1:5]]
# assign column names
dataframe.columns = ["O", "H", "L", "C"]
# set type float
dataframe = dataframe.astype("float64")
# call functions
make_RSI(dataframe)
make_bollinger_bands(dataframe)
It's not quite clear what do you want to achieve at the end, but you are just using the last row of your dataframe
so you might consider to
last = dataframe.iloc[-1]
DistanceUppBoll = last["Upper Band"] - last["20 Day MA"]
DistanceUndBoll = last["Lower Band"] - last["20 Day MA"]
This took 717 ms
on my laptop. I guess that mostly depends on the speed of your connection.
NOTE: The main point here is that you should avoid loops if possible.
Update: If you are trying to implement a trading strategy based on basic technical analysis you should have a look at how to calculate MA
in streaming.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.