def get_cmc_top_n() -> pd.DataFrame:
    """Shows top n coins. [Source: CoinMarketCap]

    Returns
    -------
    pd.DataFrame
        Top coin on CoinMarketCap

    """

    cmc = CoinMarketCapAPI(cfg.API_CMC_KEY)
    ratings = cmc.cryptocurrency_listings_latest().data

    symbol, rank, price, pchange1d, mkt_cap = [], [], [], [], []
    for coin in ratings:
        symbol.append(coin["symbol"])
        rank.append(coin["cmc_rank"])
        price.append(coin["quote"]["USD"]["price"])
        pchange1d.append(coin["quote"]["USD"]["percent_change_24h"])
        mkt_cap.append(coin["quote"]["USD"]["market_cap"] / (10**9))

    df = pd.DataFrame(data=[symbol, rank, price, pchange1d, mkt_cap]).transpose()
    df.columns = [
        "Symbol",
        "CMC_Rank",
        "Last Price",
        "1 Day Pct Change",
        "Market Cap ($B)",
    ]

    return df
Beispiel #2
0
def get_crypto_price(ticker: str) -> float:
    cmc = CoinMarketCapAPI(config['cmc_api_key'])

    crypto_listings = cmc.cryptocurrency_listings_latest().data

    crypto_price = next((crypto.get('quote', {}).get('USD', {}).get('price')
                        for crypto in crypto_listings 
                        if crypto.get('symbol') == ticker), None)
    if crypto_price is None:
        raise Exception(f'{ticker} price is None')                  
    
    return float(crypto_price)
Beispiel #3
0
class CoinMarketCap:
    def __init__(self, api_key=None):
        self.api = CoinMarketCapAPI(api_key or COIN_MARKET_CAP_API_KEY)

    @staticmethod
    def filter_essential_data(data, coin, currency):
        return {
            "source":
            "Coin Market Cap",
            "symbol":
            data[coin]["symbol"],
            "name":
            data[coin]["name"],
            "total_supply":
            data[coin]["total_supply"],
            "value":
            f"{data[coin]['quote'][currency]['price']}",
            "currency":
            currency,
            "percent_change_24h":
            data[coin]["quote"][currency]["percent_change_24h"],
            "market_cap":
            data[coin]["quote"][currency]["market_cap"],
        }

    def price(self, coin, currency):
        result = self.api.cryptocurrency_quotes_latest(symbol=coin,
                                                       convert=currency)
        return self.filter_essential_data(result.data,
                                          coin=coin,
                                          currency=currency)
Beispiel #4
0
def pull_price_list(settings, asset_list):
    api_iterator = 0  # iterates through the data pulled with API key. Resets every time an asset is found.
    asset_iterator = 0  # iterates through the list of tracked assets. Never resets.
    found = False
    asset_id = 1
    asset_list = settings[1]
    price_list = {}

    #Get data and find requested asset
    r = CoinMarketCapAPI(api_key).cryptocurrency_listings_latest()
    while not found and api_iterator < 100:

        # if tracked asset is found, add its price to the price list.
        #time.sleep(0.5)
        if r.data[api_iterator]["name"] == asset_list[asset_iterator]:

            #price_list.append(r.data[api_iterator]["quote"]["USD"]["price"])
            price_list[asset_list[asset_iterator]] = r.data[api_iterator][
                "quote"]["USD"]["price"]
            asset_iterator += 1  # move on to next tracked asset

            # if this was not the last tracked asset, reset API data iterator
            if asset_iterator < len(asset_list):
                api_iterator = -1

            # if this was the last asset, set found to true
            elif asset_iterator == len(asset_list):
                found = True

        api_iterator += 1
    return price_list
Beispiel #5
0
class Crypto:
    def __init__(self, api_key=None):
        self.manager = CoinMarketCapAPI(api_key or COIN_MARKET_CAP_API_KEY)

    @staticmethod
    def filter_essential_data(data, coin, currency):
        return {
            'symbol':
            data[coin]["symbol"],
            'name':
            data[coin]["name"],
            'total_supply':
            data[coin]["total_supply"],
            'price':
            f"{data[coin]['quote'][currency]['price']} {currency}",
            'percent_change_24h':
            data[coin]["quote"][currency]["percent_change_24h"],
            'market_cap':
            data[coin]["quote"][currency]["market_cap"]
        }

    def price(self, coin, currency):
        result = self.manager.cryptocurrency_quotes_latest(symbol=coin,
                                                           convert=currency)
        return self.filter_essential_data(result.data,
                                          coin=coin,
                                          currency=currency)
