示例#1
0
    def QueryAPI(self):
        startYear = input("Start Year: ")
        startYear = int(startYear)
        EthSnip = namedtuple("EthSnip", ["year", "month", "day", "price"])
        # Get historical ETH prices from start year to end of last full year
        for year in range(startYear, datetime.date.today().year):
            for month in range(1, 13):
                for day in range(1, monthrange(startYear, month)[1] + 1):
                    price = cc.get_historical_price(
                        'ETH', 'USD', datetime.datetime(year, month, day))
                    self.__ethPrices.append(
                        EthSnip(year, month, day, price['ETH']['USD']))
                print("Aquired prices for " + str(month) + "/" + str(year))
            print("Aquired prices for " + str(year))

        # Get historical ETH prices from beginning of current year to last full month
        year = datetime.date.today().year
        for month in range(1, datetime.date.today().month):
            for day in range(1, monthrange(year, month)[1] + 1):
                price = cc.get_historical_price(
                    'ETH', 'USD', datetime.datetime(year, month, day))
                self.__ethPrices.append(
                    EthSnip(year, month, day, price['ETH']['USD']))
            print("Aquired prices for " + str(month) + "/" + str(year))

        # Get historical ETH prices of the current month up to the current day
        startMonth = datetime.date.today().month
        for day in range(1, datetime.date.today().day):
            price = cc.get_historical_price(
                'ETH', 'USD', datetime.datetime(year, month, day))
            self.__ethPrices.append(
                EthSnip(year, month, day, price['ETH']['USD']))

        # Return List
        return self.__ethPrices
示例#2
0
    def getCCHistoricalPrice(self, fsym, tsym, exchange, date):
        """Return historical price.

        Args:
            fsym (string): symbol from wich get the price (from symbol)
            tsym (string): symbol in which the price must be get (to symbol)
            exchange (string): exchange to get the price from (can be an empty
                string '' if you don't want to use a concrete exchange)
            date (float): date in LibreOffice calc (days since 1899/12/31)

        Returns:
            float: historical price
        """

        home = expanduser("~")
        cache_file = join(home, ".cc_cache.csv")
        fieldnames = ["timestamp", "fsym", "tsym", "price"]
        date_base_calc = datetime(1899, 12, 30)
        date_base_unix = datetime(1970, 1, 1)
        delta = timedelta(days=date)
        timestamp = (date_base_calc + delta - date_base_unix).total_seconds()

        # Read cache CSV file

        price = None
        if isfile(cache_file):
            file = open(cache_file, "r")
            reader = DictReader(file, fieldnames=fieldnames)
            for row in reader:
                if row["timestamp"] == str(timestamp) \
                   and row["fsym"] == str(fsym) \
                   and row["tsym"] == str(tsym):
                   price = row["price"]
                   break
            file.close()

        # Call cryptocompare API and save price in cache

        if price is None:
            if len(exchange) != 0:
                result = get_historical_price(fsym,
                                              tsym,
                                              timestamp=timestamp,
                                              exchange=exchange)
            else:
                result = get_historical_price(fsym,
                                              tsym,
                                              timestamp=timestamp)
            price = result[fsym][tsym]
            row = { "timestamp": timestamp,
                    "fsym": fsym,
                    "tsym": tsym,
                    "price": price }
            file = open(cache_file, "a")
            writer = DictWriter(file, fieldnames=fieldnames)
            writer.writerow(row)
            file.close()

        return float(price)
示例#3
0
 def test_get_historical_price(self):
     coin = 'XMR'
     curr = 'EUR'
     price = cryptocompare.get_historical_price(
         'XMR', timestamp=datetime.date(2017, 6, 6))
     self.assertCoinAndCurrInPrice(coin, curr, price)
     price2 = cryptocompare.get_historical_price(
         'XMR', 'EUR', datetime.datetime(2017, 6, 6))
     self.assertCoinAndCurrInPrice(coin, curr, price2)
     self.assertEqual(price, price2)
