Example #1
0
def fx_quote(base, quote):
    API_KEY = 'NHFTFC9ZTIBUUPZO'
    fx = ForeignExchange(API_KEY)
    data = fx.get_currency_exchange_rate(from_currency='CHF',
                                         to_currency=quote)
    data = list(data)
    return float(data[0]['5. Exchange Rate'])
Example #2
0
class ForeignExchangeAPI(BaseAPI):
    """
    API for ForeignExchange Data
    """
    def __init__(self):
        super(ForeignExchangeAPI, self).__init__()
        self.fe = ForeignExchange(key=self.api,
                                  output_format=self.output_format)

    def get_intraday(self,
                     from_symbol,
                     to_symbol,
                     interval='15min',
                     outputsize='compact'):
        return self.fe.get_currency_exchange_intraday(from_symbol,
                                                      to_symbol,
                                                      interval=interval,
                                                      outputsize=outputsize)

    def get_exchange_rate(self, from_currency, to_currency):
        return self.fe.get_currency_exchange_rate(from_currency, to_currency)

    def plot(self, **kwargs):
        from_symbol = kwargs.get('from_symbol')
        to_symbol = kwargs.get('to_symbol')
        data, meta_data = self.get_intraday(from_symbol, to_symbol)
        data['4. close'].plot()
        plt.show()
Example #3
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Alpha Vantage sensor."""
    from alpha_vantage.timeseries import TimeSeries
    from alpha_vantage.foreignexchange import ForeignExchange

    api_key = config.get(CONF_API_KEY)
    symbols = config.get(CONF_SYMBOLS)

    timeseries = TimeSeries(key=api_key)

    dev = []
    for symbol in symbols:
        try:
            timeseries.get_intraday(symbol[CONF_SYMBOL])
        except ValueError:
            _LOGGER.error(
                "API Key is not valid or symbol '%s' not known", symbol)
        dev.append(AlphaVantageSensor(timeseries, symbol))

    forex = ForeignExchange(key=api_key)
    for conversion in config.get(CONF_FOREIGN_EXCHANGE):
        from_cur = conversion.get(CONF_FROM)
        to_cur = conversion.get(CONF_TO)
        try:
            forex.get_currency_exchange_rate(
                from_currency=from_cur, to_currency=to_cur)
        except ValueError as error:
            _LOGGER.error(
                "API Key is not valid or currencies '%s'/'%s' not known",
                from_cur, to_cur)
            _LOGGER.debug(str(error))
        dev.append(AlphaVantageForeignExchange(forex, conversion))

    add_devices(dev, True)
Example #4
0
def get_latest_exchange_rate(cur):
    cc = ForeignExchange(key=ALPHA_VANTAGE_KEY)
    # There is no metadata in this call
    data, _ = cc.get_currency_exchange_rate(from_currency=cur, to_currency='CNY')
    exRate = float(data['5. Exchange Rate'])

    return exRate
Example #5
0
def load_forex_data_intraday(api_key,params):
    for k, v in Forex_List.items():
        conn = None
        try:
            conn = psycopg2.connect(**params)
            cur = conn.cursor()
            fx = ForeignExchange(key=api_key)
            data, meta_data = fx.get_currency_exchange_intraday(from_symbol=v, to_symbol="INR", interval=Interval[0])
            for key, value in data.items():
                Last_Refreshed = key
                Time_Zone = meta_data['7. Time Zone']
                open_price = value['1. open']
                high_price = value['2. high']
                low_price = value['3. low']
                close_price = value['4. close']
                cur.execute("Insert into Currency_Exchange_Rate_Intraday values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                            (Last_Refreshed, Time_Zone, v, k,
                             "INR", "Indian Rupee", open_price, high_price, low_price, close_price)
                            )
                conn.commit()
        except ValueError:
            print(
                "Calling Forex 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()
Example #6
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Alpha Vantage sensor."""
    from alpha_vantage.timeseries import TimeSeries
    from alpha_vantage.foreignexchange import ForeignExchange

    api_key = config.get(CONF_API_KEY)
    symbols = config.get(CONF_SYMBOLS)

    timeseries = TimeSeries(key=api_key)

    dev = []
    for symbol in symbols:
        try:
            timeseries.get_intraday(symbol[CONF_SYMBOL])
        except ValueError:
            _LOGGER.error("API Key is not valid or symbol '%s' not known",
                          symbol)
        dev.append(AlphaVantageSensor(timeseries, symbol))

    forex = ForeignExchange(key=api_key)
    for conversion in config.get(CONF_FOREIGN_EXCHANGE):
        from_cur = conversion.get(CONF_FROM)
        to_cur = conversion.get(CONF_TO)
        try:
            forex.get_currency_exchange_rate(from_currency=from_cur,
                                             to_currency=to_cur)
        except ValueError as error:
            _LOGGER.error(
                "API Key is not valid or currencies '%s'/'%s' not known",
                from_cur, to_cur)
            _LOGGER.debug(str(error))
        dev.append(AlphaVantageForeignExchange(forex, conversion))

    add_devices(dev, True)