Beispiel #6
0
def watcher() -> None:

    cmc = CoinMarketCapAPI(config['coinmarketcap'].get('TOKEN'))
    print(type(cmc))
    previous_supply = 0

    while True:
        supply = getSupply(cmc)

        if supply != previous_supply:

            if supply > previous_supply:
                message = f'{supply-previous_supply} USD₮ printed! \nTotal supply: {supply} USD₮'
                print(message)

                bot.send_message(chat_id=config["telegram"].get("ADMIN_ID"),
                                 text=message)

            elif supply < previous_supply:
                message = f'{previous_supply-supply} USD₮ burned! \nTotal supply: {supply} USD₮'
                print(message)

                bot.send_message(chat_id=config["telegram"].get("ADMIN_ID"),
                                 text=message)

            previous_supply = supply

        else:
            pass

        time.sleep(60)
    def __init__(self, api_key, ignore_list=fiat_list + error_list):
        # Never invest in fiat
        self.ignore_list = list(set(ignore_list + fiat_list))

        self.client = CoinMarketCapAPI(api_key=api_key)
        self.latest_listing_response = self.client.cryptocurrency_listings_latest(
        )
        if self.latest_listing_response.status["error_code"] != 0:
            raise BaseException(
                "Getting latest listings failed with error code {}".format(
                    self.latest_listing_response.status["error_code"]))

        self.sorted_listing = sorted(self.latest_listing_response.data,
                                     key=lambda x: x["cmc_rank"])
        self.sorted_listing = [x["symbol"] for x in self.sorted_listing]
        self.sorted_listing = list(
            filter(lambda x: x not in self.ignore_list, self.sorted_listing))
Beispiel #8
0
class Ticker:
    def __init__(self):
        self.ticker = CoinMarketCapAPI(coin_mkt_token)

    def get_prices(self, *currencies):
        currencies = ','.join(currencies)
        updates = {}
        if currencies:
            for currency in self.ticker.cryptocurrency_listings_latest(
            ).data[:2]:
                updates[currency['symbol']] = {
                    'price': float(currency['quote']['USD']['price'])
                }
            return updates
        return updates
def init():
    global client, db, cmc, line_bot_api, handler, instant_resend, superuser_mode

    # DB stuff
    client = MongoClient(os.getenv("MONGODB_CONNECTION_STRING"))
    db = client[os.getenv("MONGODB_DATABASE")]
    cmc = CoinMarketCapAPI(os.getenv("CMC_API"))

    # Channel Access Token
    line_bot_api = LineBotApi(os.getenv("CHANNEL_ACCESS_TOKEN"))
    # Channel Secret
    handler = WebhookHandler(os.getenv("CHANNEL_SECRET"))

    # Default bot settings
    instant_resend = True
    superuser_mode = True
class CoinMarketCapClient:
    """
    CoinMarketCap client to get the latest top listings sorted by market volume
    """
    def __init__(self, api_key, ignore_list=fiat_list + error_list):
        # Never invest in fiat
        self.ignore_list = list(set(ignore_list + fiat_list))

        self.client = CoinMarketCapAPI(api_key=api_key)
        self.latest_listing_response = self.client.cryptocurrency_listings_latest(
        )
        if self.latest_listing_response.status["error_code"] != 0:
            raise BaseException(
                "Getting latest listings failed with error code {}".format(
                    self.latest_listing_response.status["error_code"]))

        self.sorted_listing = sorted(self.latest_listing_response.data,
                                     key=lambda x: x["cmc_rank"])
        self.sorted_listing = [x["symbol"] for x in self.sorted_listing]
        self.sorted_listing = list(
            filter(lambda x: x not in self.ignore_list, self.sorted_listing))

    def __getTopK(self, ignore, k):
        return self.sorted_listing[ignore:k]

    def getTopK(self, k):
        return self.__getTopK(0, k)

    def getLargeCap(self):
        return self.getTopK(LARGE_CAP)

    def getMidCap(self):
        return self.__getTopK(LARGE_CAP, MID_CAP)

    def getSmallCap(self):
        return self.__getTopK(MID_CAP, SMALL_CAP)
Beispiel #11
0
def setup(bot):
    client = CoinMarketCapAPI(os.getenv("CMC_API_KEY"))
    bot.add_cog(Crypto(bot, client))