示例#4
0
 def getRate(self):
     global Date
     try:
         Date = self.getDate()
         global Rate
         if type(Date) == dt:
             try:
                 Rate = cryptocompare.get_historical_price(Currency,
                                                           curr=curr,
                                                           timestamp=Date)
                 self.figure.clear()
                 self.textBrowser.setText(
                     'The rate of {} is {} {} for {}'.format(
                         self.comboBox.currentText().strip(),
                         Rate[Currency][curr], curr, Date))
             except NameError:
                 try:
                     Rate = cryptocompare.get_historical_price(
                         'ETH', curr=curr, timestamp=Date)
                     self.figure.clear()
                     self.textBrowser.setText(
                         'The rate of Etherium is {} {} for {}'.format(
                             Rate['ETH'][curr], curr, Date))
                 except NameError:
                     self.textBrowser.setText('Choose the currency!')
         else:
             try:
                 Rate = []
                 for i in Date:
                     rate = cryptocompare.get_historical_price(Currency,
                                                               curr=curr,
                                                               timestamp=i)
                     Rate.append(rate[Currency][curr])
                 self.textBrowser.setText(
                     'The values are: \n {}'.format(Rate))
                 self.plot()
             except NameError:
                 try:
                     for i in Date:
                         rate = cryptocompare.get_historical_price(
                             'ETH', curr=curr, timestamp=i)
                         Rate.append(rate['ETH'][curr])
                     self.textBrowser.setText(
                         'The values are: \n {}'.format(Rate))
                     self.plot()
                 except NameError:
                     self.textBrowser.setText('Choose the currency!')
     except NameError:
         self.textBrowser.setText('Choose the date!')
示例#5
0
def refresh_conv_rate(when, token_name):
    to_currency = 'USDT'
    conversion_rate = ConversionRate.objects.filter(
        from_currency=token_name,
        to_currency=to_currency,
        timestamp=when
    )

    if not conversion_rate:  # historical ConversionRate for the given bounty does not exist yet
        try:
            price = cc.get_historical_price(token_name, to_currency, when)

            if price and price.get(token_name):
                to_amount = price[token_name][to_currency]
                ConversionRate.objects.create(
                    from_amount=1,
                    to_amount=to_amount,
                    source='cryptocompare',
                    from_currency=token_name,
                    to_currency=to_currency,
                    timestamp=when,
                )
                print(f'Cryptocompare: {token_name}=>{to_currency}:{to_amount}')
        except Exception as e:
            logger.exception(e)
示例#6
0
 def test_get_historical_price_against_currency(self):
     res = cryptocompare.get_historical_price(coins[0],
                                              currency='EUR',
                                              exchange='Kraken')
     self.assertTrue(coins[0] in res.keys(), "expected coin requested data")
     self.assertTrue(res[coins[0]]['EUR'] > 0,
                     "Obtained a price and it is bigger than 0")
示例#7
0
def check_prices(df_mani, cryptos):
    time = datetime.datetime.now()
    df_mani[f'PriceAt {time}'] = 0
    for idx, key in enumerate(list(cryptos.keys())):
        if len(
                json_extract(
                    cryptocompare.get_historical_price(
                        key[0], currency='USD', timestamp=time), 'USD')) != 0:
            df_mani[f'PriceAt {time}'][idx] = json_extract(
                cryptocompare.get_historical_price(key[0],
                                                   currency='USD',
                                                   timestamp=time), 'USD')[0]
        else:
            df_mani[f'PriceAt {time}'][idx] = 0
    print(df_mani)
    df_mani.to_csv('Results.csv', index=False)
示例#8
0
 def test_get_historical_price_against_currency(self):
     res = cryptocompare.get_historical_price(coins[0], currency='EUR')
     self.assertTrue(coins[0] in res.keys(), "expected coin requested data")
     self.assertFalse(coins[1] in res.keys(),
                      "We do not expect data from non requested coin")
     self.assertTrue(res[coins[0]]['EUR'] > 0,
                     "Obtained a price and it is bigger than 0")
