Skip to content
This repository has been archived by the owner on Oct 27, 2023. It is now read-only.

Added function for getting moving averages from klines #5

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ Quick Start

# fetch weekly klines since it listed
klines = client.get_historical_klines("NEOBTC", Client.KLINE_INTERVAL_1WEEK, "1 Jan, 2017")

# fetch moving average based on given kline and period
five_day_moving_average = client.get_moving_average(klines, 5)


For more `check out the documentation <https://python-binance.readthedocs.io/en/latest/>`_.

Expand Down
58 changes: 58 additions & 0 deletions binance/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -793,6 +793,64 @@ def get_historical_klines(self, symbol, interval, start_str, end_str=None):

return output_data

def get_moving_average(self, klines, period):
"""
Get the average values of historical kline data

:param klines: List of OHLCV values given from get_historical_kline
:type klines: list
:param period: Moving average period
:type period: int

:return: list of average OHLCV values based on period


"""
# Transpose historical kline data
data = [list(i) for i in zip(*klines)]

# Number of values for each timestamp
slots = len(klines[0])

# init our list
moving_avg = []

idx = 0
# iterate through every day in kline
while idx < len(klines):

# init each row
row = []

# add timestamp to row
row.append(data[0][idx])

# iterate through all values
for k in range(1, slots):

# add closing time to row
if k == 6:
val = data[k][idx]

# add "n/a" if we can't calculate average over period yet
elif idx < period:
val = "n/a"

# add average over period
else:
val = 0
for i in data[k][idx - period:idx]:
val = val + float(i)
val = str(round(val / period, 8))
row.append(val)

idx += 1

# add row to moving average list
moving_avg.append(row)

return moving_avg

def get_ticker(self, **params):
"""24 hour price change statistics.

Expand Down