Beispiel #12
0
import telegram
import requests
from coinmarketcapapi import CoinMarketCapAPI, CoinMarketCapAPIError
import time

token="1669932102:AAHV28DSzEZbUQos-1h0lgPO4yrziGBiAIk"
bot=telegram.Bot(token=token)
urllina = "https://api.bscscan.com/api?module=account&action=tokenbalance&contractaddress=0x762539b45a1dcce3d36d080f74d1aed37844b878&address=0xeb325a8ea1c5abf40c7ceaf645596c1f943d0948&tag=latest&apikey=MYC6KM6E7AH8CV6GU8TH278M5GVUF1GNWR"
urlbusd = "https://api.bscscan.com/api?module=account&action=tokenbalance&contractaddress=0xe9e7cea3dedca5984780bafc599bd69add087d56&address=0xeb325a8ea1c5abf40c7ceaf645596c1f943d0948&tag=latest&apikey=MYC6KM6E7AH8CV6GU8TH278M5GVUF1GNWR"

cmc = CoinMarketCapAPI('c1d0800c-8429-48a1-b943-e5d37fa42ebb')

while True:
    response1 = requests.get(urllina)
    Json1 = response1.json()

    response1 = requests.get(urlbusd)
    Json2 = response1.json()

    lina = int(Json1['result'])
    busd = int(Json2['result'])
    pool_price = round(busd/lina, 5)

    r = cmc.cryptocurrency_info(symbol='lina')
    description = r.data['LINA']['description']
    strings = description.split(" ")
    price = float(strings[strings.index('USD') - 1])
    price = round(price, 5)

    dif = price / pool_price * 100 - 100
    dif = round(dif, 2)
Beispiel #13
0
def get_cmc_top_n(other_args: List[str]):
    """
    Shows top n coins from coinmarketcap.com
    Parameters
    ----------
    other_args: List[str]
        Arguments to pass to argparse

    """
    parser = argparse.ArgumentParser(
        prog="cmc_top_n",
        add_help=False,
        description="This gets the top ranked coins from coinmarketcap.com",
    )

    parser.add_argument("-n",
                        default=10,
                        dest="n_to_get",
                        type=int,
                        help="number of coins to display")

    parser.add_argument(
        "-s",
        "--sort",
        dest="sortby",
        type=str,
        help="column to sort data by.",
        default="CMC_Rank",
        choices=sort_options,
    )

    parser.add_argument(
        "--descend",
        action="store_false",
        help="Flag to sort in descending order (lowest first)",
        dest="descend",
        default=True,
    )

    try:
        ns_parser = parse_known_args_and_warn(parser, other_args)
        if not ns_parser:
            return

        cmc = CoinMarketCapAPI(cfg.API_CMC_KEY)
        ratings = cmc.cryptocurrency_listings_latest().data

        symbol, rank, price, pchange1d, mkt_cap = [], [], [], [], []
        for coin in ratings:
            symbol.append(coin["symbol"])
            rank.append(coin["cmc_rank"])
            price.append(coin["quote"]["USD"]["price"])
            pchange1d.append(coin["quote"]["USD"]["percent_change_24h"])
            mkt_cap.append(coin["quote"]["USD"]["market_cap"] / (10**9))

        df = pd.DataFrame(
            data=[symbol, rank, price, pchange1d, mkt_cap]).transpose()
        df.columns = [
            "Symbol",
            "CMC_Rank",
            "Last Price",
            "1 Day Pct Change",
            "Market Cap ($B)",
        ]

        df = df.sort_values(by=sort_map[ns_parser.sortby],
                            ascending=ns_parser.descend)

        print(
            tabulate(
                df.iloc[:ns_parser.n_to_get, :],
                headers=df.columns,
                showindex=False,
                tablefmt="fancy_grid",
                floatfmt=".2f",
            ))
        print("")

    except Exception as e:
        print(e)
        print("")
Beispiel #14
0
}


#get coin dict from a file using pickle
def readfiletodict(filename):
    with open(filename, 'rb') as file_to_read:
        coin_price_dict = dictionary = pickle.load(file_to_read)
        return coin_price_dict


def writedicttofile(write_dict, filename):
    with open(filename, "wb") as file_to_write:
        pickle.dump(write_dict, file_to_write)


