|
| 1 | +import csv |
| 2 | +import json |
| 3 | +import os |
| 4 | + |
| 5 | +import pandas as pd |
| 6 | +from binance.client import Client |
| 7 | + |
| 8 | +# init |
| 9 | +api_key = os.environ.get('binance_api') |
| 10 | +api_secret = os.environ.get('binance_secret') |
| 11 | + |
| 12 | +client = Client(api_key, api_secret) |
| 13 | + |
| 14 | +## main |
| 15 | + |
| 16 | +# valid intervals - 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M |
| 17 | +# get timestamp of earliest date data is available |
| 18 | +timestamp = client._get_earliest_valid_timestamp('BTCUSDT', '1d') |
| 19 | +print(timestamp) |
| 20 | + |
| 21 | +# request historical candle (or klines) data |
| 22 | +bars = client.get_historical_klines('BTCUSDT', '1d', timestamp, limit=1000) |
| 23 | +# print(bars) |
| 24 | + |
| 25 | +# option 1 - save to file using json method - this will retain Python format (list of lists) |
| 26 | +with open('btc_bars.json', 'w') as e: |
| 27 | + json.dump(bars, e) |
| 28 | + |
| 29 | +# option 2 - save as CSV file using the csv writer library |
| 30 | +with open('btc_bars.csv', 'w', newline='') as f: |
| 31 | + wr = csv.writer(f) |
| 32 | + for line in bars: |
| 33 | + wr.writerow(line) |
| 34 | + |
| 35 | +# option 3 - save as CSV file without using a library. Shorten to just date, open, high, low, close |
| 36 | +with open('btc_bars2.csv', 'w') as d: |
| 37 | + for line in bars: |
| 38 | + d.write(f'{line[0]}, {line[1]}, {line[2]}, {line[3]}, {line[4]}\n') |
| 39 | + |
| 40 | +# delete unwanted data - just keep date, open, high, low, close |
| 41 | +for line in bars: |
| 42 | + del line[5:] |
| 43 | + |
| 44 | +# option 4 - create a Pandas DataFrame and export to CSV |
| 45 | +btc_df = pd.DataFrame(bars, columns=['date', 'open', 'high', 'low', 'close']) |
| 46 | +btc_df.set_index('date', inplace=True) |
| 47 | +print(btc_df.head()) |
| 48 | +# export DataFrame to csv |
| 49 | +btc_df.to_csv('btc_bars3.csv') |
0 commit comments