示例#9
0
def get_tweets(api, cryptos, sorted_followers):
    #tweets = []
    for indx, tweet in enumerate(
            tweepy.Cursor(api.home_timeline).items(NUMBER_OF_TWEETS)):
        crypto_keys = list(cryptos.keys())
        for idx, key in enumerate(crypto_keys):
            if (f" {key[0]} "
                    in tweet.text) or (f" {key[1]} " in tweet.text) or (
                        f"${key[0]}"
                        in tweet.text) or (f"${key[1]}" in tweet.text) or (
                            f"#{key[0]}" in tweet.text) or (f"#{key[1]}"
                                                            in tweet.text):
                if len(
                        json_extract(
                            cryptocompare.get_historical_price(
                                key[0],
                                currency='USD',
                                timestamp=datetime.datetime.now()),
                            'USD')) != 0:
                    polarity = NLP(tweet.text).sentiment.polarity
                    cryptos[key] += polarity * sorted_followers[
                        tweet.user.name]
                    #tweets.append(f"*** AT {tweet.created_at} ->{tweet.user.name}<- with polarity={NLP(tweet.text).sentiment} ==={tweet.text}=== ***")
        if indx == NUMBER_OF_TWEETS - 1:
            last_tweet_time = tweet.created_at
    cryptos = dict(
        sorted(cryptos.items(), key=lambda item: item[1], reverse=True))
    cryptos = {k: v for k, v in cryptos.items() if v}
    pd.DataFrame.from_dict(data=cryptos, orient='index').to_csv('cryptos.csv',
                                                                header=False)
    return cryptos, last_tweet_time
示例#10
0
 def test_get_historical_price_giving_timestamp(self):
     res = cryptocompare.get_historical_price(
         coins[1],
         currency='EUR',
         timestamp=datetime.datetime.now() -
         datetime.timedelta(days=1, hours=-5))
     self.assertTrue(coins[1] in res.keys(), "expected coin requested data")
     self.assertFalse(coins[0] in res.keys(),
                      "We do not expect data from non requested coin")
     self.assertTrue(res[coins[1]]['EUR'] > 0,
                     "Obtained a price and it is bigger than 0"
                     )  # This doesn't prove the price is right
示例#11
0
def get_mani(cryptos, last_tweet_time):
    for idx, (crypto, significance) in enumerate(cryptos.items()):
        print(f"*{idx}.*  {crypto} {significance} {last_tweet_time}")
    df_mani = pd.DataFrame(cryptos.items(), columns=['Crypto', 'Significance'])
    df_mani['TimeOfTweet'] = last_tweet_time
    time = datetime.datetime.now() - datetime.timedelta(minutes=30)
    df_mani[f'PriceAt {time}'] = 0
    for idx, key in enumerate(list(cryptos.keys())):
        #print(idx, key)
        #print(json_extract(cryptocompare.get_historical_price(key[0], currency='USD', timestamp=time), 'USD'))
        if len(
                json_extract(
                    cryptocompare.get_historical_price(
                        key[0], currency='USD', timestamp=time), 'USD')) != 0:
            df_mani[f'PriceAt {time}'][idx] = json_extract(
                cryptocompare.get_historical_price(key[0],
                                                   currency='USD',
                                                   timestamp=time), 'USD')[0]
        else:
            df_mani[f'PriceAt {time}'][idx] = 0
    return df_mani
示例#12
0
def syncDailyPrices():  # Turned off for now needs fine tuning.
    # Connect to the MySQL database
    db = MySQLdb.connect(host='127.0.0.1',
                         user='******',
                         passwd='pass',
                         db='Blockfund')
    # Check if connection was successful
    if (db):
        # Carry out normal procedure
        print("Connection successful")
    else:
        # Terminate
        print("Connection unsuccessful")
        return -1

    c = db.cursor()
    c.execute(
        "SELECT Year, MonthOfYear, DayOfMonth FROM DimDate t LEFT JOIN btcclosingprice btc ON t.MYSQL_DateFormat = btc.CALENDAR_DATE WHERE t.MYSQL_DateFormat BETWEEN  '2017-1-1 00:00:00' AND NOW( ) AND btc.USD IS NULL;"
    )
    missing_dates = list(c.fetchall())
    # c.execute("START TRANSACTION;")
    if len(missing_dates) > 0:
        print("Retrieving and inserting data for dates:")
        print(missing_dates)
        dyn_SQL = "Insert into btcclosingprice (PK, DATE, USD) values "
        for year, month, day in missing_dates:
            print(datetime.datetime(year, month, day))
            historical_price = cryptocompare.get_historical_price(
                'BTC', 'USD', datetime.datetime(year, month,
                                                day))  # Get a day in time
            print("BTC on {}-{}-{}: {}".format(year, month, day,
                                               historical_price))

            dyn_SQL += "(0, '" + str(datetime.datetime(
                year, month, day)) + "', " + str(
                    float(historical_price['BTC']['USD'])) + "), "
        dyn_SQL = dyn_SQL[:-2] + ";"  # Remove the final comma (and space) and add semicolon
        print(dyn_SQL)
        c.execute(dyn_SQL)
        c.execute("COMMIT;")
    else:
        print("BTC USD Up to date.")

    # result_ct = c.execute("SELECT * from btcclosingprice;")
    # results = c.fetchall()

    return True