cmc = CoinMarketCapAPI(cmc_api_token)
coin_name_list = [
    'BTC', 'ETH', 'XRP', 'LTC', 'BCH', 'LINK', 'ADA', 'DOT', 'BNB', 'YFI',
    'LUNA'
]
coin_price_dict = readfiletodict('coinpricedict.txt')
coin_signal = readfiletodict('coinsignal.txt')


#check the index of the coin name
def getcoinlist():
    coin_index_list = []
    alldata = cmc.cryptocurrency_listings_latest(limit=100)
    coin_alldata = alldata.data
    for i in range(0, 100):
        if coin_alldata[i]['symbol'] in coin_name_list:
Beispiel #15
0
 def __init__(self, api_key=None):
     self.api = CoinMarketCapAPI(api_key or COIN_MARKET_CAP_API_KEY)
from coinmarketcapapi import CoinMarketCapAPI, CoinMarketCapAPIError
import json
import numpy as np

APIKEY = "2b660bde-a5ee-4ea6-b3f5-f7ff33e83685"

cmc = CoinMarketCapAPI(APIKEY)

#r = cmc.cryptocurrency_info(symbol='BTC')
response = cmc.cryptocurrency_listings_latest()

latest = list(response.data)
arr = []
for crypto in list(latest):
    quote = crypto['quote']['USD']
    liste = [
        crypto['name'],
        float(quote['percent_change_1h']),
        float(quote['percent_change_24h']),
        float(quote['percent_change_7d'])
    ]
    arr.append(liste)
''' plus rapide de convertir la liste en array '''
np_arr = np.array(arr, dtype='object')
"""for crypto in list(latest):
    print(crypto['id'],crypto['name'],crypto['quote'])"""
"""
{'price': 31844.873093123057, 'volume_24h': 18276287717.518513, 'percent_change_1h': 0.37411178, 'percent_change_24h': 1.4830346, 'percent_change_7d': -5.76745594, 'percent_change_30d': -15.65053106, 'percent_change_60d': -18.20391267, 'percent_change_90d': -44.1877872, 'market_cap': 597399851781.7104, 'last_updated': '2021-07-18T12:05:02.000Z'

"""
b = np_arr[np.argsort(np_arr[:, 1])]
Beispiel #17
0
import telegram
from telegram.ext import Updater
from telegram.ext import CommandHandler
import requests
from coinmarketcapapi import CoinMarketCapAPI, CoinMarketCapAPIError

token = "1669932102:AAHV28DSzEZbUQos-1h0lgPO4yrziGBiAIk"
updater = Updater(token=token, use_context=True)
dispatcher = updater.dispatcher
urllina = "https://api.bscscan.com/api?module=account&action=tokenbalance&contractaddress=0x762539b45a1dcce3d36d080f74d1aed37844b878&address=0xeb325a8ea1c5abf40c7ceaf645596c1f943d0948&tag=latest&apikey=MYC6KM6E7AH8CV6GU8TH278M5GVUF1GNWR"
urlbusd = "https://api.bscscan.com/api?module=account&action=tokenbalance&contractaddress=0xe9e7cea3dedca5984780bafc599bd69add087d56&address=0xeb325a8ea1c5abf40c7ceaf645596c1f943d0948&tag=latest&apikey=MYC6KM6E7AH8CV6GU8TH278M5GVUF1GNWR"
urllp = "https://api.bscscan.com/api?module=stats&action=tokensupply&contractaddress=0xeb325a8ea1c5abf40c7ceaf645596c1f943d0948&apikey=MYC6KM6E7AH8CV6GU8TH278M5GVUF1GNWR"
cmc = CoinMarketCapAPI('c1d0800c-8429-48a1-b943-e5d37fa42ebb')


def call_account():
    f = open('account.txt', 'r')
    account = f.readline()
    account = account.split(' ')
    return account[0], account[1], account[2]


