вторник, 22 мая 2018 г.

Backtrader: First Script

Backtrader: First Script
CSV Data Feed Development
Download Cryptocurrency Data with CCXT
Getting Started with the Quandl API
$ python3 ccxt_market_data.py -s BTC/USDT -e binance -t 1d
$ python3 ccxt_market_data.py -s BTC/USDT -e poloniex -t 1d
$ python3 ccxt_market_data.py -s BTC/USDT -e poloniex -t 4h

$ nano ccxt_market_data.py
##############################################################################
# Timestamp,Open,High,Low,Close,Volume
#1424361600000,0.33,0.33,225.0,225.0,0.00444444
#1424376000000,225.0,244.0,225.0,244.0,0.18867304
##############################################################################
import ccxt
from datetime import datetime, timedelta, timezone
import math
import argparse
import pandas as pd
def parse_args():
    parser = argparse.ArgumentParser(description='CCXT Market Data Downloader')
    parser.add_argument('-s','--symbol',
                        type=str,
                        required=True,
                        help='The Symbol of the Instrument/Currency Pair To Download')
    parser.add_argument('-e','--exchange',
                        type=str,
                        required=True,
                        help='The exchange to download from')
    parser.add_argument('-t','--timeframe',
                        type=str,
                        default='1d',
                        choices=['1m', '5m','15m', '30m','1h', '2h', '3h', '4h', '6h', '12h', '1d', '1M', '1y'],
                        help='The timeframe to download')
    parser.add_argument('--debug',
                            action ='store_true',
                            help=('Print Sizer Debugs'))
    return parser.parse_args()
# Get our arguments
args = parse_args()
# Get our Exchange
try:
    exchange = getattr (ccxt, args.exchange) ()
except AttributeError:
    print('-'*36,' ERROR ','-'*35)
    print('Exchange "{}" not found. Please check the exchange is supported.'.format(args.exchange))
    print('-'*80)
    quit()
# Check if fetching of OHLC Data is supported
if exchange.has["fetchOHLCV"] == False:
    print('-'*36,' ERROR ','-'*35)
    print('{} does not support fetching OHLC data. Please use another exchange'.format(args.exchange))
    print('-'*80)
    quit()
# Check requested timeframe is available. If not return a helpful error.
if args.timeframe not in exchange.timeframes:
    print('-'*36,' ERROR ','-'*35)
    print('The requested timeframe ({}) is not available from {}\n'.format(args.timeframe,args.exchange))
    print('Available timeframes are:')
    for key in exchange.timeframes.keys():
        print('  - ' + key)
    print('-'*80)
    quit()
# Check if the symbol is available on the Exchange
exchange.load_markets()
if args.symbol not in exchange.symbols:
    print('-'*36,' ERROR ','-'*35)
    print('The requested symbol ({}) is not available from {}\n'.format(args.symbol,args.exchange))
    print('Available symbols are:')
    for key in exchange.symbols:
        print('  - ' + key)
    print('-'*80)
    quit()
# Get data
data = exchange.fetch_ohlcv(args.symbol, args.timeframe)
header = ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']
df = pd.DataFrame(data, columns=header).set_index('Timestamp')
# Save it
symbol_out = args.symbol.replace("/","")
filename = '{}-{}-{}.csv'.format(args.exchange, symbol_out,args.timeframe)
df.to_csv(filename)
##############################################################################
#datetime,open,high,low,close,volume,openinterest#2018-01-01 00:00:00,13799.99999984,13799.99999984,13210.99999982,13369.40498774,985.49538388,0
#2018-01-01 04:00:00,13350.00990055,13891.99999996,13229.86326373,13621.87701406,814.86797283,0

##############################################################################
Другой вариант:
# Get data
data = exchange.fetch_ohlcv(args.symbol, args.timeframe)
#header = ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']
header = ['timestamp', 'open', 'high', 'low', 'close', 'volume']
#df = pd.DataFrame(data, columns=header).set_index('timestamp')
df = pd.DataFrame(data, columns=header)
df['timestamp']=df['timestamp']/1000
df['timestamp']=df['timestamp'].astype(int)
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s')
df['openinterest']= 0
df = df.rename(columns={'timestamp':'datetime'})
#df = df[(df['datetime'] > '2018-1-1') & (df['datetime'] <= '2018-2-1')]
df = df[(df['datetime'] >= '2018-1-1')]

# Save it
symbol_out = args.symbol.replace("/","")
#filename = '{}-{}-{}.csv'.format(args.exchange, symbol_out,args.timeframe)
filename = 'data.csv'
df.to_csv(filename)

############################################################################
Взять данные:

class OandaCSVData(bt.feeds.GenericCSVData):
    params = (
        ('nullvalue', float('NaN')),
        ('dtformat', '%Y-%m-%d %H:%M:%S'),
        #('dtformat', '%Y-%m-%dT%H:%M:%S.%fZ'),
        #('dtformat', '%Y-%m-%d'),
        ('datetime', 1),
        ('time', -1),
        ('open', 2),
        ('high', 3),
        ('low', 4),
        ('close', 5),
        ('volume', 6),
        ('openinterest', 7),
    )
#create our data list
datalist = [
    ('data.csv', 'BTCUSDT'), #[0] = Data file, [1] = Data name
]

#Loop through the list adding to cerebro.
for i in range(len(datalist)):
    data = OandaCSVData(dataname=datalist[i][0])
    cerebro.adddata(data, name=datalist[i][1])


 

Комментариев нет:

Отправить комментарий