示例#13
0
def get_price(coin='BTC', currency='USD', date=None):
    """
    Get price of cryptocurrency in terms of real currency on a specific day

    Params:
    coin [str]: cryptocurrency code
    currency [str]: real currency code
    date [datetime]: year, month, day of price

    Return [float]: price of coin in currency

    Example:
    get_price('BTC', 'USD', datetime.datetime(2017, 10, 26))
    """
    if date:
        dct = cc.get_historical_price(coin, currency, date)
    else:
        dct = cc.get_price(coin, currency, full=False)
    return dct[coin][currency] if dct else None
示例#14
0
def pull(date, coin_name, start_index):
	data = [[],[]]
	t = 0
	day_list = [date]
	while(start_index < date):
		data[0].append(t)
		data[1].append(0)
		t += 1
		start_index += dt.timedelta(days=1)

	while(date < dt.datetime.today()):
		day_list.append(date)
		date += dt.timedelta(days=1)

	# made a little for loop to replace the original while loop b/c I like progress bars
	for day in tqdm.tqdm(day_list):
		crypto = cc.get_historical_price(coin_name, 'USD', timestamp=day)
		data[0].append(t)
		data[1].append(crypto[coin_name]['USD'])
		t += 1

	return zip(data[0],data[1])
示例#15
0
    #sorted_followers = sort_followers(api)
    sorted_followers = pd.read_csv('Followers.csv',
                                   header=None,
                                   index_col=0,
                                   squeeze=True).to_dict()
    print(sorted_followers)

    #Get a list of those tweets which contain any of the key words (crypto names or symbols)
    #cryptos = pd.read_csv('cryptos.csv', header=None, index_col=0, squeeze=True).to_dict()
    cryptos, last_tweet_time = get_tweets(api, cryptos, sorted_followers)

    #Money Printer Go Brrr
    df_mani = get_mani(cryptos, last_tweet_time)

    for i in range(0, 12):
        check_prices(df_mani, cryptos)
        time.sleep(60)


if __name__ == '__main__':
    #print(type(0.))
    while True:
        main_method()
        time.sleep(750)
    time = datetime.datetime.now() - datetime.timedelta(minutes=30)
    print(
        json_extract(
            cryptocompare.get_historical_price('BTC',
                                               currency='USD',
                                               timestamp=time), 'USD')[0])
    print(time)