def update(update, context):
    if (len(context.args) == 3):
        f = open('account.txt', 'w')
        f.write("{} {} {}".format(context.args[0], context.args[1],
                                  context.args[2]))
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text="LINA, BUSD, LP 수량이 업데이트 되었습니다")
    else:
        context.bot.send_message(chat_id=update.effective_chat.id,
Beispiel #18
0
from datetime import datetime
from pprint import pprint

import cryptocompare
import requests
from coinmarketcapapi import CoinMarketCapAPI
from flask import Flask, jsonify
from flask_caching import Cache
from flask_cors import cross_origin

from private.keys import API_KEYS
from private.keys import finn_hubb_key, cryptocompare_api_key

cmc = CoinMarketCapAPI(API_KEYS['coinmarket']['api_key'])

config = {
    "DEBUG": True,  # some Flask specific configs
    "CACHE_TYPE": "simple",  # Flask-Caching related configs
    "CACHE_DEFAULT_TIMEOUT": 300
}
app = Flask(__name__)
# tell Flask to use the above defined config
app.config.from_mapping(config)
cache = Cache(app)

# keys
FH_API = finn_hubb_key['api']
CC_API = cryptocompare_api_key
FH_BASE_URL = 'https://finnhub.io/api/v1/'
CC_BASE_URL = 'https://min-api.cryptocompare.com/data/v2'
Beispiel #19
0
def insertNewCryptoData():
    # Read secret file
    dir_path = os.path.dirname(os.path.realpath(__file__))
    with open(dir_path + '/secrets.txt') as f:
        secret = f.readlines()
    secrets = [x.strip() for x in secret]

    client_id = secrets[0]
    client_secret = secrets[1]
    username = secrets[2]
    password = secrets[3]
    api_key_1 = secrets[4]
    api_key_2 = secrets[5]
    api_key_3 = secrets[6]
    api_key_4 = secrets[7]

    coinmarketcapAPI = [api_key_1, api_key_2, api_key_3, api_key_4]

    # Connect to CoinMarketCapAPI
    coinmarketcap = CoinMarketCapAPI(coinmarketcapAPI[0])
    crypto_listings = coinmarketcap.cryptocurrency_map().data
    cur_date = datetime.utcnow()

    crypto_list = []
    crypto_dict = {}
    crypto_slug_dict = {}
    crypto_slug_names = {}
    crypto_link_count_dict = {}
    crypto_link_dict = {}

    # exclude certain crypto
    crypto_exclude_dict = {
        'A': 0,
        'CAP': 0,
        'TOP': 0,
        'OK': 0,
        'ANY': 0,
        'CAN': 0,
        'JST': 0
    }

    for crypto_name in crypto_listings:
        crypto_symbol = crypto_name["symbol"]
        crypto_slug = crypto_name["slug"]
        if crypto_symbol.isalnum(
        ) and not crypto_symbol in crypto_exclude_dict:
            crypto_list.append(crypto_symbol)
            crypto_slug_dict[crypto_slug.lower()] = crypto_symbol
            crypto_slug_names[crypto_symbol] = crypto_slug
            crypto_dict[crypto_symbol] = 0
            crypto_link_count_dict[crypto_symbol] = 0
            crypto_link_dict[crypto_symbol] = ['', '']

    # Perform web scraping
    scrape_period = cur_date - timedelta(hours=6)

    # Connect to reddit API
    print("Scraping the web...")
    reddit = praw.Reddit(client_id='Vht-J5m9WtgOVQ',
                         client_secret=client_secret,
                         username=username,
                         password=password,
                         user_agent='crypto_scraper')

    dir_path = os.path.dirname(os.path.realpath(__file__))
    with open(dir_path + '/subreddits.txt') as f:
        content = f.readlines()
    subreddit_list = [x.strip() for x in content]

    # Obtain the string of all relevant posts
    post_list = []
    for subreddit_name in subreddit_list:
        subreddit = reddit.subreddit(subreddit_name)
        hot_topics = subreddit.hot(limit=1000)

        for submissions in hot_topics:
            if datetime.utcfromtimestamp(
                    submissions.created_utc) >= scrape_period:
                post_list.append([
                    submissions.title, submissions.score, submissions.permalink
                ])

    # Count mentions of each cryptos in posts
    for submission in post_list:
        topics = submission[0]
        upvotes = submission[1]
        url = 'https://www.reddit.com/' + str(submission[2])

        word_list = topics.split()
        for words in word_list:
            # strip words to alphanumeric (remove special characters)
            if not words.isalnum():
                words = ''.join(c for c in words if c.isalnum())

            if words in crypto_dict:
                crypto_dict[words] += upvotes
                if upvotes >= crypto_link_count_dict[words]:
                    crypto_link_count_dict[words] = upvotes
                    crypto_link_dict[words] = [url, topics]

            elif words.lower() in crypto_slug_dict:
                cor_symbol = crypto_slug_dict[words.lower()]
                crypto_dict[cor_symbol] += upvotes
                if upvotes >= crypto_link_count_dict[cor_symbol]:
                    crypto_link_count_dict[cor_symbol] = upvotes
                    crypto_link_dict[cor_symbol] = [url, topics]

    # Update the price and market cap for each crypto symbol
    print("Inserting Crypto Data...")
    i = 0
    api_counter = 0
    while i < len(crypto_list):
        if i + 1000 >= len(crypto_list):
            crypto_query_str = crypto_list[i:len(crypto_list)]
            i = len(crypto_list)

        else:
            crypto_query_str = crypto_list[i:i + 1000]
            i += 1000

        coinmarketcap = CoinMarketCapAPI(coinmarketcapAPI[api_counter])
        crypto_quotes = coinmarketcap.cryptocurrency_quotes_latest(
            symbol=str(','.join(crypto_query_str))).data

        api_counter += 1
        if api_counter >= len(coinmarketcapAPI):
            api_counter = 0

        for crypto_symbol in crypto_query_str:
            try:
                cur_price = round(
                    crypto_quotes[crypto_symbol]['quote']['USD']['price'], 9)
                cur_marketcap = round(
                    crypto_quotes[crypto_symbol]['quote']['USD']['market_cap'],
                    9)
                cur_vol = round(
                    crypto_quotes[crypto_symbol]['quote']['USD']['volume_24h'],
                    9)
                cur_percent_change_24h = round(
                    crypto_quotes[crypto_symbol]['quote']['USD']
                    ['percent_change_24h'], 5)
                cur_percent_change_1h = round(
                    crypto_quotes[crypto_symbol]['quote']['USD']
                    ['percent_change_1h'], 5)
                cur_count = crypto_dict[crypto_symbol]

                curCryptoDatabase = CryptoDatabase(
                    symbol=crypto_symbol,
                    slug=crypto_slug_names[crypto_symbol],
                    date=cur_date,
                    source='reddit',
                    count=cur_count,
                    popular_link=crypto_link_dict[crypto_symbol][0],
                    popular_content=crypto_link_dict[crypto_symbol][1],
                    price=cur_price,
                    marketcap=cur_marketcap,
                    volume_24h=cur_vol,
                    percent_change_24h=cur_percent_change_24h,
                    percent_change_1h=cur_percent_change_1h)
                # Save database
                curCryptoDatabase.save()

            except:
                print("invalid coin: ", crypto_symbol)

    return
import json
from pprint import pprint

from coinmarketcapapi import CoinMarketCapAPI

from private.keys import API_KEYS

cmc = CoinMarketCapAPI(API_KEYS['coinmarket']['api_key'])

r = cmc.cryptocurrency_listings_latest()
latest = [dict(d, prices=d['symbol']) for d in r.data]

pprint(r.data)

with open('../../public/dummy_data/cmc_latest.json', 'w') as f:
    f.write(json.dumps(r.data))

# r2 = cmc.cryptocurrency_quotes_historical(interval='daily', count=7)
#
# pprint(r2.data)
#
# with open('../../public/dummy_data/cmc_quotes_historical.json', 'w') as f:
#     f.write(json.dumps(r2.data))

Beispiel #21
0
def check_api_keys():
    """Check api keys and if they are supplied"""

    key_dict = {}
    if cfg.API_KEY_ALPHAVANTAGE == "REPLACE_ME":  # pragma: allowlist secret
        key_dict["ALPHA_VANTAGE"] = "Not defined"
    else:
        df = TimeSeries(
            key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas"
        ).get_intraday(symbol="AAPL")
        if df[0].empty:
            key_dict["ALPHA_VANTAGE"] = "defined, test failed"
        else:
            key_dict["ALPHA_VANTAGE"] = "defined, test passed"

    if cfg.API_KEY_FINANCIALMODELINGPREP == "REPLACE_ME":  # pragma: allowlist secret
        key_dict["FINANCIAL_MODELING_PREP"] = "Not defined"
    else:
        r = requests.get(
            f"https://financialmodelingprep.com/api/v3/profile/AAPL?apikey={cfg.API_KEY_FINANCIALMODELINGPREP}"
        )
        if r.status_code in [403, 401]:
            key_dict["FINANCIAL_MODELING_PREP"] = "defined, test failed"
        elif r.status_code == 200:
            key_dict["FINANCIAL_MODELING_PREP"] = "defined, test passed"
        else:
            key_dict["FINANCIAL_MODELING_PREP"] = "defined, test inconclusive"

    if cfg.API_KEY_QUANDL == "REPLACE_ME":  # pragma: allowlist secret
        key_dict["QUANDL"] = "Not defined"
    else:
        try:
            quandl.save_key(cfg.API_KEY_QUANDL)
            quandl.get_table(
                "ZACKS/FC",
                paginate=True,
                ticker=["AAPL", "MSFT"],
                per_end_date={"gte": "2015-01-01"},
                qopts={"columns": ["ticker", "per_end_date"]},
            )
            key_dict["QUANDL"] = "defined, test passed"
        except quandl.errors.quandl_error.ForbiddenError:
            key_dict["QUANDL"] = "defined, test failed"

    if cfg.API_POLYGON_KEY == "REPLACE_ME":
        key_dict["POLYGON"] = "Not defined"
    else:
        r = requests.get(
            f"https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/day/2020-06-01/2020-06-17?apiKey={cfg.API_POLYGON_KEY}"
        )
        if r.status_code in [403, 401]:
            key_dict["POLYGON"] = "defined, test failed"
        elif r.status_code == 200:
            key_dict["POLYGON"] = "defined, test passed"
        else:
            key_dict["POLYGON"] = "defined, test inconclusive"

    if cfg.API_FRED_KEY == "REPLACE_ME":
        key_dict["FRED"] = "Not defined"
    else:
        r = requests.get(
            f"https://api.stlouisfed.org/fred/series?series_id=GNPCA&api_key={cfg.API_FRED_KEY}"
        )
        if r.status_code in [403, 401, 400]:
            key_dict["FRED"] = "defined, test failed"
        elif r.status_code == 200:
            key_dict["FRED"] = "defined, test passed"
        else:
            key_dict["FRED"] = "defined, test inconclusive"

    if cfg.API_NEWS_TOKEN == "REPLACE_ME":
        key_dict["NEWSAPI"] = "Not defined"
    else:
        r = requests.get(
            f"https://newsapi.org/v2/everything?q=keyword&apiKey={cfg.API_NEWS_TOKEN}"
        )
        if r.status_code in [401, 403]:
            key_dict["NEWSAPI"] = "defined, test failed"
        elif r.status_code == 200:
            key_dict["NEWSAPI"] = "defined, test passed"
        else:
            key_dict["NEWSAPI"] = "defined, test inconclusive"

    if cfg.TRADIER_TOKEN == "REPLACE_ME":
        key_dict["TRADIER"] = "Not defined"
    else:
        r = requests.get(
            "https://sandbox.tradier.com/v1/markets/quotes",
            params={"symbols": "AAPL"},
            headers={
                "Authorization": f"Bearer {cfg.TRADIER_TOKEN}",
                "Accept": "application/json",
            },
        )
        if r.status_code in [401, 403]:
            key_dict["TRADIER"] = "defined, test failed"
        elif r.status_code == 200:
            key_dict["TRADIER"] = "defined, test passed"
        else:
            key_dict["TRADIER"] = "defined, test inconclusive"

    if cfg.API_CMC_KEY == "REPLACE_ME":
        key_dict["COINMARKETCAP"] = "Not defined"
    else:
        cmc = CoinMarketCapAPI(cfg.API_CMC_KEY)
        try:
            cmc.exchange_info()
            key_dict["COINMARKETCAP"] = "defined, test passed"
        except CoinMarketCapAPIError:
            key_dict["COINMARKETCAP"] = "defined, test failed"

    if cfg.API_FINNHUB_KEY == "REPLACE_ME":
        key_dict["FINNHUB"] = "Not defined"
    else:
        r = r = requests.get(
            f"https://finnhub.io/api/v1/quote?symbol=AAPL&token={cfg.API_FINNHUB_KEY}"
        )
        if r.status_code in [403, 401, 400]:
            key_dict["FINNHUB"] = "defined, test failed"
        elif r.status_code == 200:
            key_dict["FINNHUB"] = "defined, test passed"
        else:
            key_dict["FINNHUB"] = "defined, test inconclusive"

    if cfg.API_IEX_TOKEN == "REPLACE_ME":
        key_dict["IEXCLOUD"] = "Not defined"
    else:
        try:
            pyEX.Client(api_token=cfg.API_IEX_TOKEN, version="v1")
            key_dict["IEXCLOUD"] = "defined, test passed"
        except PyEXception:
            key_dict["IEXCLOUD"] = "defined, test failed"

    # Reddit
    reddit_keys = [
        cfg.API_REDDIT_CLIENT_ID,
        cfg.API_REDDIT_CLIENT_SECRET,
        cfg.API_REDDIT_USERNAME,
        cfg.API_REDDIT_PASSWORD,
        cfg.API_REDDIT_USER_AGENT,
    ]
    if "REPLACE_ME" in reddit_keys:
        key_dict["REDDIT"] = "Not defined"
    else:
        praw_api = praw.Reddit(
            client_id=cfg.API_REDDIT_CLIENT_ID,
            client_secret=cfg.API_REDDIT_CLIENT_SECRET,
            username=cfg.API_REDDIT_USERNAME,
            user_agent=cfg.API_REDDIT_USER_AGENT,
            password=cfg.API_REDDIT_PASSWORD,
        )

        try:
            praw_api.user.me()
            key_dict["REDDIT"] = "defined, test passed"
        except ResponseException:
            key_dict["REDDIT"] = "defined, test failed"

    # Twitter keys
    twitter_keys = [
        cfg.API_TWITTER_KEY,
        cfg.API_TWITTER_SECRET_KEY,
        cfg.API_TWITTER_BEARER_TOKEN,
    ]
    if "REPLACE_ME" in twitter_keys:
        key_dict["TWITTER"] = "Not defined"
    else:
        params = {
            "query": "(\\$AAPL) (lang:en)",
            "max_results": "10",
            "tweet.fields": "created_at,lang",
        }
        r = requests.get(
            "https://api.twitter.com/2/tweets/search/recent",
            params=params,  # type: ignore
            headers={"authorization": "Bearer " + cfg.API_TWITTER_BEARER_TOKEN},
        )
        if r.status_code == 200:
            key_dict["TWITTER"] = "defined, test passed"
        elif r.status_code in [401, 403]:
            key_dict["TWITTER"] = "defined, test failed"
        else:
            key_dict["TWITTER"] = "defined, test inconclusive"

    # Robinhood keys
    rh_keys = [cfg.RH_USERNAME, cfg.RH_PASSWORD]
    if "REPLACE_ME" in rh_keys:
        key_dict["ROBINHOOD"] = "Not defined"
    else:
        key_dict["ROBINHOOD"] = "defined, not tested"
    # Degiro keys
    dg_keys = [cfg.DG_USERNAME, cfg.DG_PASSWORD, cfg.DG_TOTP_SECRET]
    if "REPLACE_ME" in dg_keys:
        key_dict["DEGIRO"] = "Not defined"
    else:
        key_dict["DEGIRO"] = "defined, not tested"
    # OANDA keys
    oanda_keys = [cfg.OANDA_TOKEN, cfg.OANDA_ACCOUNT]
    if "REPLACE_ME" in oanda_keys:
        key_dict["OANDA"] = "Not defined"
    else:
        key_dict["OANDA"] = "defined, not tested"
    # Binance keys
    bn_keys = [cfg.API_BINANCE_KEY, cfg.API_BINANCE_SECRET]
    if "REPLACE_ME" in bn_keys:
        key_dict["BINANCE"] = "Not defined"
    else:
        key_dict["BINANCE"] = "defined, not tested"

    # SentimentInvestor keys
    si_keys = [cfg.API_SENTIMENTINVESTOR_KEY, cfg.API_SENTIMENTINVESTOR_TOKEN]
    if "REPLACE_ME" in si_keys:
        key_dict["SENTIMENT_INVESTOR"] = "Not defined"
    else:
        account = requests.get(
            f"https://api.sentimentinvestor.com/v4/account"
            f"?token={cfg.API_SENTIMENTINVESTOR_TOKEN}&key={cfg.API_SENTIMENTINVESTOR_KEY}"
        )
        if account.ok and account.json().get("success", False):
            key_dict["SENTIMENT_INVESTOR"] = "Defined, test passed"
        else:
            key_dict["SENTIMENT_INVESTOR"] = "Defined, test unsuccessful"

    print(
        tabulate(
            pd.DataFrame(key_dict.items()),
            showindex=False,
            headers=[],
            tablefmt="fancy_grid",
        ),
        "\n",
    )
Beispiel #22
0
 def __init__(self):
     self.ticker = CoinMarketCapAPI(coin_mkt_token)