def get_fx_data():
    fx_pairs = FX.objects.all()
    count = 0

    for fx in fx_pairs:

        latest = FXPriceData.objects.filter(
            currency_pair=fx).order_by('-timestamp').first()
        if latest and latest.timestamp == datetime.datetime.today():
            print('Latest data for {} already stored'.format(fx))
        else:
            try:
                # Check if I have hit alphas api limit, if so wait 1 min
                count += 1
                if count == 6:
                    time.sleep(75)
                    count = 0

                exchange = ForeignExchange(key='3GVY8HKU0D7L550R',
                                           output_format='pandas')
                data, meta_data = exchange.get_currency_exchange_daily(
                    from_symbol=fx.from_currency.code,
                    to_symbol=fx.to_currency.code,
                    outputsize='full')

                # Format the dataframe and save the data in the db
                df = format_df(data, fx)
                df_to_sql(df)
            except ValueError as e:
                print('{} - Pair: {}'.format(e, fx))
Example #8
0
def get_daily_currency_data(outdir,
                            filename,
                            key=key,
                            curr1='EUR',
                            curr2='USD',
                            values='all',
                            num_days=100):
    fe = ForeignExchange(key, output_format='pandas')
    data, meta = fe.get_currency_exchange_daily(from_symbol=curr1,
                                                to_symbol=curr2,
                                                outputsize='full')
    filepath = Path(outdir, filename + '.csv')
    if values == 'all':
        data = pd.DataFrame.head(data, n=num_days)
        pd.DataFrame.to_csv(data, filepath, header=True)
        return
    options = ['open', 'high', 'low', 'close']
    for i in range(len(options)):
        if values == options[i]:
            data = pd.DataFrame.head(data[data.columns[i]], n=num_days)
            pd.DataFrame.to_csv(data, filepath, header=True)
            return
    else:
        print(
            "Error: values must be \'all\', \'open\', \'high\', \'low\', or \'close\'"
        )
        return
Example #9
0
def get_intraday_currency_data(outdir,
                               filename,
                               key=key,
                               curr1='EUR',
                               curr2='USD',
                               values='all',
                               num_obs=100,
                               interval='15min'):
    fe = ForeignExchange(key, output_format='pandas')
    data, meta = fe.get_currency_exchange_intraday(from_symbol=curr1,
                                                   to_symbol=curr2,
                                                   interval=interval,
                                                   outputsize='full')
    filepath = Path(outdir, filename + '.csv')
    if values == 'all':
        data = pd.DataFrame.head(data, n=num_obs)
        pd.DataFrame.to_csv(data, filepath, header=True)
        return
    options = ['open', 'high', 'low', 'close']
    for i in range(len(options)):
        if values == options[i]:
            data = pd.DataFrame.head(data[data.columns[i]], n=num_obs)
            pd.DataFrame.to_csv(data, filepath, header=True)
            return
    else:
        print(
            "Error: values must be \'all\', \'open\', \'high\', \'low\', or \'close\'"
        )
        return


