Пример #1
0
def find_crypto_daily(ctx):
    """
    Finds all data on cryptocurrency of choice and displays data for that day.
    """

    # Check output format
    if (ctx.obj['GRAPH']):
        out = 'pandas'
    else:
        out = 'json'

    # Get data from API
    cc = CryptoCurrencies(key=apiKey, output_format=out)

    # Get object with the crypto data and another with  the call's metadata
    data, meta_data = cc.get_digital_currency_daily(symbol=crypto_symbol,
                                                    market=market)

    # Show data depending on output format
    # if(ctx.obj['GRAPH']):
    #     data['4b. close (USD)'].plot()
    # plt.tight_layout()
    # plt.title('Daily close value for bitcoin (BTC)')
    # plt.grid()
    # plt.show()
    # else:
    pprint(data)
Пример #2
0
def updateETH():
    conn = sqlite3.connect("data/crypto.db")
    cur = conn.cursor()
    cur.execute("select max(Date) from eth")
    results = cur.fetchone()
    # print(results[0])
    cc = CryptoCurrencies(key=akey, output_format='pandas')
    data, meta_data = cc.get_digital_currency_daily(symbol='ETH', market='EUR')
    data['Currency'] = 'ETH'
    data.reset_index(inplace=True)
    data.drop(['1a. open (EUR)', '2a. high (EUR)', '3a. low (EUR)','4a. close (EUR)'], axis=1, inplace=True)
    # print(data.columns.values.tolist())
    data.columns = ['Date','Open','High','Low','Close','Volume','MarketCap','Coin']
    data['Date']= pd.to_datetime(data['Date'])
    data.set_index('Date', inplace=True)
    data['200_MA'] = data['Close'].rolling('200D').mean()
    data['150_MA'] = data['Close'].rolling('150D').mean()
    data['50_MA'] = data['Close'].rolling('50D').mean()
    data['52W_High'] = data['Close'].rolling('365D').max()
    data['52W_Low'] = data['Close'].rolling('365D').min()
    data['Volatility']=(data['High']-data['Low'])/data['Open']
    data['Pct_Chg'] = (data['Close'] - data['Open'])/data['Open']
    data.drop('Coin', axis=1, inplace=True)
    eth_csv = data
    eth_csv.reset_index(inplace=True)
    eth_csv.to_csv('static/updated_csv/eth_current.csv', index=False)
    # print(data.head())
    selected = data.loc[:results[0]]
    #selected.reset_index(inplace=True)
    # print(selected.head())
    selected.to_sql('eth', conn, if_exists='append', index=False)
    con.close()
Пример #3
0
 def Init_Crypto_Currency_API_Alpha_Vantage(self , API_Key, Crypto_Currency , Market):
 
     cc = CryptoCurrencies(key=API_Key,output_format='pandas')
     
     self.Data, self.MetaData = cc.get_digital_currency_daily(Crypto_Currency,Market)
     self.Base = self.data['4a. close (USD)']
     self.DataSet = None
Пример #4
0
def save_digital_dataset(symbol, market):
    
    cc = CryptoCurrencies(key=api_key, output_format='pandas')
    
    data, meta_data = cc.get_digital_currency_daily(symbol, market)
    
    data.to_csv(f'./Crypto Data/{symbol}_daily')
Пример #5
0
 def getCurrentPrice(symbol, currency='Stock'):
     '''
     get current price for a given stock or cryptocurrency
     :param symbol: string of the desired stock or cryptocurrency
     :param currency: 'stock' or 'crypto'
     :return: (x,y) x is string with date and time, and y is stock value
     '''
     if currency == 'Stock':
         ts = TimeSeries(key=api_key, output_format='pandas')
         try:
             data, meta_data = ts.get_intraday(symbol,
                                               interval='1min',
                                               outputsize='compact')
         except KeyError:
             return None, None
         x = data.index.values[-1]  # get index values (dates)
         y = data.iloc[-1, 3]  # get third column which is closing price
         return x, y
     elif currency == 'Cryptocurrency':
         cc = CryptoCurrencies(key=api_key, output_format='pandas')
         try:
             data, meta_data = cc.get_digital_currency_daily(symbol,
                                                             market='USD')
         except KeyError:
             return None, None
         x = data.index.values[-1]  # get index values (dates)
         y = data.iloc[-1, 3]  # get third column which is closing price
         return x, y
Пример #6
0
    def getData(self, params):
        ticker = params['ticker']
        key = '' #insertkeyhere-for.ex-6CGJ8IWIR2UQ361H
        cc = CryptoCurrencies(key,output_format='pandas')
        df, meta = cc.get_digital_currency_daily(symbol=ticker,market='USD')

        #df= pd.read_csv('physical_currency_list.csv')
        return df
Пример #7
0
def get_crypto_data(crypto_symbol, market):

    cc = CryptoCurrencies(key=apiKey, output_format='json')

    # Get json object with the crypto data and another with  the call's metadata
    data, meta_data = cc.get_digital_currency_daily(symbol=crypto_symbol,
                                                    market=market)

    return data, meta_data
Пример #8
0
def crypto_currencies(key, symbol, market="CNY"):
    from alpha_vantage.cryptocurrencies import CryptoCurrencies
    import matplotlib.pyplot as plt

    cc = CryptoCurrencies(key=key, output_format="pandas")
    data, meta_data = cc.get_digital_currency_daily(symbol=symbol,
                                                    market=market)
    data["4b. close (USD)"].plot()
    plt.tight_layout()
    plt.title("Daily close value for bitcoin (BTC)")
    plt.grid()
    plt.show()
