def simulate(start, now): p = generateHistoricalData(start, now.strftime('%Y-%m-%d')) # commandCenter = LongtermStrategy(p) commandCenter = ShortTermStrategy(p) while now < datetime.datetime(2019, 4, 1): next = now + datetime.timedelta(days=1) data = ts.get_hist_data('cyb', start=now.strftime('%Y-%m-%d'), end=next.strftime('%Y-%m-%d'), ktype="5")[::-1] for row in data.iterrows(): open = float(row[1]['open']) close = float(row[1]['close']) high = float(row[1]['high']) low = float(row[1]['low']) date = row[0].split(' ')[0] currentPrice = Price(high, low, open, close, date) decision = commandCenter.do(currentPrice) if decision.Type == 'Quit with benefit' or decision.Type == 'First Position' \ or decision.Type == "Stop with loss" or decision.Type == 'Follow Buying': logging.info(decision) logging.info(row) now = next return commandCenter.account
def simulate(start, now): p = generateHistoricalData(start, now) # commandCenter = LongtermStrategy(p) commandCenter = ShortTermStrategy(p) with open('resource/BTCUSD_1h.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) cursor = 0 for row in reader: date = row['Date'].split(' ')[0] if date < now: continue h = float(row['High']) l = float(row['Low']) o = float(row['Open']) c = float(row['Close']) currentPrice = Price(h, l, o, c) decision = commandCenter.do(currentPrice, cursor % 24) if decision.Type == 'Quit with benefit' or decision.Type == 'First Position' \ or decision.Type == "Stop with loss" or decision.Type == 'Follow Buying': logging.info(decision) logging.info(row) cursor += 1 return commandCenter.account
def generateHistoricalData(startDate, endDate): data = ts.get_hist_data('cyb', start=startDate, end=endDate, ktype="D") dailyPrices = [] for row in data.iterrows(): open = float(row[1]['open']) close = float(row[1]['close']) high = float(row[1]['high']) low = float(row[1]['low']) date = row[0] dailyPrices.insert(0, Price(high, low, open, close, date)) return dailyPrices
def dayPriceFromHourPrice(self, hours): h = 0 l = sys.maxsize o = 0 c = hours[-1].close for hour in hours: if o == 0: o = hour.open if h < hour.high: h = hour.high if l > hour.low: l = hour.low return Price(h, l, o, c, hours[0].date)
def retrieveLastHourData(self): URL = 'https://www.bitstamp.net/api/ticker_hour/' try: r = requests.get(URL) raw_body = json.loads(r.text) open = float(raw_body['open']) close = float(raw_body['last']) high = float(raw_body['high']) low = float(raw_body['low']) date = datetime.datetime.utcfromtimestamp( int(raw_body['timestamp'])).strftime('%Y-%m-%d') return Price(high, low, open, close, date) except requests.ConnectionError: print("Error querying Bitstamp API") return None
def retrieveHistoricalData(self, from_date, to_date=None, coin='bitcoin'): """Retrieve basic historical information for a specific cryptocurrency from coinmarketcap.com Parameters ---------- from_date : the starting date (as string) for the returned data; required format is %Y-%m-%d (e.g. "2017-06-21") to_date : the end date (as string) for the returned data; required format is %Y-%m-%d (e.g. "2017-06-21") Optional. If unspecified, it will default to the current day coin : the name of the cryptocurrency (e.g. 'bitcoin', 'ethereum', 'dentacoin') Returns ------- pandas Dataframe """ if to_date is None: to_date = datetime.date.today().strftime("%Y-%m-%d") try: output = pd.read_html( "https://coinmarketcap.com/currencies/{}/historical-data/?start={}&end={}" .format(coin, from_date.replace("-", ""), to_date.replace("-", "")))[0] except: # future versions may split out the different exceptions (e.g. timeout) raise output = output.assign(Date=pd.to_datetime(output['Date'])) for col in output.columns: if output[col].dtype == np.dtype('O'): output.loc[output[col] == "-", col] = 0 output[col] = output[col].astype('int64') output.columns = [ re.sub(r"[^a-z]", "", col.lower()) for col in output.columns ] result = [] for row in output.iterrows(): open = float(row[1]['open']) close = float(row[1]['close']) high = float(row[1]['high']) low = float(row[1]['low']) date = row[1]['date'].strftime('%Y-%m-%d') result.insert(0, Price(high, low, open, close, date)) return result
def generateHistoricalData(startDate, endDate): dailyPrices = [] with open('resource/BTC-USD.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: if row['Date'] < startDate: continue if row['Date'] >= endDate: break h = float(row['High']) l = float(row['Low']) o = float(row['Open']) c = float(row['Close']) p = Price(h, l, o, c) dailyPrices.append(p) return dailyPrices