Пример #1
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()
Пример #2
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)
Пример #3
0
 def getValues(symbol, currency='Stock'):
     '''
     get the full time series from a given stock or cryptocurrency
     :param symbol: symbol of desired stock or crypto
     :param currency: 'stock' or 'crypto'
     :return: (x,y) x is the dates, and y is the stock value
     '''
     if currency == 'Stock':
         ts = TimeSeries(key=api_key, output_format='pandas')
         try:
             data, meta_data = ts.get_weekly(symbol)
         except KeyError:
             return None, None
         x = data.index.values  # get index values (dates)
         y = data.iloc[:,
                       3].values  # 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_weekly(symbol,
                                                              market='USD')
         except KeyError:
             return None, None
         x = data.index.values  # get index values (dates)
         y = data.iloc[:,
                       3].values  # get third column which is closing price
         return x, y
Пример #4
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
Пример #5
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')
Пример #6
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
Пример #7
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
Пример #8
0
 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)
Пример #9
0
def step_impl(context):
    digital_currency = context.vars['digital_currency']

    crypto_currencies = CryptoCurrencies(key=context.apy_key)
    response = crypto_currencies.get_digital_currency_weekly(
        symbol=digital_currency['currency'], market=digital_currency['market'])

    context.response = response
Пример #10
0
 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')
Пример #11
0
async def crypto_current_price(ctx, symbol: str, market: str):
    cc = CryptoCurrencies(key=os.environ['ALPHA_VANTAGE_API_KEY'])
    data = cc.get_digital_currency_intraday(symbol=symbol, market=market)
    current_time = max(data[0].keys())
    most_recent_entry = data[0][current_time]
    output_header = "{} ({})".format(symbol, market)
    output = get_nice_output(output_header, current_time, most_recent_entry)
    print(output)
    await bot.say(output)
Пример #12
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
Пример #13
0
    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()
Пример #14
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()
Пример #15
0
 def __init__(self,
              interval=None,
              interval_length=None,
              symbol='BTC',
              market='USD'):
     self.cc = CryptoCurrencies(key=ALPHA_VANTAGE_API_KEY)
     self.fe = ForeignExchange(key=ALPHA_VANTAGE_API_KEY)
     self.symbol = symbol
     self.market = market
     super(BtcData,
           self).__init__(interval or 'daily',
                          interval_length or 7,
                          key_name='4a. close ({})'.format(self.market))
Пример #16
0
def generate_report(stock):
    logger.info(f"Generating report for {stock}")
    if stock.replace("$", "") in const.CRYPTO_CURRENCIES:
        crypto = CryptoCurrencies(key=environ["ALPHA_VANTAGE_API_KEY"])
        data, _ = crypto.get_digital_crypto_rating(stock)
    else:
        fd = FundamentalData(key=environ["ALPHA_VANTAGE_API_KEY"])
        data, _ = fd.get_company_overview(stock)
        for (key, val) in list(data.items()):
            if val.isnumeric():
                data[key] = "${:,.2f}".format(float(val))
            if key not in const.REPORT_FIELDS:
                data.pop(key)
    save_report_to_image(data)
Пример #17
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")
Пример #18
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
Пример #19
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()
Пример #20
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"]]
Пример #21
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
Пример #22
0
def setup_request_object(request, symbol, interval):
    if CHARTDOMAIN == 'stock':
        try:
            ts = TimeSeries(API_KEY, output_format='pandas', indexing_type='date')
        except:
            print("Error occurred/ Number of API calls exhausted")
            return [False, False]
        if request == 'intraday': return ['intraday', ts]
        if request == 'daily': return ['daily', ts]
        if request == 'weekly': return ['weekly', ts]
        if request == 'monthly': return ['monthly', ts]
        return [False, False]

    if CHARTDOMAIN == 'cryptocurrency':
        try:
            cc = CryptoCurrencies(key=API_KEY, output_format='pandas')
        except:
            print("Error occurred/ Number of API calls exhausted")
            return [False, False]
        if CRYPTOINTERVAL == 'daily': return ['daily', cc]
        if CRYPTOINTERVAL == 'weekly': return ['weekly', cc]
        if CRYPTOINTERVAL == 'monthly': return ['monthly', cc]
        return [False, False]       
Пример #23
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
Пример #24
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
# ------------------------------
# Part Three: Sector Performance
# ------------------------------

sp = SectorPerformances(key='API_KEY', output_format='pandas')
data, metadata = sp.get_sector()
data['Rank A: Real-Time Performance'].plot(kind='bar')
plt.title('Real Time Performance (%) per Sector')
plt.tight_layout()
plt.grid()
plt.show()

# ---------------------------
# Part Four: Cryptocurrencies
# ---------------------------
ticker = 'BTC'
cc = CryptoCurrencies(key='YOUR_API_KEY', output_format='pandas')
data, metadata = cc.get_digital_currency_intraday(symbol=ticker, market='CNY')
data['1b. price (USD)'].plot()
plt.tight_layout()
plt.title('Intraday value for bitcoin (BTC)')
plt.grid()
plt.show()