Пример #9
0
def GetCrypto(coin):
    '''
    :return: A pandas dataframe of the information from AlphaVantage
    '''

    # Using AlphaVantage https://alpha-vantage.readthedocs.io/en/latest/
    cc = CryptoCurrencies(key=ALPHA_API, output_format='pandas')
    data, meta_data = cc.get_digital_currency_daily(symbol=coin, market='USD')

    meta = None
    historical = read_latest(coin, parse_dates=True, errors='ignore')
    #set_trace()
    if historical is None:
        data, meta_data = cc.get_digital_currency_daily(symbol=coin, market='USD')
        data.rename(columns={'1a. open (USD)':OPEN_PRICE, '2a. high (USD)':DAY_HIGH,
                             '3a. low (USD)':DAY_LOW, '4a. close (USD)':DAY_CLOSE,
                             '5. volume':DAY_VOLUME,
                             '6. market cap (USD)':MARKET_CAP}
                    ,inplace=True)
        data = data[[OPEN_PRICE, DAY_HIGH, DAY_LOW, DAY_CLOSE, DAY_VOLUME, MARKET_CAP]]
        write_data(data, coin)
        ticker_data=data
    else:
        #set_trace()
        # If we have old data, then we'll go back to the source and get new data
        print(relativedelta(pd.to_datetime(historical.index[-1]), TODAY).days)
        if relativedelta(pd.to_datetime(historical.index[-1]), TODAY).days != 0:
            last_100, meta = cc.get_digital_currency_daily(symbol=coin, market='USD')
            last_100.rename(columns={'1a. open (USD)':OPEN_PRICE, '2a. high (USD)':DAY_HIGH,
                                     '3a. low (USD)':DAY_LOW, '4a. close (USD)':DAY_CLOSE,
                                     '5. volume':DAY_VOLUME,
                                     '6. market cap (USD)':MARKET_CAP}
                            ,inplace=True)
            last_100 = last_100[[OPEN_PRICE, DAY_HIGH, DAY_LOW, DAY_CLOSE, DAY_VOLUME, MARKET_CAP]]
            ticker_data = historical.append(last_100)
            ticker_data.drop_duplicates(inplace=True)
            write_data(ticker_data, coin)
        else:
            ticker_data = historical
    return ticker_data
Пример #10
0
class CheckingStockPrice:
    def __init__(self, args):
        self.args = args
        #self.ts = TimeSeries(key=self.args.api_key, output_format='pandas')
        self.cc = CryptoCurrencies(key=self.args.api_key,
                                   output_format='pandas')
        self.daily_data, self.meta_data = self.cc.get_digital_currency_daily(
            symbol='ETC', market='USD')
        print('reached here')
        # pass

    def get_excel_sheet(self):
        i = 1
        while i is 1:
            self.data.to_excel('/Users/christianalcala/desktop/microsoft.xlsx')
            time.sleep(60)
Пример #11
0
def cryptocurrency(API_key='Z6P4MY41TAIKFAXW', currency="BTC"):
  print("########PROCESSING#########")
  from alpha_vantage.cryptocurrencies import CryptoCurrencies
  import matplotlib.pyplot as plt
  import mplfinance as mpf

  cc=CryptoCurrencies(key=API_key,output_format='pandas')
  data=cc.get_digital_currency_daily(symbol=currency, market='INR')[0]

  data.columns = ['Open','_Open','High','_High','Low','_Low','Close','_Close','Volume','Market Cap']
  data.index.name = "Date"
  mpf.plot(data,
          type='candle', 
          title=f'Daily Time series for the {currency} cryptocurrency',
          mav=(20), 
          volume=True, 
          tight_layout=True,
          style='yahoo')
  return data