示例#16
0
def fullBackloadBySymbolandCurrency(symbol, currency):
    start_time = time.time()
    coin_list = cryptocompare.get_coin_list(format=False)
    print("Symbol: {}, Id: {}".format(symbol, coin_list[symbol]['Id']))
    snapshot = cryptocompare.get_snapshotbyid(coin_list[symbol]['Id'])
    # Get start date for API from the snapshot list then convert to MYSQL date format
    start_date = datetime.datetime.strptime(
        snapshot['Data']['General']['StartDate'],
        '%d/%m/%Y').strftime('%Y-%m-%d')
    print(snapshot['Data']['General']['StartDate']
          )  # Get ICO date, or whatever they consider a start date #
    if snapshot['Data']['General']['StartDate'] < '01/01/2000':
        print("Invalid date range, skipping")
        logging.warning(
            "Invalid date range for {}, supposed start date: {}".format(
                symbol, snapshot['Data']['General']['StartDate']))
        return False
    db = MySQLdb.connect(host='127.0.0.1',
                         user='******',
                         passwd='pass',
                         db='Backload',
                         local_infile=1)
    # Check if connection was successful
    if (db):
        # Carry out normal procedure
        print("Connection successful")
    else:
        # Terminate
        print("Connection unsuccessful")
        logging.warning(
            "Database connection error. Symbol: {}, StartDate: {}".format(
                symbol, snapshot['Data']['General']['StartDate']))
        return -1
    cursor = db.cursor()
    #print("SELECT CALENDAR_DATE from DimDate where CALENDAR_DATE >= CAST('{}' AS DATE) AND CALENDAR_DATE < date(now()) order by CALENDAR_DATE limit 10;".format(start_date))
    result_ct = cursor.execute(
        "SELECT CALENDAR_DATE from DimDate where CALENDAR_DATE >= CAST('{}' AS DATE) AND CALENDAR_DATE < date(now()) order by CALENDAR_DATE;"
        .format(start_date))
    results = list(cursor.fetchall())
    print("{} days to load.".format(len(results)))
    row_ct = 0
    if len(results) > 0:
        if cryptocompare.get_historical_price(
                symbol, currency,
                datetime.datetime.combine(
                    results[0][0], datetime.datetime.min.time())) == None:
            with open('allcoins/nodatacurrency.csv', 'a',
                      newline='\n') as csvfile:
                writer = csv.writer(csvfile,
                                    delimiter=',',
                                    quotechar='"',
                                    quoting=csv.QUOTE_MINIMAL)
                writer.writerow("No data returned for: {} - {}".format(
                    symbol, currency))
            return True

        with open("allcoins/" + symbol + currency + '_' +
                  'loadHistoricalDailyPrices.csv',
                  'a',
                  newline='\n') as csvfile:
            writer = csv.writer(csvfile,
                                delimiter=',',
                                quotechar='"',
                                quoting=csv.QUOTE_MINIMAL)
            for row in results:
                row_ct += 1
                time.sleep(
                    0.5)  # Slow down the API calls so as to not get banned.
                historical_date = datetime.datetime.combine(
                    row[0], datetime.datetime.min.time()
                )  # Ugggh, did I make this column date instead of datetime? This is a quick fix until I fix the db datatype
                for attempt in range(
                        5):  # Try to reconnect 5 times if we can't connect
                    try:
                        historical_price = cryptocompare.get_historical_price(
                            symbol, currency, historical_date)
                    except:
                        print("Retrying API Call...")
                        historical_price = cryptocompare.get_historical_price(
                            symbol, currency, historical_date)
                    else:
                        break
                else:
                    print(
                        "Backloading failed, API calls got denied. Exiting...")
                    return False
                print('{} rows inserted!'.format(row_ct), end='\r')

                try:
                    writer.writerow([
                        0, historical_date, historical_price[symbol][currency]
                    ])
                except:
                    logging.warning(
                        "Writerow error - Symbol: {}, Currency: {}, historicaldate: {}, historical_price: {}"
                        .format(symbol, currency, historical_date,
                                historical_price))
                    return False
    else:
        print("{} - {} backload complete.".format(symbol, currency))
    elapsed_time = time.time() - start_time
    print("{}: {} rows inserted in {}s.\nAPI call frequency: {}".format(
        symbol, row_ct, elapsed_time,
        float(elapsed_time) / float(row_ct)))
    print("(If call frequency exceeds 1.67 they will ban the IP)")

    # Now create the db tables and load them from CSV
    try:
        createTableSQL = "CREATE TABLE {}{}_closingprice (`PK` int(11) NOT NULL AUTO_INCREMENT,`date` datetime DEFAULT NULL,`{}` double DEFAULT NULL, PRIMARY KEY (`PK`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;".format(
            symbol.lower().replace("*", ""), currency.lower(), currency)
        result_ct = cursor.execute(createTableSQL)

        loadTableSQL = "LOAD DATA LOCAL INFILE '~/workspace/Random/allcoins/{}{}_loadHistoricalDailyPrices.csv' INTO TABLE {}{}_closingprice FIELDS OPTIONALLY ENCLOSED BY '\"' TERMINATED BY ',' LINES TERMINATED BY '\n' (PK,@DATE,USD) SET DATE = STR_TO_DATE(@DATE, '%Y-%m-%d %H:%i:%s');".format(
            symbol, currency, symbol.lower(), currency.lower())
        cursor.execute("START TRANSACTION;")
        cursor.execute(
            loadTableSQL)  # Getting warnings here but the uploads look ok
        cursor.execute("COMMIT;")
    except Exception as e:
        print("Create or load table error:\n{}".format(e))
    return True
def get_coin_price(coin_code, currency, time=None):
    return cryptocompare.get_historical_price(coin_code, currency, time)
示例#18
0
def getPriceThatDay(crytoName, currencyName, timeStamp):
    price = cryptocompare.get_historical_price(crytoName, currencyName,
                                               timeStamp)
    return price[crytoName][currencyName]