# Example: get_intraday_currency_data(outdir="C:/Users/RBP7855/Desktop", filename="EUR_to_USD_intraday", curr1='EUR', curr2='USD', values='open', num_obs=500, interval='30min')
Example #10
0
def test():
    cc = ForeignExchange(key=config.AV_API)
    data, _ = cc.get_currency_exchange_rate(from_currency='BTC',
                                            to_currency='USD')
    pprint(data)
    value = data['5. Exchange Rate']
    print(f'${value}')
def get_historical(from1, to1, timeframe):
    cc = ForeignExchange(key='N6A6QT6IBFJOPJ70', output_format='pandas')
    data, meta_data = cc.get_currency_exchange_intraday(
        from_symbol=from1.strip(),
        to_symbol=to1.strip(),
        interval=timeframe.strip(),
        outputsize='full')
    df = pd.DataFrame(data)
    #df= pd.date_range(pd.to_datetime('today'), periods=10, freq='15min')
    df = df.rename(
        columns={
            'date': 'Date',
            '1. open': 'Open',
            '2. high': 'High',
            '3. low': 'Low',
            '4. close': 'Close'
        })
    df.index.names = ['Date']
    st.write(df)
    #df['Close'].plot()
    #plt.tight_layout()
    #plt.title('15 mins EUR/USD')
    #df = df.to_csv(quote + ".csv")
    #plt.show()
    #print()
    #print("##############################################################################")
    #print("Today's price")
    #today_stock = df.iloc[1:2]
    #print(today_stock)
    #print("##############################################################################")
    #print()
    return df
Example #12
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)
Example #13
0
def grap_api_data():
    api_key = '1456af4c4704e5e6bd4b60c30094b56b-32c375f91dc677c9fce0916d50811d4f'
    cc = ForeignExchange(key=api_key)
    global data
    data, _ = cc.get_currency_exchange_intraday(from_symbol='EUR',
                                                to_symbol='USD',
                                                interval="1min",
                                                outputsize='compact')
Example #14
0
def fetch_forex_data(from_symbol, to_symbol):
    cc = ForeignExchange(key=ALPHA_VANTAGE_API_KEY, output_format="pandas")
    data, meta_data = cc.get_currency_exchange_intraday(
        from_symbol=from_symbol,
        to_symbol=to_symbol,
        interval="1min",
        outputsize="full")
    return data
Example #15
0
def step_impl(context):
    currency_pair = context.vars['currency_pair']

    foreign_exchange = ForeignExchange(key=context.apy_key)
    response = foreign_exchange.get_currency_exchange_rate(
        from_currency=currency_pair['source'],
        to_currency=currency_pair['target'])

    context.response = response
Example #16
0
def getfxdata(alphaVantageKey, our, their, interval):
    data = None
    while data is None:
        try:
            fx = ForeignExchange(key=alphaVantageKey, output_format='pandas')
            data, meta_data = fx.get_currency_exchange_intraday(
                our, their, interval=interval, outputsize='full')
        except:
            pass
    return data['4. close']
Example #17
0
    def get_current_value(self, obj):
        stock = TimeSeries('WN9UYF2SGX9V3P0S')
        data, meta_data = stock.get_batch_stock_quotes(symbols=obj.ticker)
        current_market = data[0]
        currency = ForeignExchange(key='WN9UYF2SGX9V3P0S')
        data = currency.get_currency_exchange_rate(from_currency='EUR', to_currency='USD')
        currency_value = data[0]

        return_statmenet = float(currency_value['5. Exchange Rate'])*float(current_market['2. price'])*obj.shares
        return return_statmenet
Example #18
0
 def __init__(self, api_key=None):
     if api_key is None:
         default_api_key = utils.get_api_key('AlphaVantage')
         if default_api_key is None:
             raise ValueError('No AlphaVantage API Key found.')
         else:
             self.ts = ForeignExchange(key=default_api_key,
                                       output_format='pandas')
     else:
         self.ts = ForeignExchange(key=api_key, output_format='pandas')