Пример #12
0
def cryptocurrency(API_key, currency):
  from alpha_vantage.cryptocurrencies import CryptoCurrencies
  import matplotlib.pyplot as plt

  cc=CryptoCurrencies(key=API_key,output_format='pandas')
  option=input('1. Exchange Rates\n2. Health Index\n3. Daily\n4. Weekly\n5. Monthly\n').lower()

  if option=='exchange rates' or option=='1':
    data=cc.get_currency_exchange_rate(from_currency=currency, to_currency='USD')[0]
    return data

  elif option=='health index' or option=='2':
    data=cc.get_crypto_rating(symbol=currency)[0]
    return data

  elif option=='daily' or option=='3':
    data=cc.get_digital_currency_daily(symbol=currency, market='CNY')[0]
    data.plot()
    plt.title(f'Crypto Daily for the {currency} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data

  elif option=='weekly' or option=='4':
    data=cc.get_digital_currency_weekly(symbol=currency, market='CNY')[0]
    data.plot()
    plt.title(f'Crypto Weekly for the {currency} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data

  elif option=='monthly' or option=='5':
    data=cc.get_digital_currency_monthly(symbol=currency, market='CNY')[0]
    data.plot()
    plt.title(f'Crypto Monthly for the {currency} stock')
    plt.tight_layout()
    plt.grid()
    plt.show()
    return data
  else:
    print("DATA NOT AVAILABLE")
Пример #13
0
def load_cryptocurrency_data(api_key,params):
    for k, v in Cryptocurrencies["From_Currency"].items():
        conn = None
        try:
            conn = psycopg2.connect(**params)
            cur = conn.cursor()
            cr = CryptoCurrencies(key=api_key)
            data, meta_data = cr.get_digital_currency_daily(symbol=v,
                                                            market=Cryptocurrencies["To_Currency"]["Indian Rupee"])
            for key, value in data.items():
                Last_Refreshed = key,
                Time_Zone = meta_data['7. Time Zone'],
                Digital_Currency_Code = v,
                Digital_Currency_Name = k,
                Market_Code = Cryptocurrencies["To_Currency"]["Indian Rupee"],
                Market_Name = "Indian Rupee",
                Open_INR = value['1a. open (INR)']
                Open_USD = value['1b. open (USD)']
                High_INR = value['2a. high (INR)']
                High_USD = value['2b. high (USD)']
                Low_INR = value['3a. low (INR)']
                Low_USD = value['3b. low (USD)']
                Close_INR = value['4a. close (INR)']
                Close_USD = value['4b. close (USD)']
                Volume = value['5. volume']
                Market_CAP = value['6. market cap (USD)']
                cur.execute(
                    "Insert into Cryptocurrency_Data_Daily values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                    (Last_Refreshed, Time_Zone, Digital_Currency_Code, Digital_Currency_Name,
                     Market_Code, Market_Name, Open_INR, Open_USD, High_INR, High_USD, Low_INR, Low_USD,
                     Close_INR, Close_USD, Volume, Market_CAP
                     )
                    )
            conn.commit()
        except ValueError:
            print(
                "Calling Cryptocurrency Data but execeeded number of calls per min,\nSo will call rest of the symbols after 60 seconds\n")
            time.sleep(60)
        finally:
            if conn is not None:
                conn.close()
Пример #14
0
    def download_data(self, criptocoin='BTC', currency='EUR'):
        # Alpha Vantage API
        api_key = "J41D51QYZT0JLZ99"
        # This API outputs a dataframe with the open, low, high and close values in the "market" currency
        # daily for the whole historical record. Also gives same values for USD and the volume and market capitalization
        # in USD.
        cc = CryptoCurrencies(key=api_key, output_format='pandas')
        data, _ = cc.get_digital_currency_daily(symbol=criptocoin,
                                                market=currency)

        data = data.rename(
            columns={
                "3a. low (EUR)": "low",
                "2a. high (EUR)": "high",
                "1a. open (EUR)": "open",
                "4a. close (EUR)": "close",
                "5. volume": "volume"
            })

        # Keep only the "close" and "volume" columns
        self.data = data[["close", "volume"]]
Пример #15
0
def get_bitcoin():
    cc = CryptoCurrencies(key='YOUR_API_KEY', output_format='pandas')
    data_btc, meta_data = cc.get_digital_currency_daily(symbol='BTC',
                                                        market='CNY')
    data_btc = data_btc.reset_index()
    data_btc = data_btc.drop(data_btc.index[100:1000], 0)
    data_btc_x = data_btc.drop(labels=[
        "1a. open (CNY)", "1b. open (USD)", "2a. high (CNY)", "2b. high (USD)",
        "3a. low (CNY)", "3b. low (USD)", "4a. close (CNY)", "4b. close (USD)",
        "5. volume", "6. market cap (USD)"
    ],
                               axis=1)
    data_btc_x = pd.to_datetime(data_btc_x["date"].unique()).tolist()

    data_btc_y = data_btc.drop(labels=[
        "date", "1a. open (CNY)", "1b. open (USD)", "2a. high (CNY)",
        "2b. high (USD)", "3a. low (CNY)", "3b. low (USD)", "4a. close (CNY)",
        "5. volume", "6. market cap (USD)"
    ],
                               axis=1)
    data_btc_y = data_btc_y.rename(columns={"4b. close (USD)": "Close"})
    data_btc_y = data_btc_y["Close"].values.tolist()

    return data_btc_x, data_btc_y
Пример #16
0
class REST(object):

    def __init__(self, api_key):
        self._api_key = get_alpha_vantage_credentials(api_key)
        self._session = requests.Session()
        self._timeseries = TimeSeries(key=self._api_key)
        self._cryptocurrencies = CryptoCurrencies(key=self._api_key)
        self._foreignexchange = ForeignExchange(key=self._api_key)
        self._sectorperformance = SectorPerformances(key=self._api_key)
        self._techindicators = TechIndicators(key=self._api_key)

    def _request(self, method, params=None):
        url = 'https://www.alphavantage.co/query?'
        params = params or {}
        params['apikey'] = self._api_key
        resp = self._session.request(method, url, params=params)
        resp.raise_for_status()
        return resp.json()

    def get(self, params=None):
        ''' Customizable endpoint, where you can pass all 
        keywords/paramters from the documentation:
        https://www.alphavantage.co/documentation/#

        Returns:
            pandas, csv, or json
        '''
        return self._request('GET', params=params)

    def historic_quotes(self, symbol, adjusted=False, outputsize='full', cadence='daily', output_format=None):
        ''' Returns the one of the TIME_SERIES_* endpoints of the Alpha Vantage API.

        Params:
            symbol: The ticker to return
            adjusted: Return the adjusted prices
            cadence: Choose between ['daily', 'weekly', 'monthly'], to return the cadence
            output_format: Choose between['json', 'csv', 'pandas']

        Returns:
            pandas, csv, or json
        '''
        if output_format:
            self._timeseries.output_format = output_format
        if cadence == 'daily':
            data, _ = self._timeseries.get_daily_adjusted(
                symbol=symbol, outputsize=outputsize) if adjusted else self._timeseries.get_daily(symbol=symbol, outputsize=outputsize)
        if cadence == 'weekly':
            data, _ = self._timeseries.get_weekly_adjusted(
                symbol=symbol) if adjusted else self._timeseries.get_weekly(symbol=symbol)
        if cadence == 'monthly':
            data, _ = self._timeseries.get_monthly_adjusted(
                symbol=symbol) if adjusted else self._timeseries.get_monthly(symbol=symbol)
        return data

    def intraday_quotes(self, symbol, interval='5min', outputsize='full', output_format=None):
        ''' Returns the TIME_SERIES_INTRADAY endpoint of the Alpha Vantage API.

        Params:
            symbol: The ticker to return
            interval: Choose between['1min', '5min', '15min', '30min', '60min']
            output_format: Choose between['json', 'csv', 'pandas']

        Returns:
            pandas, csv, or json
        '''
        if output_format:
            self._timeseries.output_format = output_format
        data, _ = self._timeseries.get_intraday(
            symbol=symbol, interval=interval, outputsize=outputsize)
        return data

    def current_quote(self, symbol):
        ''' Returns the GLOBAL_QUOTE endpoint
        of the Alpha Vantage API.

        Params:
            symbol: The ticker to return
            output_format: Choose between['json', 'csv', 'pandas']

        Returns:
            pandas, csv, or json
        '''
        data, _ = self._timeseries.get_quote_endpoint(symbol=symbol)
        return data

    def last_quote(self, symbol):
        return self.current_quote(symbol)

    def company(self, symbol, datatype='json'):
        return self.search_endpoint(symbol, datatype=datatype)

    def search_endpoint(self, keywords, datatype='json'):
        '''Search endpoint returns a list of possible companies
        that correspond to keywords

        Params:
            datatype: csv, json, or pandas
            keywords: ex. keywords=microsoft

        Returns:
            pandas, csv, or json
        '''
        params = {'function': 'SYMBOL_SEARCH',
                  'keywords': keywords, 'datatype': datatype}
        return self.get(params)

    def historic_fx_quotes(self, from_symbol, to_symbol, outputsize='full', cadence='daily', output_format=None):
        ''' Returns the one of the FX_* endpoints of the Alpha Vantage API.

        Params:
            from_currency: The symbol to convert
            to_currency: The symbol to convert to
            cadence: Choose between ['daily', 'weekly', 'monthly'], to return the cadence
            output_format: Choose between['json', 'csv', 'pandas']

        Returns:
            pandas, csv, or json
        '''
        if output_format:
            self._foreignexchange.output_format = output_format
        if cadence == 'daily':
            data, _ = self._foreignexchange.get_currency_exchange_daily(
                from_symbol=from_symbol, to_symbol=to_symbol, outputsize=outputsize)
        if cadence == 'weekly':
            data, _ = self._foreignexchange.get_currency_exchange_weekly(
                from_symbol=from_symbol, to_symbol=to_symbol, outputsize=outputsize)
        if cadence == 'monthly':
            data, _ = self._foreignexchange.get_currency_exchange_monthly(
                from_symbol=from_symbol, to_symbol=to_symbol, utputsize=outputsize)
        return data

    def intraday_fx_quotes(self, from_symbol, to_symbol, interval='5min', outputsize='full', output_format=None):
        ''' Returns the FX_INTRADAY endpoint of the Alpha Vantage API.

        Params:
            from_currency: The symbol to convert
            to_currency: The symbol to convert to
            interval: Choose between['1min', '5min', '15min', '30min', '60min']
            output_format: Choose between['json', 'csv', 'pandas']

        Returns:
            pandas, csv, or json
        '''
        if output_format:
            self._foreignexchange.output_format = output_format
        data, _ = self._foreignexchange.get_currency_exchange_intraday(
            from_symbol=from_symbol, to_symbol=to_symbol, interval=interval, outputsize=outputsize)
        return data

    def exchange_rate(self, from_currency, to_currency):
        ''' Returns the exchange rate of two currencies, digital or physical.
        CURRENCY_EXCHANGE_RATE endpoint of the Alpha Vantage API

        Params:
            from_currency: The symbol to convert
            to_currency: The symbol to convert to

        Returns:
            json
        '''
        params = {'function': "CURRENCY_EXCHANGE_RATE",
                  'from_currency': from_currency, 'to_currency': to_currency}
        data = self.get(params)
        return data

    def historic_cryptocurrency_quotes(self, symbol, market, cadence='daily', output_format=None):
        ''' Returns the one of the DIGITAL_CURRENCY_* endpoints of the Alpha Vantage API.

        Params:
            symbol: The cryptocurrency to return
            market: The market it's being sold on
            cadence: Choose between ['daily', 'weekly', 'monthly'], to return the cadence
            output_format: Choose between['json', 'csv', 'pandas']

        Returns:
            pandas, csv, or json
        '''
        if output_format:
            self._cryptocurrencies.output_format = output_format
        if cadence == 'daily':
            data, _ = self._cryptocurrencies.get_digital_currency_daily(
                symbol=symbol, market=market)
        if cadence == 'weekly':
            data, _ = self._cryptocurrencies.get_digital_currency_weekly(
                symbol=symbol, market=market)
        if cadence == 'monthly':
            data, _ = self._cryptocurrencies.get_digital_currency_monthly(
                symbol=symbol, market=market)
        return data

    def techindicators(self, techindicator='SMA', output_format='json', **kwargs):
        ''' Returns the one of the technical indicator endpoints of the Alpha Vantage API.

        Params:
            techindicator: The technical indicator of choice
            params: Each technical indicator has additional optional parameters

        Returns:
            pandas, csv, or json
        '''
        if output_format:
            self._techindicators.output_format = output_format
        params = {'function': techindicator}
        for key, value in kwargs.items():
            params[key] = value
        data = self.get(params)
        return data

    def sector(self):
        ''' Returns the sector performances

        Returns:
            pandas, csv, or json
        '''
        data, _ = self._sectorperformance.get_sector()
        return data
Пример #17
0
from alpha_vantage.cryptocurrencies import CryptoCurrencies

#Notice instead of TimeSeries, we use CryptoCurrencies instead
av_gmail_cryptocurrency_credentials = CryptoCurrencies(key='YOUR_API_KEY',
                                                       output_format='pandas')

cryptocurrency_list = sorted(['BTC', 'ETH', 'LTC', 'XLM'])

cryptocurrency_open_list = []
cryptocurrency_high_list = []
cryptocurrency_low_list = []
cryptocurrency_close_list = []
cryptocurrency_volume_list = []

for ticker in cryptocurrency_list:
    tupledf1 = av_gmail_cryptocurrency_credentials.get_digital_currency_daily(
        symbol=ticker, market='USD')
    df1 = tupledf1[0]
    df2 = df1[[
        '1a. open (USD)', '2a. high (USD)', '3a. low (USD)', '4a. close (USD)',
        '5. volume'
    ]]
    df3 = df2.reset_index()

    df3['date'] = pd.to_datetime(df3['date']).dt.strftime('%Y-%m-%d')
    df3.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
    df4 = df3.set_index('Date')
    df5 = df4.sort_index(ascending=True)
    df6 = df5.add_prefix(ticker + ' ')

    dfcryptocurrencyopendata = df6[ticker + ' Open']
    dfcryptocurrencyhighdata = df6[ticker + ' High']
Пример #18
0
def getCrypto(bot, update, args):

    try:
        # The args contain the crypto name
        cryptoName = " ".join(args).upper()

        # Call the constructor of the Alphavantage API wrapper
        cc = CryptoCurrencies(key=alphaVantage_apiKey, output_format='pandas')

        # Calls the method to fetch intraday prices
        data, meta_data = cc.get_digital_currency_intraday(cryptoName,
                                                           market='USD')

        #Plotting the close values
        data['1a. price (USD)'].plot()
        # To show all of the graph, since crypto prices can spike a lot
        plt.tight_layout()
        plt.grid()

        #Setting the Graph title
        plotTitle = 'Intraday price for {}'.format(cryptoName)
        plt.title(plotTitle)

        # Using a Python Util called Temporary file in order to convert the graph into a file object
        #tmpfile = tempfile.TemporaryFile(suffix=".png")
        tmpfile = BytesIO()
        plt.savefig(tmpfile, format="png")
        tmpfile.seek(0)
        img = tmpfile

        # Calls the method to fetch daily prices
        data, meta_data = cc.get_digital_currency_daily(cryptoName,
                                                        market='USD')
        dataList = data.iloc[-1]

        openUSD = dataList['1a. open (USD)']
        highUSD = dataList['2a. high (USD)']
        lowUSD = dataList['3a. low (USD)']
        closeUSD = dataList['4a. close (USD)']
        volume = dataList['5. volume']
        marketCapUSD = dataList['6. market cap (USD)']

        message = '''
         <b> {} </b> 
         \n Open: <em>${}</em>
         \n Close: <em>${}</em>
         \n High: <em>${}</em>
         \n Low: <em>${}</em>
         \n Volume: <em>{}</em>
         \n Market Cap: <em>${}</em> 
        '''.format(cryptoName, openUSD, highUSD, lowUSD, closeUSD, volume,
                   marketCapUSD)

        update.message.reply_photo(img)
        plt.close()

        # Sends the above formatted message to the user
        update.message.reply_html(message)

    except Exception as e:
        # Catches the exception and prints the stack trace
        logging.exception("message")
        message = '''You probably used the incorrect format for the command.\nUse <pre>/crypto <pre>'companyName' </pre>\nFor more info, please check /help'''
        # If any exception, send the message showing the frequent cause of exception
        update.message.reply_html(message)
Пример #19
0
ti = TechIndicators(key=mykey, output_format='pandas')
data, meta_data = ti.get_bbands(symbol=myticker, time_period=20)
data.tail(252).plot()  # Plot last year only.
plt.title('BBbands indicator for ' + myticker)
plt.show()

# Sector performance.
sp = SectorPerformances(key=mykey, output_format='pandas')
data, meta_data = sp.get_sector()
data['Rank G: Year Performance'].plot(kind='bar')
plt.title('Sector Performance (Year)')
plt.tight_layout()
plt.grid()
plt.show()

# Crypto currencies.
cc = CryptoCurrencies(key=mykey, output_format='pandas')
data, meta_data = cc.get_digital_currency_daily(symbol='BTC', market='CNY')
data['4b. close (USD)'].plot(logy=True)
plt.tight_layout()
plt.title('Daily Value for Bitcoin (BTC)')
plt.grid()
plt.show()

# Foreign exchange data is only available as JSON format (not in CSV
# or Pandas format). There's also no metadata in this call (so we just
# use a placeholder `_`).
cc = ForeignExchange(key=mykey)
data, _ = cc.get_currency_exchange_rate(from_currency='EUR', to_currency='USD')
pprint(data)
Пример #20
0

# #### Get api key by accessing to 'https://www.alphavantage.co/support/#api-key'

# In[3]:


# Api key given
api_key = '9YUGBQ4SDSM881A2'


# In[4]:


btc = CryptoCurrencies(key=api_key, output_format='pandas')
data_btc, meta_data_btc = btc.get_digital_currency_daily(symbol='BTC', market='CNY')

eth = CryptoCurrencies(key=api_key,output_format='pandas')
data_eth, meta_data_eth = eth.get_digital_currency_daily(symbol='ETH', market='CNY')


# In[5]:


df1 = data_btc['4b. close (USD)']
df2 = data_eth['4b. close (USD)']

total_df = pd.concat([df1, df2], axis=1)
print(total_df)

Пример #21
0
from alpha_vantage.cryptocurrencies import CryptoCurrencies

stocks_up = True
bot_startup = int(time.time())
STOCK_API = os.environ["STOCK_API"]

try:
    ts = TimeSeries(STOCK_API, output_format='pandas')
    crypto = CryptoCurrencies(STOCK_API, output_format='pandas')

    mlly, columns = ts.get_daily(symbol='AAPL')
    bngr, columns = ts.get_daily(symbol='TSLA')
    ytl, columns = ts.get_daily(symbol='LYFT')
    clyn, columns = ts.get_daily(symbol='FB')

    btc, columns = crypto.get_digital_currency_daily(symbol='BTC',
                                                     market='CAD')

except:
    stocks_up = False
    print(
        'Stock API reached its limit, wait a minute and try again (5 calls/minute, 500 calls/day)'
    )

os.chdir('C:\\Users\\fares\\Desktop\\Discord Bots\\MellyBot 2.0\\cogs')

mainshop = [{
    'name': 'MellyCoin',
    'emoji': ':coin:',
    'price': 10,
    'description': 'Just a prop'
}, {
Пример #22
0
 def fetch(self, symbol, conf):
     cc = CryptoCurrencies(key=AV_API_KEY, output_format='pandas')
     df, meta_data = cc.get_digital_currency_daily(symbol=symbol.name, market='USD')
     df.index = pd.to_datetime(df.index, format="%Y-%m-%d")
     return df
Пример #23
0
def main():

    if not os.path.exists(data_path + function):
        os.mkdir(data_path + function)

    refresh = []
    for symbol in symbols:
        if os.path.exists(data_path + function + '\\' + symbol + '.csv'):
            filestatsobj = os.stat(data_path + function + '\\' + symbol +
                                   '.csv')
            modified_time = time.ctime(filestatsobj[stat.ST_MTIME])
            print('File:          ', str(symbol))
            print('Modified Time: ', modified_time)
            time_dif = datetime.now() - pd.to_datetime(modified_time)
            print('File Age:      ', time_dif)
            if time_dif > dt.timedelta(hours=age):
                refresh.append(symbol)
        else:
            refresh.append(symbol)

    i = 0
    missing_downloads = []
    print('Downloading %s Files' % len(refresh))
    while i <= len(refresh) & (len(refresh) - i > 0):
        for symbol in refresh:
            try:
                if function == 'TIME_SERIES_INTRADAY':
                    if not os.path.exists(data_path + function + '\\' +
                                          interval):
                        os.mkdir(data_path + function + '\\' + interval)

                    file_to_save = data_path + function + '\\' + interval + '\\' + symbol + '.csv'
                    ts = TimeSeries(key=api_key, output_format='pandas')
                    data, meta_data = ts.get_intraday(symbol=symbol,
                                                      interval=interval,
                                                      outputsize=outputsize)
                    data['date'] = data.index
                    data.index = list(range(0, len(data.index)))
                    data = data[[
                        'date', '1. open', '2. high', '3. low', '4. close',
                        '5. volume'
                    ]]

                    if os.path.exists(data_path + function + '\\' + interval +
                                      '\\' + symbol + '.csv'):
                        temp_df = pd.read_csv(data_path + function + '\\' +
                                              interval + '\\' + symbol +
                                              '.csv')
                        temp_df = temp_df[[
                            'date', '1. open', '2. high', '3. low', '4. close',
                            '5. volume'
                        ]]
                        data = data.append(temp_df)
                        data.drop_duplicates(inplace=True)
                        data = data.sort_index()
                        data.to_csv(file_to_save)
                        print('Data saved to : %s' % file_to_save)

                    else:
                        data.to_csv(file_to_save)
                        print('Data saved to : %s' % file_to_save)

                elif function == 'TIME_SERIES_DAILY_ADJUSTED':
                    file_to_save = data_path + function + '\\' + symbol + '.csv'
                    ts = TimeSeries(key=api_key, output_format='pandas')
                    data, meta_data = ts.get_daily_adjusted(
                        symbol=symbol, outputsize=outputsize)
                    data.to_csv(file_to_save)
                    print('Data saved to : %s' % file_to_save)

                elif function == 'DIGITAL_CURRENCY_DAILY':
                    file_to_save = data_path + function + '\\' + symbol + '.csv'
                    cc = CryptoCurrencies(key=api_key2, output_format='pandas')
                    data, meta_data = cc.get_digital_currency_daily(
                        symbol=symbols, market=market)
                    data.to_csv(file_to_save)
                    print('Data saved to : %s' % file_to_save)

                else:
                    print('Edit Code for new data')

                i += 1
                if i == len(refresh):
                    pass
                if (i % 5 == 0):
                    print('Waiting %s seconds' % wait)
                    print('%s Completed, %s Remain' % (i, (len(refresh)) - i))
                    print(str(datetime.now()))
                    print('Approximately %s Minutes Until Complete' %
                          str(round((len(refresh) - i) / 5 * wait / 60, 1)))
                    time.sleep(wait)
                else:
                    pass

            except ValueError:
                print(str(symbol), ' Not Found')
                missing_downloads.append(symbol)
            except KeyError:
                print('Keyerror, waiting %s seconds' % '10')
                time.sleep(10)

    print('Download Complete')
    print('Missing Symbols: ', missing_downloads)

    names, df_list, missing = [], [], []
    for symbol in symbols:
        names.append(symbol)
        try:
            n = pd.read_csv(data_path + function + '\\' + symbol + '.csv')
            df_list.append(n)
        except FileNotFoundError:
            print(str(symbol), ' is missing.')
            missing.append(symbol)

    names.sort()
    print(names, 'Loaded')
    print(missing, 'Missing')

    tickers = []
    for x, y in zip(names, df_list):
        globals()[x] = y
        tickers.append(globals()[x])

    missing_downloads = pd.DataFrame(missing_downloads)
    missing_downloads.to_csv(data_path + function + '\\' + 'missing.csv')
Пример #24
0
from analysis import *
from config import *
import matplotlib.pyplot as plt
import pandas as pd


def formatCryptoData(data):
    df = pd.DataFrame(data)
    cols = [i.split(' ')[1] for i in df.columns]
    df.columns = cols
    return df.T.drop_duplicates().T


if __name__ == '__main__':
    api = CryptoCurrencies(AV_API_KEY, output_format='pandas')
    bData = api.get_digital_currency_daily(symbol='BTC', market='USD')[0]
    tData = api.get_digital_currency_daily(symbol='XTZ', market='USD')[0]
    btc = formatCryptoData(bData)
    xtz = formatCryptoData(tData)
    bAverage = averagePrice(btc['open'], btc['high'], btc['low'], btc['close'])
    tAverage = averagePrice(xtz['open'], xtz['high'], xtz['low'], xtz['close'])
    ratio = bAverage / tAverage

    plt.figure(0)
    plt.title('Bitcoin/Tezos Daily (USD-Derived)')
    plt.xlabel('Date')
    plt.ylabel('Ratio')
    plt.grid()
    plt.plot(ratio, label='BTC/XTZ')
    plt.plot(sma(ratio, 100), '--', label='100-SMA')
    plt.legend()
Пример #25
0
from alpha_vantage.cryptocurrencies import CryptoCurrencies

cc = CryptoCurrencies(key='XNPHCZ8ACJ6PW4T6')
data, meta_data = cc.get_digital_currency_intraday(symbol='XRP', market='USD')

dailyData, dailyMetaData = cc.get_digital_currency_daily(symbol='XRP',
                                                         market='USD')

print(dailyData)

# data['1b. price (USD)'].plot()
# plt.tight_layout()
# plt.title('Intraday value for ripple (XRP)')
# plt.grid()
# plt.show()
Пример #26
0
def Request(crypto, moeda):
    cc = CryptoCurrencies(key='3DEMOuwu', output_format='json')
    data, metadata = cc.get_digital_currency_daily(symbol=crypto, market = moeda)
    return data, metadata
Пример #27
0
class app:
    def __init__(self):
        self.root = Tk()
        self.root.title("Crypto Graph")
        self.root.geometry("1070x800")
        self.root.configure(background="light green")
        self.used_symbolsC = pickle.load(open("symbolsC", "rb"))
        self.usedsymbolsM = pickle.load(open("markets", "rb"))
        self.cc = CryptoCurrencies(key='YOUR_API_KEY', output_format='pandas')
        self.actv = False

        self.fig = Figure()
        self.ax1 = self.fig.add_subplot(111)
        self.ax1.grid()

        self.canvas = FigureCanvasTkAgg(self.fig, master=self.root)
        self.canvas.draw()

        self.toolbar = NavigationToolbar2Tk(self.canvas, self.root)
        self.toolbar.update()
        self.canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=1)

        self.labelSym = Label(self.root,
                              text="Symbol:",
                              bg="light green",
                              width=8,
                              height=2)
        self.labelSym.pack(side=LEFT)

        self.entry = ttk.Combobox(self.root, width=8)
        self.entry["values"] = self.used_symbolsC
        self.entry.pack(side=LEFT)

        self.labelMarket = Label(self.root,
                                 text="Market:",
                                 bg="light green",
                                 width=8,
                                 height=2)
        self.labelMarket.pack(side=LEFT)
        self.entryMarket = ttk.Combobox(self.root, width=8)
        self.entryMarket["values"] = self.usedsymbolsM
        self.entryMarket.pack(side=LEFT)
        self.btnTable = Button(self.root, text="SHOW TABLE", height=1)
        self.btnTable.pack(side=RIGHT)
        self.btnGraph = Button(self.root,
                               text="SHOW GRAPH",
                               height=1,
                               command=self.activate)
        self.btnGraph.pack(side=RIGHT)

        ani = animation.FuncAnimation(self.fig,
                                      self.representation,
                                      interval=1000)

        self.root.mainloop()

    def draw_graph(self):
        self.ax1.clear()
        self.ax1.grid()
        data, meta_data = (self.cc.get_digital_currency_daily(
            symbol=self.entry.get(), market=self.entryMarket.get()))

        self.ax1.plot(data['4b. close (USD)'])
        self.actv = False

    def representation(self, i):
        if self.actv == True:
            self.draw_graph()

    def activate(self):
        self.actv = True
ti=TechIndicators(key=free_api_key, output_format='pandas')

sma=ti.get_sma('MSFT',interval='daily',time_period=50)[0]

bbands=ti.get_bbands('MSFT',interval='daily',time_period=50)[0]

# add close price to bollinger bands df (want to adadjusted!!)
bbands['close']=close.iloc[:,0]


macd=ti.get_macd('MSFT',interval='daily')[0]

# currencies
# supports 150 currencies

fx=ForeignExchange(key=free_api_key, output_format='pandas')

eurusd=fx.get_currency_exchange_daily('EUR','USD',outputsize='full')[0]

#intraday
fx.get_currency_exchange_intraday('EUR','USD', interval='1min', outputsize='full')[0]

# cryptocurrencies more than 500 supported
cc=CryptoCurrencies(key=free_api_key, output_format='pandas')


VTC= cc.get_digital_currency_daily(symbol='BTC',market='USD')
BTC[1]
BTC[0
Пример #29
0
def create_line_chart(user_doc):
    """
    This function creates a line chart for the user's wallet performance. It querries
    the user's wallet and calls the API Alpha Vantage in order to get historical data
    of those specific cryptocurrencies. The values are filtered to only those 
    after the coins have been purchased for the first time. For simplicity purposes, 
    it assumes A CONSTANT TICKER DURING THE WHOLE TIME PERIOD. 

    """

    # Alpha Vantage
    Alpha_Vantage_Key = os.getenv("ALPHAVANTAGE_API_KEY")
    cc = CryptoCurrencies(Alpha_Vantage_Key)

    # Fetching historical data for specific coins in user's wallet
    user_wallet = user_doc['wallet']
    wallet_coins = user_wallet['coins']
    coins_obj = {}
    for coin, obj in wallet_coins.items():
        symbol = coin.replace('USDT', '')
        coins_obj[coin] = {}
        ticker = obj['total_ticker']
        coins_obj[coin]['ticker'] = ticker
        start_date = pd.to_datetime(obj['transactions'][0]['date'])
        coins_obj[coin]['coin_name'] = obj['transactions'][0]['name']
        coins_obj[coin]['start_date'] = start_date

        #API Call for every coin in wallet, market is set to United States US$
        cc_data, meta_data = cc.get_digital_currency_daily(symbol=symbol,
                                                           market='USD')

        filter_data = {}
        for date, data in cc_data.items():
            date = pd.to_datetime(date)
            # Filter only relevant values by date and calculate total value
            if date >= start_date:
                filter_data[date] = float(data['4b. close (USD)']) * ticker
        coins_obj[coin]['historical_data'] = filter_data

    # Plotly line chart initiation
    figure = go.Figure()

    # Add data to figure
    for coin, info in coins_obj.items():
        historical_data = info['historical_data']
        coin_name = info['coin_name']
        labels = []
        values = []
        for time, value in historical_data.items():
            labels.append(time)
            values.append(value)
        trace = go.Scatter(x=labels, y=values, mode='lines', name=coin_name)
        figure.add_trace(trace)

    # Edit the layout
    figure.update_layout(title='My CryptoWallet Performance',
                         xaxis_title='Month',
                         yaxis_title='Total value (US$)')

    # Json the data to be parsed later onto the html template.
    graphJSON = json.dumps(figure, cls=plotly.utils.PlotlyJSONEncoder)
    return graphJSON
Пример #30
0
class DataLoader:
    """
    API limit: 5 API requests per minute and 500 requests per day
    Get your free API key from
    https://www.alphavantage.co/support/#support

    FOREX, while supported, is not implemented.
    
    API details here:
    https://github.com/RomelTorres/alpha_vantage
    """
    def __init__(self, api_key):
        self.API_KEY = api_key
        self.cc = CryptoCurrencies(key=self.API_KEY, output_format='pandas')
        self.ti = TechIndicators(key=self.API_KEY, output_format='pandas')
        self.ts = TimeSeries(key=self.API_KEY, output_format='pandas')

    def get_local_data(self, path):
        df = pd.read_csv(path)
        return df.sort_values('Timestamp')

    def get_crypto(self, crypto_symbol):

        data, _ = self.cc.get_digital_currency_daily(symbol=crypto_symbol,
                                                     market='CNY')

        return rename_data(data, crypto=True)

    def get_stock(self,
                  stock: str,
                  period=TimeFrame.TimeFrame.DAILY,
                  full: bool = False):
        """
        Returns stock data and meta data of the ticker for the specified time frame
        :param stock: [ENUM]: Stock ticker
        :param period: [ENUM] DAILY, WEEKLY, MONTHLY
        :param full: Returns only last 100 ticks if False, otherwise full tick data set if True. False by default.
        :return: stock data, meta_data
        """
        if period is TimeFrame.TimeFrame.DAILY:
            if full:
                data, _ = self.ts.get_daily(symbol=stock.upper(),
                                            outputsize='full')
                return rename_data(data)
            else:
                data, _ = self.ts.get_daily(symbol=stock.upper(),
                                            outputsize='compact')
                return rename_data(data)

        if period is TimeFrame.TimeFrame.WEEKLY:
            if full:
                data, _ = data = self.ts.get_weekly(symbol=stock.upper(),
                                                    outputsize='full')
                return rename_data(data)
            else:
                data, _ = self.ts.get_weekly(symbol=stock.upper(),
                                             outputsize='compact')
                return rename_data(data)

        if period is TimeFrame.TimeFrame.MONTHLY:
            if full:
                data, _ = self.ts.get_monthly(symbol=stock.upper(),
                                              outputsize='full')
                return rename_data(data)
            else:
                data, _ = self.ts.get_monthly(symbol=stock.upper(),
                                              outputsize='compact')
                return rename_data(data)

    def get_intraday_stock(self,
                           stock: str,
                           interval: INTERVAL = INTERVAL.INTERVAL.FIVE_MIN,
                           full: bool = False):
        """
        Returns intraday tick data for the given stock in the given time interval
        :param stock: [ENUM] ticker
        :param interval: [ENUM] 1min, 5min, 15min, 30min, 60min
        :param full: Returns only last 100 ticks if False, otherwise full tick data set if True. False by default.
        :return: stock data, meta_data
        """

        if full:
            data, _ = self.ts.get_intraday(symbol=stock.upper(),
                                           interval=interval.value,
                                           outputsize='full')
            return rename_data(data)
        else:
            data, _ = self.ts.get_intraday(symbol=stock.upper(),
                                           interval=interval.value,
                                           outputsize='compact')
            return rename_data(data)

    def get_tech_indicator(
        self,
        stock="MSFT",
        indicator=TECHIND.TECHIND.BBANDS,
        interval=TimeFrame.TimeFrame.DAILY,
        time_period: int = 20,
    ):
        """
        Returns the technical indicator for the given stock ticker on the given interval
        :param indicator [ENUM]: @See TECHIND
        :param stock [ENUM]: Ticker
        :param interval: Daily, Weekly, Monthly. Set to Daily by default
        :param time_period: Nr of time units between two calculating points. Set to 20 by default.
        :return: pandas dataframe containing the technical indicator for all recorded trading days of the stock.
        """
        if indicator is TECHIND.TECHIND.BBANDS:
            data, _ = self.ti.get_bbands(symbol=stock.upper(),
                                         interval=interval.name.lower(),
                                         time_period=time_period)

        if indicator is TECHIND.TECHIND.SMA:
            data, _ = self.ti.get_sma(symbol=stock.upper(),
                                      interval=interval.name.lower(),
                                      time_period=time_period)

        if indicator is TECHIND.TECHIND.EMA:
            data, _ = self.ti.get_ema(symbol=stock.upper(),
                                      interval=interval.name.lower(),
                                      time_period=time_period)

        if indicator is TECHIND.TECHIND.WMA:
            data, _ = self.ti.get_wma(symbol=stock.upper(),
                                      interval=interval.name.lower(),
                                      time_period=time_period)

        if indicator is TECHIND.TECHIND.MACD:
            data, _ = self.ti.get_macd(symbol=stock.upper(),
                                       interval=interval.name.lower())

        if indicator is TECHIND.TECHIND.STOCH:
            data, _ = self.ti.get_stoch(symbol=stock.upper(),
                                        interval=interval.name.lower())

        if indicator is TECHIND.TECHIND.RSI:
            data, _ = self.ti.get_rsi(symbol=stock.upper(),
                                      interval=interval.name.lower(),
                                      time_period=time_period)

        if indicator is TECHIND.TECHIND.ADX:
            data, _ = self.ti.get_adx(symbol=stock.upper(),
                                      interval=interval.name.lower(),
                                      time_period=time_period)

        if indicator is TECHIND.TECHIND.CCI:
            data, _ = self.ti.get_cci(symbol=stock.upper(),
                                      interval=interval.name.lower(),
                                      time_period=time_period)

        if indicator is TECHIND.TECHIND.AROON:
            data, _ = self.ti.get_aroon(symbol=stock.upper(),
                                        interval=interval.name.lower(),
                                        time_period=time_period)

        if indicator is TECHIND.TECHIND.MOM:
            data, _ = self.ti.get_mom(symbol=stock.upper(),
                                      interval=interval.name.lower())

        if indicator is TECHIND.TECHIND.OBV:
            data, _ = self.ti.get_obv(symbol=stock.upper(),
                                      interval=interval.name.lower())

        return data