示例#19
0
async def on_ready():        

    print('We have logged in as {0.user}'.format(client))
    channel = client.get_channel(channel_id)
    while(True):
        embed=discord.Embed(title="Etherum", description=str(cryptocompare.get_price('ETH','USD')['ETH']['USD'])+"$")
        embed.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/Ethereum-icon-purple.svg/1200px-Ethereum-icon-purple.svg.png")
        embed.add_field(name = "24h change ",value=str(cryptocompare.get_price('ETH','USD')['ETH']['USD']/(cryptocompare.get_historical_price('ETH', 'USD', datetime.datetime(datetime.datetime.now().year,datetime.datetime.now().month,datetime.datetime.now().day-1))['ETH']['USD']))[:4]+"%", inline=False)
        embedBTC=discord.Embed(title="Bitcoin", description=str(cryptocompare.get_price('BTC','USD')['BTC']['USD'])+"$")
        embedBTC.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/commons/thumb/4/46/Bitcoin.svg/1200px-Bitcoin.svg.png")
        await channel.send(embed=embed)
        await channel.send(embed=embedBTC)
        await asyncio.sleep(60)
示例#20
0
print('===================== PRICE ======================')
print(cryptocompare.get_price(coins[0]))
print(cryptocompare.get_price(coins[1], curr='USD'))
print(cryptocompare.get_price(coins[2], curr=['EUR','USD','GBP']))
print(cryptocompare.get_price(coins[2], full=True))
print(cryptocompare.get_price(coins[0], curr='USD', full=True))
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 ================')
示例#21
0
import json
import cryptocompare
import datetime
print(
    json.loads(
        cryptocompare.get_historical_price('XMR', 'USD',
                                           datetime.datetime.now())))
 def getPastPrice(self, ticker):
     return cryptocompare.get_historical_price(
         ticker, 'USD', datetime.datetime(2017, 6, 6))
示例#23
0
def syncDailyPrices():  # Turned off for now needs fine tuning.
    # Connect to the MySQL database
    db = MySQLdb.connect(host='127.0.0.1',
                         user='******',
                         passwd='pass',
                         db='Blockfund')
    # Check if connection was successful
    if (db):
        # Carry out normal procedure
        print("Connection successful")
    else:
        # Terminate
        print("Connection unsuccessful")
        return -1

    c = db.cursor()
    c.execute(
        "SELECT Year, MonthOfYear, DayOfMonth FROM DimDate t LEFT JOIN btcclosingprice btc ON t.MYSQL_DateFormat = btc.CALENDAR_DATE WHERE t.MYSQL_DateFormat BETWEEN  '2017-1-1 00:00:00' AND NOW( ) AND btc.USD IS NULL;"
    )
    missing_dates = list(c.fetchall())
    # c.execute("START TRANSACTION;")
    if len(missing_dates) > 0:
        print("Retrieving and inserting data for dates:")
        print(missing_dates)
        dyn_SQL = "Insert into btcclosingprice (PK, DATE, USD) values "
        for year, month, day in missing_dates:
            print(datetime.datetime(year, month, day))
            historical_price = cryptocompare.get_historical_price(
                'BTC', 'USD', datetime.datetime(year, month,
                                                day))  # Get a day in time
            print("BTC on {}-{}-{}: {}".format(year, month, day,
                                               historical_price))

            dyn_SQL += "(0, '" + str(datetime.datetime(
                year, month, day)) + "', " + str(
                    float(historical_price['BTC']['USD'])) + "), "
        dyn_SQL = dyn_SQL[:-2] + ";"  # Remove the final comma (and space) and add semicolon
        print(dyn_SQL)
        c.execute(dyn_SQL)
        c.execute("COMMIT;")
    else:
        print("BTC USD Up to date.")

    # result_ct = c.execute("SELECT * from btcclosingprice;")
    # results = c.fetchall()

    return True