Example #19
0
def api_info():
    api_key = "1456af4c4704e5e6bd4b60c30094b56b-32c375f91dc677c9fce0916d50811d4f"
    api_name = ForeignExchange(key=api_key)
    global data
    data, _ = api_name.get_currency_exchange_intraday(from_symbol="EUR",
                                                      to_symbol="USD",
                                                      interval="1min",
                                                      outputsize="compact")
    global json
    json = str(data)
Example #20
0
 def create_data_frame(self):
     fe = ForeignExchange(key=self.api_key)
     data, _ = fe.get_currency_exchange_daily(from_symbol=EXCHANGE_RATE_SYMBOLS['from_symbol'],
                                              to_symbol=EXCHANGE_RATE_SYMBOLS['to_symbol'],
                                              outputsize='full')
     data_df = pd.DataFrame(data)
     data_df = data_df.T
     data_df.columns = ['open', 'high', 'low', 'close']
     data_df.index = pd.DatetimeIndex(data_df.index)
     self.df = data_df
Example #21
0
def get_exchange_rate(cur):
    cc = ForeignExchange(key=ALPHA_VANTAGE_KEY, output_format='pandas', indexing_type='date')
    # There is no metadata in this call
    data, _ = cc.get_currency_exchange_daily(from_symbol=cur, to_symbol='CNY')
    data.reset_index(inplace=True)
    exRate = data.loc[:, ('date', '4. close')]
    exRate.rename(columns={'date': 'Date', '4. close': 'Close'}, inplace=True)
    exRate.insert(1, 'SymbolCode', cur)
    exRate['Date'] = exRate.apply(lambda x: x['Date'].strftime('%Y-%m-%d'), axis=1)

    return exRate
Example #22
0
def get_price(stock):
    if stock in const.CRYPTO_CURRENCIES:
        fe = ForeignExchange(key=environ["ALPHA_VANTAGE_API_KEY"])
        data, _ = fe.get_currency_exchange_rate(stock, "USD")
        full_price = data["5. Exchange Rate"]

    else:
        ts = TimeSeries(key=environ["ALPHA_VANTAGE_API_KEY"])
        data, meta_data = ts.get_intraday(stock)
        key = list(data.keys())[0]
        full_price = data[key]["1. open"]
    return float(full_price[:-2])
Example #23
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))
Example #24
0
 def get_forex_daily(self, from_currency, to_currency, num_days):
     self._check_api_rate_limit()
     cc = ForeignExchange(key=self._api_key, output_format='pandas')
     output_size = 'compact'
     if num_days > 100:
         output_size = 'full'
     cc_data, _ = cc.get_currency_exchange_daily(
         from_symbol=from_currency,
         to_symbol=to_currency,
         outputsize=output_size,
     )
     self._rename_columns(cc_data)
     return cc_data.iloc[-num_days:]