# --------------------------------
# Part Five: Foreign Exchange (FX)
# --------------------------------
fe = ForeignExchange(key='YOUR_API_KEY')
# No metadata here
data, _ = fe.get_currency_exchange_rate(from_currency='BTC', to_currency='USD')
pprint(data)
Пример #26
0
    def fetch(self, ticker):
        if self.exchange == 'poloniex':
            #ticker in format 'BTC_OMG'
            #period in format '5m', '1h' etc
            #downloads all data for a given exchange
            directory = self.directory + '/Raw_data/' + self.exchange + '/' + self.period + '/' + tickDir(
                ticker) + '.pickle'
            if (not os.path.isfile(directory)) or self.newdata == True:
                data = self.exchangeObject.fetch_ohlcv(ticker,
                                                       timeframe=self.period)
                df = pd.DataFrame(data)
                df.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
                df['Date'] = pd.to_datetime(df['Date'], unit='ms')
                df.set_index('Date', inplace=True)

                if not os.path.exists(self.directory + '/Raw_data/' +
                                      self.exchange + '/' + self.period):
                    os.makedirs(self.directory + '/Raw_data/' + self.exchange +
                                '/' + self.period)
                pickler(directory, df)
                return df

            elif os.path.isfile(directory):
                return dePickler(directory)

        if self.exchange == 'snp500':
            directory = self.directory + '/Raw_data/' + self.exchange + '/1d/' + ticker + '.pickle'
            if not os.path.isfile(directory):
                df = web.DataReader(ticker, 'google')
                if not os.path.exists(self.directory + self.exchange + '/1d'):
                    os.makedirs(self.directory + self.exchange + '/1d')
                pickler(directory, df)

            elif os.path.isfile(directory):
                return dePickler(directory)

        if self.exchange == 'alphavantage':
            directory = self.directory + 'Raw_data/' + self.exchange + '/' + self.period + '/' + ticker + '.pickle'
            if (not os.path.isfile(directory)) or self.newdata == True:
                if self.asset_type == 'eft' and self.period == '1d':
                    ts = TimeSeries(key='YOUR_API_KEY', output_format='pandas')
                    data, meta_data = ts.get_daily(symbol=ticker,
                                                   outputsize='full')
                    data.columns = ['Open', 'High', 'Low', 'Close', 'Volume']

                elif self.asset_type == 'crypto' and self.period == '1d':
                    ts = CryptoCurrencies(key='YOUR_API_KEY',
                                          output_format='pandas')
                    data, meta_data = ts.get_digital_currency_daily(
                        symbol=ticker, market='USD')
                    data.drop([
                        '1b. open (USD)', '2b. high (USD)', '3b. low (USD)',
                        '4b. close (USD)', '6. market cap (USD)'
                    ],
                              axis=1,
                              inplace=True)
                    data.columns = ['Open', 'High', 'Low', 'Close', 'Volume']

                elif self.asset_type == 'crypto' and self.period == '5m':
                    ts = CryptoCurrencies(key='YOUR_API_KEY',
                                          output_format='pandas')
                    data, meta_data = ts.get_digital_currency_intraday(
                        symbol=ticker, market='USD')
                    data.drop(['1b. price (USD)', '3. market cap (USD)'],
                              axis=1,
                              inplace=True)
                    data.columns = ['Close', 'Volume']
                    print(data)
                    time.sleep(50)
                else:
                    print(
                        'incompatible asset type and period (see getdata module)'
                    )
                    sys.exit(2)
            else:
                data = dePickler(directory)

            if not os.path.exists(self.directory + '/Raw_data/' +
                                  self.exchange + '/' + self.period):
                os.makedirs(self.directory + '/Raw_data/' + self.exchange +
                            '/' + self.period)
            pickler(directory, data)

            return data
Пример #27
0
import streamlit as st
import pandas as pd
import numpy as np
import os
import requests
import plotly.express as px
from datetime import datetime, timedelta
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.cryptocurrencies import CryptoCurrencies
from PIL import Image
ALPHAVANTAGE_API_KEY = 'H983JJABQU6EEV35'
ts = TimeSeries(key=ALPHAVANTAGE_API_KEY, output_format='pandas')
cc = CryptoCurrencies(key=ALPHAVANTAGE_API_KEY, output_format='pandas')

resp = requests.get('https://www.alphavantage.co/query',
                    params={
                        'function': 'TIME_SERIES_DAILY_ADJUSTED',
                        'symbol': 'ITSA4.SA',
                        'market': 'BRL',
                        'apikey': ALPHAVANTAGE_API_KEY,
                        'datatype': 'json',
                        'outputsize': "full"
                    })
doc = resp.json()

df = pd.DataFrame.from_dict(doc['Time Series (Daily)'],
                            orient='index',
                            dtype=np.float)
df.reset_index(inplace=True)
df = df.rename(columns={
    'index': 'Data',
Пример #28
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)
Пример #29
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)
Пример #30
0
def getData():
    cc = CryptoCurrencies(API_key, output_format="json")
    data = cc.get_digital_currency_exchange_rate(cur, toCur)
    data1 = float(json.loads(json.dumps(data))[0][dataType1[0][0]])
    data2 = float(json.loads(json.dumps(data))[0][dataType2[0][0]])
    return ([data1, data2])