# scheduler = BackgroundScheduler()
# scheduler.start()
# scheduler.add_job(
#     func=print_date_time,
#     trigger=IntervalTrigger(minutes=1),
#     id='printing_job',
#     name='Print date and time every five seconds',
#     replace_existing=True)
# scheduler.add_job(
#     func=lambda: add_daily_price_to_db('BTC'),      # Must use lambda to pass function referencewith parameters otherwise function fires on app start
#     trigger='cron',
#     year='*', month='*', day="*", week='*', day_of_week='*', hour='*', minute="*", second=5);
# # Shut down the scheduler when exiting the app
# atexit.register(lambda: scheduler.shutdown())
# ##############################
示例#24
0
 def test_get_historical_price(self):
     res = cryptocompare.get_historical_price(coins[0])
     self.assertTrue(coins[0] in res.keys(), "expected coin requested data")
     self.assertTrue(res[coins[0]]['USD'] > 0,
                     "Obtained a price and it is bigger than 0"
                     )  # USD is default currency
示例#25
0
文件: tasks.py 项目: shfkdroal/hts
def Handle_CryptoCurrency(scd, RD_id, gapSeed):
    if gapSeed == 'N/A':
        gapSeed = '0'
    gapSeed = int(gapSeed)

    RD_row = RD_Related_To_Shares.objects.get(id=RD_id)
    currentPrice = cryptocompare.get_price(scd, 'USD')  #('BTC')
    yesterday = date.today() - timedelta(1)
    #yesterday = datetime.strftime(datetime.now() - timedelta(1), '%Y:%m:%d')
    yesterday = yesterday.strftime('%Y:%m:%d')
    yestList = yesterday.split(':')
    y = int(yestList[0])
    m = int(yestList[1])
    d = int(yestList[2])
    yesterdayPrice = cryptocompare.get_historical_price(scd,
                                                        'USD',
                                                        timestamp=datetime(
                                                            y, m, d))
    currentPrice = currentPrice[scd]['USD']
    yesterdayPrice = yesterdayPrice[scd]['USD']
    hPrice = currentPrice - yesterdayPrice

    excgR = MarketStatus.exchRate()
    hPrice = hPrice * excgR
    currentPrice = currentPrice * excgR
    #initQuant = currentPrice
    #QuantMado = "61;62;63;64;65;66;67;68;69;"
    #QuantMaSu = "71;72;73;74;75;76;77;78;79;"

    q = []
    if gapSeed < 2:
        gapSeed = 2
    for i in range(0, 18):
        rn = random.randrange(0, gapSeed)
        rn = rn / 15000000
        q.append("{0:.4f}".format(rn))

    currentPrice = int(currentPrice)
    length = len(str(currentPrice))
    divider = length - 5
    if divider < 0:
        divider = 0
    fixer = pow(10, -divider)
    currentPrice = int(fixer * currentPrice)
    temp = currentPrice / fixer
    currentPrice = temp
    dict = {
        'scd': scd,
        '10': currentPrice,
        '15': 1,
        '11': hPrice,
        '61': q[0],
        '62': q[1],
        '63': q[2],
        '64': q[3],
        '65': q[4],
        '66': q[5],
        '67': q[6],
        '68': q[7],
        '69': q[8],
        '71': q[9],
        '72': q[10],
        '73': q[11],
        '74': q[12],
        '75': q[13],
        '76': q[14],
        '77': q[15],
        '78': q[16],
        '79': q[17]
    }

    RD_row.RDDictString = json.dumps(dict)
    RD_row.Should_be_updated_now = False
    RD_row.save()

    return
示例#26
0
 def get_historical_price(self, crypto, datetime):
     price = cryptocompare.get_historical_price(crypto, 'USD', datetime)
     return price
示例#27
0
import cryptocompare
import datetime

print(cryptocompare.get_price('BTC', 'USD'))
# or
# print(cryptocompare.get_price('BTC',curr='USD',full=True))

# print(cryptocompare.get_coin_list(format=False))
# or
#print(cryptocompare.get_price(['BTC','ETH'],['EUR','GBP']))

# {'BTC': {'EUR': 3709.04, 'GBP': 3354.78},
#  'ETH': {'EUR': 258.1, 'GBP': 241.25}}


# print(cryptocompare.get_historical_price('BTC', timestamp=datetime.datetime(2018,3,11)))
print(cryptocompare.get_historical_price('BTC', 'USD', datetime.datetime.now(tz=datetime.tzinfo(0))))
示例#28
0
def change(date1, date2):
    price = cryptocompare.get_historical_price(
        'XMR', 'USD',
        (date1)) - cryptocompare.get_historical_price('XMR', 'USD', (date2))
    return price