Example #25
0
def digital_currency(message):
    try:
        text = message.text
        if text =="Назад":
            markup = types.ReplyKeyboardMarkup()
            markup.row('Информация о боте', 'Котировки', 'Форекс', 'Портфель')
            bot.send_message(message.chat.id, "Выберите действие:", reply_markup=markup)
        else:
            markup = types.ReplyKeyboardMarkup()
            markup.row("Получить новости", "Назад")
            global slov
            slov = message.text
            String = str(slov)
            string1 = String[0:3]
            string2 = String[4:7]
            cc = ForeignExchange(key='ZBRM5PCHPIYQV8BY', output_format='pandas')
            # There is no metadata in this call
            data, meta_data = cc.get_currency_exchange_daily(from_symbol=string1, to_symbol=string2, outputsize='full')
            now = pd.DataFrame(data.tail(1))
            now1 = now['1. open']
            nw = str(now1)
            nw2 = nw[19:25]
            nw3 = float(nw2)
            openn = pd.DataFrame(data.tail(1))
            openn1 = openn['4. close']
            op = str(openn1)
            op2 = op[19:25]
            op3 = float(op2)
            if op3 >= nw3:
                proc = round(100 - ((op3 / nw3) * 100), 2)
                proc1 = str(proc)
                bot.send_message(message.chat.id, slov + " - $" + op2 + ' +' + proc1 + '%')
            elif op3 < nw3:
                proc2 = round(100 - ((nw3 / op3) * 100), 2)
                proc2 = str(proc2)
                bot.send_message(message.chat.id, slov + " - $" + op2 + ' -' + proc2 + '%')
            da, meta_data = cc.get_currency_exchange_daily(from_symbol=string1, to_symbol=string2, outputsize='full')
            da['4. close'].plot()

            plt.title('Intraday Times Series (1 min) within 10 days')
            plt.savefig('graph.png')
            plt.close()
            photo = open("graph.png", 'rb')
            bot.send_photo(message.chat.id, photo)
            msg = bot.send_message(message.chat.id, "Получить новости?", reply_markup=markup)
            bot.register_next_step_handler(msg, new)
    except Exception as e:
        m = types.ReplyKeyboardMarkup()
        m.row('Информация о боте', 'Котировки', 'Форекс', 'Портфель')
        bot.send_message(message.chat.id, 'Что-то пошло не так...', reply_markup=m)
Example #26
0
def setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the Alpha Vantage sensor."""
    api_key = config[CONF_API_KEY]
    symbols = config.get(CONF_SYMBOLS, [])
    conversions = config.get(CONF_FOREIGN_EXCHANGE, [])

    if not symbols and not conversions:
        msg = "No symbols or currencies configured."
        persistent_notification.create(hass, msg, "Sensor alpha_vantage")
        _LOGGER.warning(msg)
        return

    timeseries = TimeSeries(key=api_key)

    dev: list[SensorEntity] = []
    for symbol in symbols:
        try:
            _LOGGER.debug("Configuring timeseries for symbols: %s",
                          symbol[CONF_SYMBOL])
            timeseries.get_intraday(symbol[CONF_SYMBOL])
        except ValueError:
            _LOGGER.error("API Key is not valid or symbol '%s' not known",
                          symbol)
        dev.append(AlphaVantageSensor(timeseries, symbol))

    forex = ForeignExchange(key=api_key)
    for conversion in conversions:
        from_cur = conversion.get(CONF_FROM)
        to_cur = conversion.get(CONF_TO)
        try:
            _LOGGER.debug("Configuring forex %s - %s", from_cur, to_cur)
            forex.get_currency_exchange_rate(from_currency=from_cur,
                                             to_currency=to_cur)
        except ValueError as error:
            _LOGGER.error(
                "API Key is not valid or currencies '%s'/'%s' not known",
                from_cur,
                to_cur,
            )
            _LOGGER.debug(str(error))
        dev.append(AlphaVantageForeignExchange(forex, conversion))

    add_entities(dev, True)
    _LOGGER.debug("Setup completed")
Example #27
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Alpha Vantage sensor."""
    from alpha_vantage.timeseries import TimeSeries
    from alpha_vantage.foreignexchange import ForeignExchange

    api_key = config.get(CONF_API_KEY)
    symbols = config.get(CONF_SYMBOLS, [])
    conversions = config.get(CONF_FOREIGN_EXCHANGE, [])

    if not symbols and not conversions:
        msg = "Warning: No symbols or currencies configured."
        hass.components.persistent_notification.create(msg,
                                                       "Sensor alpha_vantage")
        _LOGGER.warning(msg)
        return

    timeseries = TimeSeries(key=api_key)

    dev = []
    for symbol in symbols:
        try:
            _LOGGER.debug("Configuring timeseries for symbols: %s",
                          symbol[CONF_SYMBOL])
            timeseries.get_intraday(symbol[CONF_SYMBOL])
        except ValueError:
            _LOGGER.error("API Key is not valid or symbol '%s' not known",
                          symbol)
        dev.append(AlphaVantageSensor(timeseries, symbol))

    forex = ForeignExchange(key=api_key)
    for conversion in conversions:
        from_cur = conversion.get(CONF_FROM)
        to_cur = conversion.get(CONF_TO)
        try:
            _LOGGER.debug("Configuring forex %s - %s", from_cur, to_cur)
            forex.get_currency_exchange_rate(from_currency=from_cur,
                                             to_currency=to_cur)
        except ValueError as error:
            _LOGGER.error(
                "API Key is not valid or currencies '%s'/'%s' not known",
                from_cur,
                to_cur,
            )
            _LOGGER.debug(str(error))
        dev.append(AlphaVantageForeignExchange(forex, conversion))

    add_entities(dev, True)
    _LOGGER.debug("Setup completed")
