コード例 #1
0
ファイル: engine.py プロジェクト: pxsocs/warden
def fx_rate():
    config = load_config()
    fx = config['PORTFOLIO']['base_fx']

    # This grabs the realtime current currency conversion against USD
    try:
        rate = {}
        rate['base'] = fx
        rate['symbol'] = fxsymbol(fx)
        rate['name'] = fxsymbol(fx, 'name')
        rate['name_plural'] = fxsymbol(fx, 'name_plural')
        rate['cross'] = "USD" + " / " + fx
        if fx.upper() == 'USD':
            rate['fx_rate'] = 1
        else:
            try:
                from pricing_engine.alphavantage import realtime as aa_realtime
                fxrate = aa_realtime(fx)
                fxrate = parseNumber(fxrate['price'])
                rate['fx_rate'] = 1 / fxrate
            except Exception as e:
                rate['error'] = ("Error: " + str(e))
                rate['fx_rate'] = 1
    except Exception as e:
        rate = {}
        rate['error'] = ("Error: " + str(e))
        rate['fx_rate'] = 1
    return (rate)
コード例 #2
0
def price_and_position():
    # Gets price and position data for a specific ticker
    ticker = request.args.get("ticker")
    fx = request.args.get("fx")
    if fx is None:
        fx = fx_rate()['base']

    # Gets Price and market data first
    realtime_data = realtime_price(ticker=ticker, fx=fx)
    historical_data = historical_prices(ticker=ticker, fx=fx)
    historical_data.index = historical_data.index.astype('datetime64[ns]')

    filemeta = (ticker + "_" + fx + ".meta")
    historical_meta = pickle_it(action='load', filename=filemeta)

    price_chart = historical_data[["close_converted", "close"]].copy()
    # dates need to be in Epoch time for Highcharts
    price_chart.index = price_chart.index.astype('datetime64[ns]')
    price_chart.index = (price_chart.index -
                         datetime(1970, 1, 1)).total_seconds()
    price_chart.index = price_chart.index * 1000
    price_chart.index = price_chart.index.astype(np.int64)
    price_chart = price_chart.to_dict()
    price_chart_usd = price_chart["close"]
    price_chart = price_chart["close_converted"]

    # Now gets position data
    df = positions()
    if isinstance(df, pd.DataFrame):
        if not df.empty:
            df = df[df['trade_asset_ticker'] == ticker]

    df_trades = transactions_fx()
    position_chart = None
    if isinstance(df_trades, pd.DataFrame):
        df_trades = df_trades[df_trades['trade_asset_ticker'] == ticker]
        if not df_trades.empty:
            df_trades = df_trades.sort_index(ascending=True)
            df_trades['trade_quantity_cum'] = df_trades[
                'trade_quantity'].cumsum()
            position_chart = df_trades[["trade_quantity_cum"]].copy()
            # dates need to be in Epoch time for Highcharts
            position_chart.index = position_chart.index.astype(
                'datetime64[ns]')
            position_chart.index = (position_chart.index -
                                    datetime(1970, 1, 1)).total_seconds()
            position_chart.index = position_chart.index * 1000
            position_chart.index = position_chart.index.astype(np.int64)
            position_chart = position_chart.to_dict()
            position_chart = position_chart["trade_quantity_cum"]

    if ticker == 'GBTC':
        from pricing_engine.engine import GBTC_premium
        from parseNumbers import parseNumber
        GBTC_price = parseNumber(realtime_data['price'])
        GBTC_fairvalue, GBTC_premium = GBTC_premium(GBTC_price)
    else:
        GBTC_premium = GBTC_fairvalue = None

    return render_template("warden/price_and_position.html",
                           title="Ticker Price and Positions",
                           current_app=current_app,
                           current_user=fx_rate(),
                           realtime_data=realtime_data,
                           historical_data=historical_data,
                           historical_meta=historical_meta,
                           positions=df,
                           ticker=ticker,
                           fx=fx,
                           price_chart=price_chart,
                           price_chart_usd=price_chart_usd,
                           position_chart=position_chart,
                           GBTC_premium=GBTC_premium,
                           GBTC_fairvalue=GBTC_fairvalue)
