def test_price_minute(self): coin = 'BTC' curr = 'USD' price = cryptocompare.get_historical_price_minute( coin, currency=curr, limit=3, exchange='CCCAGG', toTs=datetime.datetime.now()) for frame in price: self.assertIn('time', frame)
def test_get_historical_price_minute_custom_limit(self): res = cryptocompare.get_historical_price_minute(coins[2], limit=90) self.assertTrue('Data' in res.keys(), "expected 'Data'") # XXX: cryptocompare is off-by-one self.assertEqual( 91, len(res['Data']), "expected limit to match days returned, got {}".format( len(res['Data'])))
def test_get_historical_price_minute_non_default_currency(self): res = cryptocompare.get_historical_price_minute(coins[1], currency='USD', limit=10) self.assertTrue('Data' in res.keys(), "expected 'Data'") # XXX: cryptocompare is off-by-one self.assertEqual( 11, len(res['Data']), "expected limit to match days returned, got {}".format( len(res['Data'])))
def get_history(ticker, port): socks.set_default_proxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', port) socket.socket = socks.socksocket day_30 = cryptocompare.get_historical_price_day(ticker, curr='USD', limit=30) day_3 = cryptocompare.get_historical_price_hour(ticker, curr='USD', limit=3 * 24) hour_1 = cryptocompare.get_historical_price_minute(ticker, curr='USD', limit=60) for o, file_name in [(day_30, f"data/{ticker}_30.json"), (day_3, f"data/{ticker}_3.json"), (hour_1, f"data/{ticker}_1.json")]: if o is not None: with open(file_name, 'w') as f: json.dump(o, f) time.sleep(1.5)
def get_historical(self, coin, time_step, nod, end=datetime.now(), columns=['close'], currency="USD", add_this_moment_price=False): """ :param: coin: It should be symbol. e.x 'BTC' :param: time_step: It can be 'day' for price history in last days, 'hour' for ... and 'min' for ... :param: nod: Number of dates. Actually number of rows in returned dataframe(Except when add_this_moment_price is True) :param: end: Default is today date. But can pass a date to recive data from nod days before end to end day :param: columns: A list of columns from ['high', 'low', 'open', 'volumefrom', 'volumeto', 'close']. And if it is 'OHLC', columns will be consideres as ['open', 'high', 'low', 'close']. :param: add_this_moment_price: Only works when columns=['close']. Adds this moment's price to dataframe. :param: currency: currency unit :returns: A dataframe with index of time laps and columns passed """ if columns == "OHLC": #Famous open, high, low, close dataframe for candle bars columns = ['open', 'high', 'low', 'close'] if columns == "OHLCV": columns = ['open', 'high', 'low', 'close', 'volumeto'] if time_step == "day": data = cc.get_historical_price_day(coin, currency, limit=nod, toTs=end) elif time_step == "hour": data = cc.get_historical_price_hour(coin, currency, limit=nod, toTs=end) elif time_step == "min": data = cc.get_historical_price_minute(coin, currency, limit=nod, toTs=end) else: raise ValueError( "Only 'day', 'hour' and 'min' are valid as time_stamp") df = pd.DataFrame.from_dict( data) #converting json like recived data to a pandas df index = [datetime.fromtimestamp(tstamp) for tstamp in df.time] dates = [t + timedelta(seconds=510 * 60 - 21) for t in index] # Converting timelaps to Tehran time zone df.index = dates if add_this_moment_price: if columns == ['close'] and time_step == "min": #Adding this moment's price to tail price = cc.get_price(coin, currency)[coin][currency] t = datetime.now() now_df = pd.DataFrame({"close": price}, index=[t]) df = df.append(now_df) else: raise ValueError( "add_this_moment_price will only work when dataframe is a price table and time_step is 'min'" ) return df[columns]
def main(): analyzer = SentimentIntensityAnalyzer() tweets = [] #Stores the tweets dates = [] #Stores the dates of the tweets arr_compound = [] # Stores the compund of the sentiment Analysis. arr_positive = [] #Stores the positives of the sentiment Analysis. arr_neutral = [] #Stores de neutral values of the sentiment Analysis. arr_negative = [] #Store the negative values of the Sentiment Analysis. #Getting the crypto information crypto_data = cryptocompare.get_historical_price_minute('BTC', curr='EUR', limit=1) date = datetime.datetime.fromtimestamp( crypto_data[0]['time']).strftime('%d-%m-%Y %H:%M:%S') open_price = crypto_data[0]['open'] close_price = crypto_data[0]['close'] high = crypto_data[0]['high'] low = crypto_data[0]['low'] volume_from = crypto_data[0]['volumefrom'] gain = compare(crypto_data[0]['close'], crypto_data[1]['close']) print( "=================================================================================" ) print('Crypto info date: ', date) #Getting the tweets form the API. for tweet in tweepy.Cursor(api.search, q='Bitcoin -giving -Giveaway', lang='en').items(10): tweets.append(tweet.text) dates.append(tweet.created_at) print('Tweet date: ', tweet.created_at) for tweet in tweets: print( "=================================================================================" ) vs = analyzer.polarity_scores(tweet) print(tweet) #Getting the values from the Sentiment Analysis. full_result = "{:-<65} {}".format(tweet, str(vs)) result = full_result.split('{') split_result = str(result[1]).split(':') params = str(split_result).split(',') full_neg = str(params[1]).split('"') neg = full_neg[1] full_neu = str(params[3]).split('"') neu = full_neu[1] full_pos = str(params[5]).split('"') pos = full_pos[1] full_comp = str(params[7]).split('}') split_comp = str(full_comp[0]).split() comp = split_comp[1] #Storing the values of the analysis. arr_compound.append(comp) arr_positive.append(pos) arr_neutral.append(neu) arr_negative.append(neg) print('Negative: ', neg) print('Neutral: ', neu) print('Positive: ', pos) print('Compound: ', comp) compound = process(arr_compound, 'compound') positive = process(arr_positive, 'positive') negative = process(arr_negative, 'negative') neutral = process(arr_neutral, 'neutral') #Creating the object to write in the csv file. with open('Results.csv', mode='a') as csv_file: fieldnames = [ 'date', 'negative', 'neutral', 'positive', 'compound', 'open', 'close', 'high', 'low', 'volume_from', 'gain' ] writer = csv.DictWriter(csv_file, fieldnames=fieldnames) record(writer, date, compound, negative, neutral, positive, open_price, close_price, high, low, volume_from, gain)
def test_get_historical_price_minute_from_exchange_and_aggregation(self): res = cryptocompare.get_historical_price_minute('ETH', currency='BTC', exchange='Cryptopia', aggregate=5) self.assertTrue('Data' in res.keys(), "expected 'Data'")
def test_get_historical_price_minute(self): res = cryptocompare.get_historical_price_minute(coins[0]) self.assertTrue('Data' in res.keys(), "expected 'Data'") # XXX: cryptocompare is off-by-one self.assertEqual(31, len(res['Data']), "response data limit defaults to 31 days")
print(cryptocompare.get_price(coins[1], curr=['EUR','USD','GBP'], full=True)) print('==================================================') print(cryptocompare.get_price(coins)) print(cryptocompare.get_price(coins, curr='USD')) print(cryptocompare.get_price(coins, curr=['EUR','USD','GBP'])) print('==================== HIST PRICE ==================') print(cryptocompare.get_historical_price(coins[0])) print(cryptocompare.get_historical_price(coins[0], curr='USD')) print(cryptocompare.get_historical_price(coins[1], curr=['EUR','USD','GBP'])) print(cryptocompare.get_historical_price(coins[1], 'USD', datetime.datetime.now())) print(cryptocompare.get_historical_price(coins[2], ['EUR','USD','GBP'], time.time(), exchange='Kraken')) print('================== HIST PRICE MINUTE ===============') print(cryptocompare.get_historical_price_minute(coins[0], curr='USD')) print(cryptocompare.get_historical_price_minute(coins[0], curr='USD', limit=100)) print('================== HIST PRICE HOUR ===============') print(cryptocompare.get_historical_price_hour(coins[0])) print(cryptocompare.get_historical_price_hour(coins[0], curr='USD')) print(cryptocompare.get_historical_price_hour(coins[1], curr=['EUR','USD','GBP'])) print('================== HIST PRICE DAY ================') print(cryptocompare.get_historical_price_day(coins[0])) print(cryptocompare.get_historical_price_day(coins[0], curr='USD')) print(cryptocompare.get_historical_price_day(coins[1], curr=['EUR','USD','GBP'])) print('======================== AVG =====================') print(cryptocompare.get_avg(coins[0], exchange='Coinbase')) print(cryptocompare.get_avg(coins[0], curr='USD', exchange='Coinbase'))
def get_btc_prices(coin="BTC"): raw = cryptocompare.get_historical_price_minute(coin, "USD", 60) for row in raw["Data"]: row["time"] = datetime.fromtimestamp(row["time"]) return raw["Data"]