Example #28
0
 def __init__(self, host, ckey, csecret, akey):
     self.host = host
     self.key = ckey
     self.secret = csecret
     #self.producer = KafkaProducer(bootstrap_servers=self.host)
     self.p = Producer({
         'bootstrap.servers': host,
         'broker.version.fallback': '0.10.0.0',
         'api.version.fallback.ms': 0,
         'sasl.mechanisms': 'PLAIN',
         'security.protocol': 'SASL_SSL',
         'sasl.username': ckey,
         'sasl.password': csecret,
     })
     self.c = Consumer({
         'bootstrap.servers': host,
         'broker.version.fallback': '0.10.0.0',
         'api.version.fallback.ms': 0,
         'sasl.mechanisms': 'PLAIN',
         'security.protocol': 'SASL_SSL',
         'sasl.username': ckey,
         'sasl.password': csecret,
         # this will create a new consumer group on each invocation.
         'group.id': str(uuid.uuid1()),
         'auto.offset.reset': 'earliest'
     })
     self.ts = TimeSeries(key=akey, output_format='pandas')
     self.fx = ForeignExchange(key=akey)
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Alpha Vantage sensor."""
    from alpha_vantage.timeseries import TimeSeries
    from alpha_vantage.foreignexchange import ForeignExchange

    api_key = config.get(CONF_API_KEY)
    symbols = config.get(CONF_SYMBOLS, [])
    conversions = config.get(CONF_FOREIGN_EXCHANGE, [])

    if not symbols and not conversions:
        msg = 'Warning: No symbols or currencies configured.'
        hass.components.persistent_notification.create(
            msg, 'Sensor alpha_vantage')
        _LOGGER.warning(msg)
        return

    timeseries = TimeSeries(key=api_key)

    dev = []
    for symbol in symbols:
        try:
            _LOGGER.debug("Configuring timeseries for symbols: %s",
                          symbol[CONF_SYMBOL])
            timeseries.get_intraday(symbol[CONF_SYMBOL])
        except ValueError:
            _LOGGER.error(
                "API Key is not valid or symbol '%s' not known", symbol)
        dev.append(AlphaVantageSensor(timeseries, symbol))

    forex = ForeignExchange(key=api_key)
    for conversion in conversions:
        from_cur = conversion.get(CONF_FROM)
        to_cur = conversion.get(CONF_TO)
        try:
            _LOGGER.debug("Configuring forex %s - %s", from_cur, to_cur)
            forex.get_currency_exchange_rate(
                from_currency=from_cur, to_currency=to_cur)
        except ValueError as error:
            _LOGGER.error(
                "API Key is not valid or currencies '%s'/'%s' not known",
                from_cur, to_cur)
            _LOGGER.debug(str(error))
        dev.append(AlphaVantageForeignExchange(forex, conversion))

    add_devices(dev, True)
    _LOGGER.debug("Setup completed")
Example #30
0
def forex(API_key='Z6P4MY41TAIKFAXW', fromCurr='INR', toCurr='USD'):
  print("########PROCESSING#########")
  from alpha_vantage.foreignexchange import ForeignExchange
  import matplotlib.pyplot as plt
  import mplfinance as mpf

  fe=ForeignExchange(key=API_key,output_format='pandas')
  data=fe.get_currency_exchange_daily(from_symbol=fromCurr, to_symbol=toCurr)[0]
  data.columns = ['Open', 'High', 'Low', 'Close']
  data.index.name = "Date"
  mpf.plot(data,
          type='candle', 
          title=f'Daily FOREX for the {fromCurr} against {toCurr} currency',
          mav=(20), 
          tight_layout=True,
          style='yahoo')
  return data
Example #31
0
def omen(key, from_symbol, to_symbol, interval=False):
    """Takes Alpha Vantage API key, currency pair and optional interval, and returns the predicted next value."""

    #set constants
    FIELD = "4. close"

    #fetch data
    api = ForeignExchange(key=key)
    if interval:
        data, _ = api.get_currency_exchange_intraday(from_symbol=from_symbol,
                                                     to_symbol=to_symbol,
                                                     outputsize="full",
                                                     interval=interval)
    else:
        data, _ = api.get_currency_exchange_daily(from_symbol=from_symbol,
                                                  to_symbol=to_symbol,
                                                  outputsize="full")

    #extract required data
    time_series = []
    for date in data:
        time_series.append((date, float(data[date][FIELD])))
    time_series.sort(key=lambda tup: tup[0])
    dates = []
    prices = []
    for date, price in time_series:
        dates.append(date)
        prices.append(price)

    #build data structures
    df = pd.DataFrame(data=prices, index=dates, columns=["price"])
    df["prediction"] = df[["price"]].shift(-1)
    x = np.array(df.drop(["prediction"], 1))
    x = preprocessing.scale(x)
    x_forecast = x[-1:]
    x = x[:-1]
    y = np.array(df["prediction"])
    y = y[:-1]
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)

    #run linear regression
    reg = LinearRegression()
    reg.fit(x_train, y_train)
    future = reg.predict(x_forecast)
    return prices[-1], future[0]
Example #32
0
def convert_currency(fr_curr, to_curr='USD'):
    #import pandas as bear
    #from alpha_vantage.foreignexchange import ForeignExchange #https://alpha-vantage.readthedocs.io/en/latest/genindex.html
    #keys = 'BGDF14R9D6NKLQ19'

    output_format = ForeignExchange(key=keys, output_format='pandas')
    z = output_format.get_currency_exchange_rate(from_currency=fr_curr,
                                                 to_currency=to_curr)
    z[0].reset_index(inplace=True)
    z[0].columns = [
        'index', 'From_Currency Code', 'From_Currency Name',
        'To_Currency Code', 'To_Currency Name', 'Exchange Rate',
        'Last Refreshed', 'Time Zone', 'Bid Price', 'Ask Price'
    ]

    exch_rate = float(z[0]['Exchange Rate'].to_string(index=False))

    return exch_rate
Example #33
0
File: plugin.py Project: dqd/heap
    def currency(self, irc, msg, args, amount, c1, c2):
        '''[<amount>] <currency1> to <currency2>

        Converts from <currency1> to <currency2>. If amount is not given,
        it defaults to 1.
        '''
        api_key = self.registryValue('api_key')

        c1 = self._normalize(c1)
        c2 = self._normalize(c2)

        rate = None

        try:
            if ALPHA_VANTAGE and api_key and \
                (c1 not in Currency.AVAILABLE_CURRENCIES or
                 c2 not in Currency.AVAILABLE_CURRENCIES):
                fe = ForeignExchange(key=api_key)
                r, _ = fe.get_currency_exchange_rate(
                    from_currency=c1,
                    to_currency=c2,
                )
                rate = float(r.get('5. Exchange Rate', 0))
            else:
                r = requests.get(
                    'https://frankfurter.app/current?from={}'.format(c1)
                )

                if r.ok:
                    rate = r.json().get('rates', {}).get(c2)
        except Exception as e:
            irc.error(unicode(e), Raise=True)

        if rate:
            irc.reply('{:.2f} {} = {:.2f} {}'.format(amount, c1, amount * rate, c2))
        else:
            irc.error('Unable to convert {} to {}.'.format(c1, c2))