コード例 #3
0
ファイル: engine.py プロジェクト: pxsocs/warden
def realtime_price(ticker, fx=None, source=None, parsed=True):
    '''
    Gets realtime price from first provider available and returns
    result = {
            'symbol': ,
            'name': ,
            'price': ,
            'fx': ,
            'time': ,
            'timezone':
            'source':
        }
    '''
    if fx is None:
        config = load_config()
        fx = config['PORTFOLIO']['base_fx']

    if fx == 'USD':
        fxrate = 1
    else:
        from pricing_engine.alphavantage import realtime as aa_realtime
        fxrate = aa_realtime(fx)
        fxrate = parseNumber(fxrate['price'])

    ticker = ticker.replace(' ', '')
    if source and type(source) != list:
        raise TypeError("source has to be a list of strings - can be one string inside a list")

    try:
        source_list = mapping[ticker]
    except KeyError:
        source_list = [
            'cryptocompare',
            'alphavantage_currency',
            'alphavantage_global',
            'twelvedata',
            'fmp'
        ]

    from pricing_engine.alphavantage import realtime as aa_realtime
    from pricing_engine.cryptocompare import realtime as cc_realtime
    from pricing_engine.fmp import realtime as fmp_realtime
    from pricing_engine.twelvedata import realtime as td_realtime

    results = None
    # Gets from each source
    for src in source_list:
        if src == 'alphavantage_currency':
            results = aa_realtime(ticker, 'USD', 'CURRENCY_EXCHANGE_RATE', parsed=parsed)
        if src == 'alphavantage_global':
            results = aa_realtime(ticker, 'USD', 'GLOBAL_QUOTE', parsed=parsed)
        if src == 'cryptocompare':
            results = cc_realtime(ticker, 'USD', parsed=parsed)
        if src == 'fmp':
            results = fmp_realtime(ticker, parsed=parsed)
        if src == 'twelvedata':
            results = td_realtime(ticker, parsed=parsed)
        # Check if data is valid
        if results is not None:
            if parsed and 'price' in results:
                if results['price'] is not None:
                    if isinstance(results['time'], str):
                        results['time'] = parser.parse(results['time'])
                    results['price'] = parseNumber(results['price'])
                    results['price'] = (
                        results['price'] / fxrate)
                    return (results)
    return (results)
コード例 #4
0
ファイル: warden_modules.py プロジェクト: pxsocs/warden
    def find_data(ticker):
        notes = None
        last_up_source = None
        source = None
        try:
            # Parse the cryptocompare data
            price = multi_price["RAW"][ticker][fx]["PRICE"]
            # GBTC should not be requested from multi_price as there is a
            # coin with same ticker
            if ticker in ['GBTC', 'MSTR', 'TSLA', 'SQ']:
                raise KeyError
            price = float(price)
            high = float(multi_price["RAW"][ticker][fx]["HIGHDAY"])
            low = float(multi_price["RAW"][ticker][fx]["LOWDAY"])
            chg = multi_price["RAW"][ticker][fx]["CHANGEPCT24HOUR"]
            mktcap = multi_price["DISPLAY"][ticker][fx]["MKTCAP"]
            volume = multi_price["DISPLAY"][ticker][fx]["VOLUME24HOURTO"]
            last_up_source = multi_price["RAW"][ticker][fx]["LASTUPDATE"]
            source = multi_price["DISPLAY"][ticker][fx]["LASTMARKET"]
            last_update = datetime.now()
        except (KeyError, TypeError):
            # Couldn't find price with CryptoCompare. Let's try a different source
            # and populate data in the same format [aa = alphavantage]
            try:
                single_price = realtime_price(ticker)
                if single_price is None:
                    raise KeyError
                price = clean_float(single_price['price'])
                last_up_source = last_update = single_price['time']

                try:
                    chg = parseNumber(single_price['chg'])
                except Exception:
                    chg = 0

                try:
                    source = last_up_source = single_price['source']
                except Exception:
                    source = last_up_source = '-'

                try:
                    high = single_price['high']
                    low = single_price['low']
                    mktcap = volume = '-'
                except Exception:
                    mktcap = high = low = volume = '-'

            except Exception:
                try:
                    # Finally, if realtime price is unavailable, find the latest
                    # saved value in historical prices
                    # Create a price class
                    price_class = historical_prices(ticker, fx)
                    if price_class is None:
                        raise KeyError
                    price = clean_float(
                        price_class.df['close_converted'].iloc[0])
                    high = '-'
                    low = '-'
                    volume = '-'
                    mktcap = chg = 0
                    source = last_up_source = 'Historical Data'
                    last_update = price_class.df.index[0]
                except Exception as e:
                    price = high = low = chg = mktcap = last_up_source = last_update = volume = 0
                    source = '-'
                    logging.error(
                        f"There was an error getting the price for {ticker}." +
                        f"Error: {e}")

        if ticker.upper() == 'BTC':
            nonlocal btc_price
            btc_price = price

        # check if 24hr change is indeed 24h or data is old, if so 24hr change = 0
        try:
            checker = last_update
            if not isinstance(checker, datetime):
                checker = parser.parse(last_update)
            if checker < (datetime.now() - timedelta(days=1)):
                chg = 0
        except Exception:
            pass

        return price, last_update, high, low, chg, mktcap, last_up_source, volume, source, notes