class OracleServer:
    def __init__(self, api_key=alpha_vantage_api_key, ticker_symbol=alpha_vantage_ticker_symbol, tezos_key=tezos_user_key, oracle_contract_address=oracle_address):
        self.oracle_contract_address = oracle_contract_address
        self.pytezos_instance = pytezos.using(key=tezos_key, shell='carthagenet')
        self.time_series = TimeSeries(key=api_key, output_format='json')
        self.ticker_symbol = ticker_symbol

    def oracle_contract(self):
        return self.pytezos_instance.contract(self.oracle_contract_address)

    def update_value(self):
        try:
            now_utc = datetime.now(tz=timezone.utc)
            operation_group = self.oracle_contract().updateValue(now_utc, self.price()).operation_group # hi
            operation_str = f"<p> Last operation:\n{operation_group.autofill().sign().inject()} </p>"
            storage_str = f"<p> Current storage:\n{self.oracle_contract().storage()} </p>"
            return (operation_str + storage_str)
        except Exception as e:
            exception_doc = f"<p> Exception: {str(e.__doc__)} </p>"
            exception_message = None
            try:
                exception_message = f"<p> {str(e.message)} </p>"
            except:
                exception_message = f"(unknown message: {e.__class__.__name__})"
            return (exception_doc + exception_message)

    def price(self):
        quote_data, expected_none = self.time_series.get_quote_endpoint(self.ticker_symbol)
        if expected_none is None:
            try:
                return int(float(quote_data['05. price']) * 100)
            except KeyError:
                raise f"expected key: '05. price' in {str(quote_data)}"
        else:
            raise f"expected_none not None: {str(expected_none)}"
Exemple #2
0
def main():

    # get API keys
    key = s3_read(bucket='trader-con', key='secrets/alpha_vantage_secrets.txt')

    # read in portfolio (TO DO: switch to s3 location
    portfolio = get_portfolio()

    # get cash value
    cash = portfolio['cash']
    print(cash)

    # get stock value
    ts = TimeSeries(key)
    stock_value = 0
    for ticker in portfolio['stock'].keys():
        print(ticker)
        # get number of shares
        shares = portfolio['stock'][ticker]

        # get stock price
        prices, meta = ts.get_quote_endpoint(symbol=ticker)
        price = float(prices['05. price'])
        print(f'Shares: {shares}, Share Price: {price} \n')

        stock_value += 1 * (shares * price)

    # compute total
    total = cash + stock_value
    print(f'Total Portfolio Value: {total}')
    return total
Exemple #3
0
 def get_object(self):
     symbol = self.kwargs.get("symbol")
     try:
         stock = Stock.objects.get(symbol__iexact=symbol)
     except Stock.DoesNotExist:
         print("Stock does not exist!")
         raise Http404(f"Stock symbol <{symbol}> does not exist!")
     ts = TimeSeries(key=_AV_LIVE_API_QUOTE_KEY, output_format="json")
     try:
         av_response = ts.get_quote_endpoint(symbol=symbol)
         av_quote = av_response[0]
     except:
         print("Error contacting API")
         raise Http404("Error contacting alphavantage API.")
     # TODO(jonas): check if a quote with same prices already exists
     quote, created = Price.objects.get_or_create(
         symbol=stock,
         interval="quote",
         date=dateutil.parser.parse(
             av_quote["07. latest trading day"]).date(),
         # TODO(jonas): if this is the prev. day
         # we need to write midnight as timestamp instead
         p_low=float(av_quote["04. low"]),
         p_open=float(av_quote["02. open"]),
         p_high=float(av_quote["03. high"]),
         p_close=float(av_quote["05. price"]),
         p_adjusted_close=float(av_quote["05. price"]),
         volume=int(av_quote["06. volume"]),
     )
     if not created:
         quote.exchange_time = timezone.now().time()
     return quote
def quote_val_by_symbol(symba):
    #import pandas as bear
    #from alpha_vantage.timeseries import TimeSeries #https://alpha-vantage.readthedocs.io/en/latest/genindex.html
    #keys = 'BGDF14R9D6NKLQ19' #get free API Key here: https://www.alphavantage.co/support/#api-key

    output_format = TimeSeries(key=keys, output_format='pandas')
    x = output_format.get_symbol_search(keywords=symba)
    x[0].reset_index(inplace=True)
    x[0].columns = ['date','symbol','name','type','region','marketOpen','marketClose','timezone','currency','matchScore']
    
    base_currency = x[0][x[0]['symbol']==symba]['currency'].to_string(index=False)
    base_currency = base_currency.replace(" ","")
    rate = convert_currency(base_currency)
       
    output_format = TimeSeries(key=keys, output_format='pandas')
    y = output_format.get_quote_endpoint(symbol=symba)
    y[0].reset_index(inplace=True)
    y[0].columns = ['index','symbol','open','high','low','price','volume','latest trading day','previous close','change','change percent']
    y[0]
    
    quote_in_usd=y[0]
    quote_in_usd['open']  = (float(quote_in_usd['open']) * rate )
    quote_in_usd['high']  = (float(quote_in_usd['high']) * rate )
    quote_in_usd['low']   = (float(quote_in_usd['low']) * rate  )
    quote_in_usd['price'] = (float(quote_in_usd['price']) * rate)
    
    return quote_in_usd
Exemple #5
0
def get_prices():
	# Your key here - keep it
	key = '6LGG0QGAGBROB2M6'

	ts = TimeSeries(key=key, output_format='pandas')

	start_time = time.time()
	count = 0

	# track these throughout
	sell_value = 0.0
	curr_value = 0.0

	for stock in TICKERS:
		print(stock[0], end=' ', flush=True)
		count += 1
		stock[3] = float(ts.get_quote_endpoint(symbol=stock[0])[0]['05. price']['Global Quote'])

		if count == 5:
			print(' [ delay ]', flush=True)
			for i in range(0, 60):
				time.sleep(1)
				print(' .', end='', flush=True)
			count = 0
			print('', flush=True)

		# update values of holdings
		sell_value += stock[1]*stock[2]
		curr_value += stock[1]*stock[3]

	print("\n\nValue at sell time: $", sell_value, flush=True)
	print("Value now         : $", curr_value, flush=True)
	print("Change in value   : $", curr_value - sell_value, flush=True)
Exemple #6
0
 def getQuoteFromMarket(self):
     #ti = TechIndicators(self.key, output_format='pandas')
     try:
         #self.script = self.exchange_text.get() + ":" + self.symbol_text.get()
         curr_selection = self.search_symbol_combo.current()
         if (curr_selection >= 0):
             self.script = self.searchTuple[0].values[curr_selection][0]
         else:
             msgbx.showerror('Get Quote', 'No script selected')
             self.search_symbol_combo.focus_force()
             return
         ts = TimeSeries(self.key, output_format='pandas')
         quote_tuple = ts.get_quote_endpoint(symbol=self.script)
         #quote_tuple[0].values[0][1]
         #for i in range(1, 1, quote_tuple[0].size):
         self.open_val_label.configure(text=quote_tuple[0].values[0][1])
         self.high_val_label.configure(text=quote_tuple[0].values[0][2])
         self.low_val_label.configure(text=quote_tuple[0].values[0][3])
         self.price_val_label.configure(text=quote_tuple[0].values[0][4])
         self.volume_val_label.configure(text=quote_tuple[0].values[0][5])
         self.latesttradingday_val_label.configure(
             text=quote_tuple[0].values[0][6])
         self.prevclose_val_label.configure(
             text=quote_tuple[0].values[0][7])
         self.change_val_label.configure(text=quote_tuple[0].values[0][8])
         self.changepct_val_label.configure(
             text=quote_tuple[0].values[0][9])
     except Exception as e:
         msgbx.showerror("Get Quote Error", str(e))
         self.search_symbol_combo.focus_force()
         return
Exemple #7
0
def update_values(request):
    try:
        portfolio = Portfolio.objects.get(user=request.user)
        current_value = 0
        unrealized_pnl = 0
        growth = 0
        holding_companies = StockHolding.objects.filter(portfolio=portfolio)
        stockdata = {}
        for c in holding_companies:
            ts = TimeSeries(key=get_alphavantage_key(), output_format='json')
            data, meta_data = ts.get_quote_endpoint(symbol=c.company_symbol)
            last_trading_price = float(data['05. price'])
            pnl = (last_trading_price *
                   c.number_of_shares) - c.investment_amount
            net_change = pnl / c.investment_amount
            stockdata[c.company_symbol] = {
                'LastTradingPrice': last_trading_price,
                'PNL': pnl,
                'NetChange': net_change * 100
            }
            current_value += (last_trading_price * c.number_of_shares)
            unrealized_pnl += pnl
        growth = unrealized_pnl / portfolio.total_investment
        return JsonResponse({
            "StockData": stockdata,
            "CurrentValue": current_value,
            "UnrealizedPNL": unrealized_pnl,
            "Growth": growth * 100
        })
    except Exception as e:
        return JsonResponse({"Error": str(e)})
def get_data_latest(symbol, savingtoCsv=True):
    # reads the latest data of the API
    # get changes of the last day
    from alpha_vantage.timeseries import TimeSeries
    API_KEY, waiting_times = api_key_finder()
    ts = TimeSeries(key=API_KEY, output_format='pandas')
    data = ts.get_quote_endpoint(symbol=symbol)
    return data  # , waiting_times
Exemple #9
0
def get_realtime_price_single(symbol):
    ts = TimeSeries(key=ALPHA_VANTAGE_KEY, output_format='pandas', indexing_type='date')
    data, meta_data = ts.get_quote_endpoint(symbol)
    price = data.reset_index(drop=True)
    price = price[['01. symbol', '05. price', '10. change percent']]
    price.rename(columns={'01. symbol': 'SymbolCode', '05. price': 'Close', '10. change percent': 'DayRatio'}, inplace=True)
    price.iat[0, 2] = float(price.iat[0, 2].split('%')[0].strip())/100

    return price
def company_stock_valuation(company):
    ts = TimeSeries(key=settings.ALPHA_VANTAGE_API_KEY)

    data, _ = ts.get_quote_endpoint(company.symbol)

    return {
        'open': data['02. open'],
        'high': data['03. high'],
        'low': data['04. low'],
        'close': data['05. price'],
        'price': data['05. price'],
        'volume': data['06. volume']
    }
Exemple #11
0
def get_fin_quotes(ticker_symbol):
    ts = TimeSeries(key="QG9CQILAD7ASQXK0")
    data = ts.get_quote_endpoint(ticker_symbol)
    symbol_search = ts.get_symbol_search(ticker_symbol)
    try:
        return str(symbol_search[0][0]['2. name']) \
               + ": Цена - " + str(data[0]['05. price']) \
               + " Объем - " + str(data[0]['06. volume']) \
               + " Процент изменений с последнего торгового дня - " + str(data[0]['10. change percent'])
    except ValueError:
        print("Неверный тикет")
    finally:
        print("Конец обработки исключения")
Exemple #12
0
def get_price(ticker):
    ts = TimeSeries(key=AV_KEY)
    data, meta_data = ts.get_quote_endpoint(symbol=ticker)
    # json_file = json.loads(data)
    json_dict = {}

    for key in data:
        k = key.split(' ')[1:]
        k = ' '.join(k)
        v = data[key]
        json_dict[k] = v

    return json_dict
Exemple #13
0
def StockQuote(request, pk, format=None):
    try:
        symbol = Stock.objects.get(pk=pk).symbol
    except symbol.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        from alpha_vantage.timeseries import TimeSeries
        ts = TimeSeries(key=key)
        try:
            data, meta_data = ts.get_quote_endpoint(symbol=symbol)
        except Exception:
            return Response(status=status.HTTP_404_NOT_FOUND)
        return Response(data)
Exemple #14
0
 def getStockInfo(self):
     api_key = key.returnKey()
     try:
         ts = TimeSeries(key=api_key, output_format='pandas')
         data, meta_data = ts.get_quote_endpoint(symbol=self.symbol)
     except:
         return False
     self.open = float(data['02. open'][0])
     self.high = float(data['03. high'][0])
     self.low = float(data['04. low'][0])
     self.close = float(data['05. price'][0])
     self.volume = float(data['06. volume'][0])
     self.date = str(data['07. latest trading day'][0])
     self.change = float(data['09. change'])
     return True
def get_price_curr(ticker):
    """
    Pulls data from Alphavantage using ticker.
    Returns back close for today (latest value).
    """
    ts = TimeSeries(api_keys.AV_KEY)
    attempts = 1
    while attempts <= 2:
        try:
            data = ts.get_quote_endpoint(symbol=ticker)
            price = float(data[0]['05. price'])
            return price
        except ValueError:
            sleep(61)
            attempts += 1
Exemple #16
0
 def getStockLatestInfo(cls, symbol):
     api_key = key.returnKey()
     try:
         ts = TimeSeries(key=api_key, output_format='pandas')
         data, meta_data = ts.get_quote_endpoint(symbol=symbol)
     except:
         return False
     stock = StockModel(data['01. symbol'][0])
     stock.open = float(data['02. open'][0])
     stock.high = float(data['03. high'][0])
     stock.low = float(data['04. low'][0])
     stock.close = float(data['05. price'][0])
     stock.volume = float(data['06. volume'][0])
     stock.date = str(data['07. latest trading day'][0])
     stock.change = float(data['09. change'])
     return stock.json()
def getCurrentStockPrice(api_key, symbols):
    """Get Current Stock Price for a list of symbols."""
    if app_mode == 'debug':
        print("Starting Alpha Vantage Call...\n")
    timeseries = TimeSeries(key=api_key)

    try:
        with ThreadPoolExecutor(max_workers=10) as executor:
            generator = executor.map(lambda stock:timeseries.get_quote_endpoint(symbol=stock), symbols)
        for data in generator:
            # Lets publish this to MQTT....
            publishToMqtt(data[0]['01. symbol'], data[0]['05. price'])
            if app_mode == 'debug':
                print("{} - {}".format(data[0]['01. symbol'],data[0]['05. price']))
    except ValueError:
        if app_mode == 'debug':
            print("API Key is not valid or symbols not known")
    if app_mode == 'debug':
        print("Alpha Vantage Call Complete...\n")
    return data
Exemple #18
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"]
        return float(full_price[:-2])
    else:
        try:
            ts = TimeSeries(key=environ["ALPHA_VANTAGE_API_KEY"])
            if nasdaq_is_open():
                data, meta_data = ts.get_intraday(stock)
                key = list(data.keys())[0]
                full_price = data[key]["4. close"]
                return float(full_price[:-2])
            else:
                data, _ = ts.get_quote_endpoint(stock)
                full_price = data["05. price"]
                return float(full_price[:-2])
        except ValueError:
            response = requests.get(f"{const.FMP_API_GET_PRICE_ENDPOINT}"
                                    f'{stock}?apikey={environ["FMP_API_KEY"]}')
            return response.json()[0]["price"]
Exemple #19
0
def get_data(ticker):
    APIkey = AV_func.GetAPIkey(
        KEYS)  # get a new API key each time the script runs
    TEMPdf = pd.DataFrame()  # create empty dataframe
    print("Gather data for {}".format(ticker))
    ts = TimeSeries(key=APIkey, output_format='pandas')
    data = ts.get_quote_endpoint(symbol=ticker)
    data = data[0]
    df = pd.DataFrame(data)
    df.append(data)
    ti = TechIndicators(key=APIkey, output_format='pandas')
    dataRSI = ti.get_rsi(symbol=ticker,
                         interval=RSI_INT,
                         time_period=RSI_PERIOD)
    dataRSI = dataRSI[0]
    TEMPdf = TEMPdf.append(dataRSI)
    RS = TEMPdf.last('1D')
    RS = RS.iat[0, 0]
    RSR = round(RS, 2)
    df['11. RSI'] = RSR  # add to df
    df = df.transpose()
    print(df)
Exemple #20
0
def crawl(
    module_id: str,
    app,
    api_key: str,
    symbols: List[Tuple[int, int]],
    mode: str = "table",
) -> None:
    ts = TimeSeries(key="YOUR_API_KEY")
    stocks_data: Dict[str, Any] = {"_timestamp": time.time(), "stocks": []}

    # Get the data from the alpha vantage API
    for symbol, alias in symbols:
        if mode == "table":
            LOGGER.info(
                "Requesting global quote for symbol '%s' with alias '%s'", symbol, alias
            )
            try:
                data = ts.get_quote_endpoint(symbol)
            except ConnectionError:
                raise CrawlerDataError("Could not connect to Alpha Vantage API")
            stocks_data["stocks"].append(
                # TODO It looks like alpha_vantage returns a list with the data
                # at first element and a second element which is always None
                # TODO Normalize the data and get rid of all those 1., 2., 3.
                # in the dictionary keys
                {"symbol": symbol, "alias": alias, "data": data[0]}
            )
        else:
            LOGGER.info(
                "Requesting intraday for symbol '%s' with alias '%s'", symbol, alias
            )
            try:
                data, meta_data = ts.get_intraday(symbol)
            except ConnectionError:
                raise CrawlerDataError("Could not connect to Alpha Vantage API")

            # As the dictionary is already "sorted" by the time in chronologial
            # (desc) order, we could simply reformat it into a list and move
            # the time frame as a value inside the dictionary. This makes
            # visualizing the data much simpler.
            norm_values = []
            times = []
            for timeframe, values in data.items():
                norm_values.append(
                    {
                        "open": values["1. open"],
                        "high": values["2. high"],
                        "low": values["3. low"],
                        "close": values["4. close"],
                        "volume": values["5. volume"],
                    }
                )
                times.append(timeframe)

            stocks_data["stocks"].append(
                {
                    "symbol": symbol,
                    "alias": alias,
                    "data": {"values": norm_values[::-1], "times": times[::-1]},
                    "meta_data": meta_data,
                }
            )
            # TODO Use meta_data to calculate correct timezone information
            # {'1. Information': 'Intraday (15min) open, high, low, close prices and volume',
            # '2. Symbol': 'GOOGL', '3. Last Refreshed': '2019-10-04 16:00:00',
            # '4. Interval': '15min', '5. Output Size': 'Compact', '6. Time Zone': 'US/Eastern'}

    app.store_module_data(module_id, stocks_data)
Exemple #21
0
class AVInterface:
    """
    AlphaVantage interface class, provides methods to call AlphaVantage API
    and return the result in useful format handling possible errors.
    """

    def __init__(self, apiKey, config):
        self.read_configuration(config)
        self._last_call_ts = dt.datetime.now()
        self.TS = TimeSeries(
            key=apiKey,
            output_format="pandas",
            indexing_type="integer",
            treat_info_as_error=True,
            retries=0,
        )
        self.TI = TechIndicators(key=apiKey, output_format="pandas", retries=0)
        logging.info("AlphaVantage initialised.")

    def read_configuration(self, config):
        self.enable = config["alpha_vantage"]["enable"]
        self.api_timeout = config["alpha_vantage"]["api_timeout"]

    def get_prices(self, market_id, interval):
        """
        Return the price time series of the requested market with the interval
        granularity. Return None if the interval is invalid
        """
        if (
            interval == AVInterval.MIN_1
            or interval == AVInterval.MIN_5
            or interval == AVInterval.MIN_15
            or interval == AVInterval.MIN_30
            or interval == AVInterval.MIN_60
        ):
            return self.intraday(market_id, interval)
        elif interval == AVInterval.DAILY:
            return self.daily(market_id)
        elif interval == AVInterval.WEEKLY:
            return self.weekly(market_id)
        # TODO implement monthly call
        else:
            return None

    def daily(self, marketId):
        """
        Calls AlphaVantage API and return the Daily time series for the given market

            - **marketId**: string representing an AlphaVantage compatible market id
            - Returns **None** if an error occurs otherwise the pandas dataframe
        """
        self._wait_before_call()
        market = self._format_market_id(marketId)
        try:
            data, meta_data = self.TS.get_daily(symbol=market, outputsize="full")
            return data
        except Exception as e:
            logging.error("AlphaVantage wrong api call for {}".format(market))
            logging.debug(e)
            logging.debug(traceback.format_exc())
            logging.debug(sys.exc_info()[0])
        return None

    def intraday(self, marketId, interval):
        """
        Calls AlphaVantage API and return the Intraday time series for the given market

            - **marketId**: string representing an AlphaVantage compatible market id
            - **interval**: string representing an AlphaVantage interval type
            - Returns **None** if an error occurs otherwise the pandas dataframe
        """
        self._wait_before_call()
        if interval is AVIntervals.DAILY:
            logging.error("AlphaVantage Intraday does not support DAILY interval")
            return None
        market = self._format_market_id(marketId)
        try:
            data, meta_data = self.TS.get_intraday(
                symbol=market, interval=interval.value, outputsize="full"
            )
            return data
        except Exception as e:
            logging.error("AlphaVantage wrong api call for {}".format(market))
            logging.debug(e)
            logging.debug(traceback.format_exc())
            logging.debug(sys.exc_info()[0])
        return None

    def weekly(self, marketId):
        """
        Calls AlphaVantage API and return the Weekly time series for the given market

            - **marketId**: string representing an AlphaVantage compatible market id
            - Returns **None** if an error occurs otherwise the pandas dataframe
        """
        self._wait_before_call()
        market = self._format_market_id(marketId)
        try:
            data, meta_data = self.TS.get_weekly(symbol=market)
            return data
        except Exception as e:
            logging.error("AlphaVantage wrong api call for {}".format(market))
            logging.debug(e)
            logging.debug(traceback.format_exc())
            logging.debug(sys.exc_info()[0])
        return None

    def quote_endpoint(self, market_id):
        """
        Calls AlphaVantage API and return the Quote Endpoint data for the given market

            - **market_id**: string representing the market id to fetch data of
            - Returns **None** if an error occurs otherwise the pandas dataframe
        """
        self._wait_before_call()
        market = self._format_market_id(market_id)
        try:
            data, meta_data = self.TS.get_quote_endpoint(
                symbol=market, outputsize="full"
            )
            return data
        except:
            logging.error("AlphaVantage wrong api call for {}".format(market))
        return None

    # Technical indicators

    def macdext(self, marketId, interval):
        """
        Calls AlphaVantage API and return the MACDEXT tech indicator series for the given market

            - **marketId**: string representing an AlphaVantage compatible market id
            - **interval**: string representing an AlphaVantage interval type
            - Returns **None** if an error occurs otherwise the pandas dataframe
        """
        self._wait_before_call()
        market = self._format_market_id(marketId)
        try:
            data, meta_data = self.TI.get_macdext(
                market,
                interval=interval.value,
                series_type="close",
                fastperiod=12,
                slowperiod=26,
                signalperiod=9,
                fastmatype=2,
                slowmatype=1,
                signalmatype=0,
            )
            if data is None:
                return None
            data.index = range(len(data))
            return data
        except Exception as e:
            logging.error("AlphaVantage wrong api call for {}".format(market))
            logging.debug(e)
            logging.debug(traceback.format_exc())
            logging.debug(sys.exc_info()[0])
        return None

    def macd(self, marketId, interval):
        """
        Calls AlphaVantage API and return the MACDEXT tech indicator series for the given market

            - **marketId**: string representing an AlphaVantage compatible market id
            - **interval**: string representing an AlphaVantage interval type
            - Returns **None** if an error occurs otherwise the pandas dataframe
        """
        self._wait_before_call()
        market = self._format_market_id(marketId)
        try:
            data, meta_data = self.TI.get_macd(
                market,
                interval=interval.value,
                series_type="close",
                fastperiod=12,
                slowperiod=26,
                signalperiod=9,
            )
            return data
        except Exception as e:
            logging.error("AlphaVantage wrong api call for {}".format(market))
            logging.debug(e)
            logging.debug(traceback.format_exc())
            logging.debug(sys.exc_info()[0])
        return None

    # Utils functions

    def _format_market_id(self, marketId):
        """
        Convert a standard market id to be compatible with AlphaVantage API.
        Adds the market exchange prefix (i.e. London is LON:)
        """
        return "{}:{}".format("LON", marketId.split("-")[0])

    def _wait_before_call(self):
        """
        Wait between API calls to not overload the server
        """
        while (dt.datetime.now() - self._last_call_ts) <= dt.timedelta(
            seconds=self.api_timeout
        ):
            time.sleep(0.5)
        self._last_call_ts = dt.datetime.now()
class AVInterface(StocksInterface):
    """
    AlphaVantage interface class, provides methods to call AlphaVantage API
    and return the result in useful format handling possible errors.
    """
    def initialise(self) -> None:
        logging.info("Initialising AVInterface...")
        api_key = self._config.get_credentials()["av_api_key"]
        self.TS = TimeSeries(key=api_key,
                             output_format="pandas",
                             treat_info_as_error=True)
        self.TI = TechIndicators(key=api_key,
                                 output_format="pandas",
                                 treat_info_as_error=True)

    def _to_av_interval(self, interval: Interval) -> AVInterval:
        """
        Convert the Broker Interval to AlphaVantage compatible intervals.
        Return the converted interval or None if a conversion is not available
        """
        if interval == Interval.MINUTE_1:
            return AVInterval.MIN_1
        elif interval == Interval.MINUTE_5:
            return AVInterval.MIN_5
        elif interval == Interval.MINUTE_15:
            return AVInterval.MIN_15
        elif interval == Interval.MINUTE_30:
            return AVInterval.MIN_30
        elif interval == Interval.HOUR:
            return AVInterval.MIN_60
        elif interval == Interval.DAY:
            return AVInterval.DAILY
        elif interval == Interval.WEEK:
            return AVInterval.WEEKLY
        elif interval == Interval.MONTH:
            return AVInterval.MONTHLY
        else:
            logging.error(
                "Unable to convert interval {} to AlphaVantage equivalent".
                format(interval.value))
            raise ValueError("Unsupported Interval value: {}".format(interval))

    def get_prices(self, market: Market, interval: Interval,
                   data_range: int) -> MarketHistory:
        data = None
        av_interval = self._to_av_interval(interval)
        if (av_interval == AVInterval.MIN_1 or av_interval == AVInterval.MIN_5
                or av_interval == AVInterval.MIN_15
                or av_interval == AVInterval.MIN_30
                or av_interval == AVInterval.MIN_60):
            data = self.intraday(market.id, av_interval)
        elif av_interval == AVInterval.DAILY:
            data = self.daily(market.id)
        elif av_interval == AVInterval.WEEKLY:
            data = self.weekly(market.id)
        # TODO implement monthly call
        else:
            raise ValueError("Unsupported Interval.{}".format(interval.name))
        history = MarketHistory(
            market,
            data.index,
            data["2. high"].values,
            data["3. low"].values,
            data["4. close"].values,
            data["5. volume"].values,
        )
        return history

    def daily(self, marketId: str) -> pandas.DataFrame:
        """
        Calls AlphaVantage API and return the Daily time series for the given market

            - **marketId**: string representing an AlphaVantage compatible market id
            - Returns **None** if an error occurs otherwise the pandas dataframe
        """
        self._wait_before_call(self._config.get_alphavantage_api_timeout())
        market = self._format_market_id(marketId)
        try:
            data, meta_data = self.TS.get_daily(symbol=market,
                                                outputsize="full")
            return data
        except Exception as e:
            print(e)
            logging.error("AlphaVantage wrong api call for {}".format(market))
            logging.debug(e)
            logging.debug(traceback.format_exc())
            logging.debug(sys.exc_info()[0])
        return None

    def intraday(self, marketId: str,
                 interval: AVInterval) -> pandas.DataFrame:
        """
        Calls AlphaVantage API and return the Intraday time series for the given market

            - **marketId**: string representing an AlphaVantage compatible market id
            - **interval**: string representing an AlphaVantage interval type
            - Returns **None** if an error occurs otherwise the pandas dataframe
        """
        self._wait_before_call(self._config.get_alphavantage_api_timeout())
        market = self._format_market_id(marketId)
        try:
            data, meta_data = self.TS.get_intraday(symbol=market,
                                                   interval=interval.value,
                                                   outputsize="full")
            return data
        except Exception as e:
            logging.error("AlphaVantage wrong api call for {}".format(market))
            logging.debug(e)
            logging.debug(traceback.format_exc())
            logging.debug(sys.exc_info()[0])
        return None

    def weekly(self, marketId: str) -> pandas.DataFrame:
        """
        Calls AlphaVantage API and return the Weekly time series for the given market

            - **marketId**: string representing an AlphaVantage compatible market id
            - Returns **None** if an error occurs otherwise the pandas dataframe
        """
        self._wait_before_call(self._config.get_alphavantage_api_timeout())
        market = self._format_market_id(marketId)
        try:
            data, meta_data = self.TS.get_weekly(symbol=market)
            return data
        except Exception as e:
            logging.error("AlphaVantage wrong api call for {}".format(market))
            logging.debug(e)
            logging.debug(traceback.format_exc())
            logging.debug(sys.exc_info()[0])
        return None

    def quote_endpoint(self, market_id: str) -> pandas.DataFrame:
        """
        Calls AlphaVantage API and return the Quote Endpoint data for the given market

            - **market_id**: string representing the market id to fetch data of
            - Returns **None** if an error occurs otherwise the pandas dataframe
        """
        self._wait_before_call(self._config.get_alphavantage_api_timeout())
        market = self._format_market_id(market_id)
        try:
            data, meta_data = self.TS.get_quote_endpoint(symbol=market,
                                                         outputsize="full")
            return data
        except Exception:
            logging.error("AlphaVantage wrong api call for {}".format(market))
        return None

    # Technical indicators

    def get_macd(self, market: Market, interval: Interval,
                 datapoints_range: int) -> MarketMACD:
        av_interval = self._to_av_interval(interval)
        data = self.macdext(market.id, av_interval)
        macd = MarketMACD(
            market,
            data.index,
            data["MACD"].values,
            data["MACD_Signal"].values,
            data["MACD_Hist"].values,
        )
        return macd

    def macdext(self, marketId: str, interval: AVInterval) -> pandas.DataFrame:
        """
        Calls AlphaVantage API and return the MACDEXT tech indicator series for the given market

            - **marketId**: string representing an AlphaVantage compatible market id
            - **interval**: string representing an AlphaVantage interval type
            - Returns **None** if an error occurs otherwise the pandas dataframe
        """
        self._wait_before_call(self._config.get_alphavantage_api_timeout())
        market = self._format_market_id(marketId)
        data, meta_data = self.TI.get_macdext(
            market,
            interval=interval.value,
            series_type="close",
            fastperiod=12,
            slowperiod=26,
            signalperiod=9,
            fastmatype=2,
            slowmatype=1,
            signalmatype=0,
        )
        return data

    def macd(self, marketId: str, interval: AVInterval) -> pandas.DataFrame:
        """
        Calls AlphaVantage API and return the MACDEXT tech indicator series for the given market

            - **marketId**: string representing an AlphaVantage compatible market id
            - **interval**: string representing an AlphaVantage interval type
            - Returns **None** if an error occurs otherwise the pandas dataframe
        """
        self._wait_before_call(self._config.get_alphavantage_api_timeout())
        market = self._format_market_id(marketId)
        data, meta_data = self.TI.get_macd(
            market,
            interval=interval.value,
            series_type="close",
            fastperiod=12,
            slowperiod=26,
            signalperiod=9,
        )
        return data

    # Utils functions

    def _format_market_id(self, marketId: str) -> str:
        """
        Convert a standard market id to be compatible with AlphaVantage API.
        Adds the market exchange prefix (i.e. London is LON:)
        """
        # TODO MarketProvider/IGInterface should return marketId without "-UK"
        return "{}:{}".format("LON", marketId.split("-")[0])
def index(request):
    form = nameofstock()
    price = 0.0
    m = money.objects.get(pk=1)
    amount = m.mymoney
    amount = round(amount, 2)
    rem = 1000000 - amount
    rem = round(rem, 2)
    close = []
    close1 = []
    close2 = []
    no = []
    no1 = []
    no2 = []
    s = ""
    labels = []
    datap = []
    DataFrame3 = "Table for Particular Stock"
    #rem=investments.objects.filter(field_name__isnull=True).aggregate(Sum('price'))
    query_results = investments.objects.all().order_by('-id')[:10]
    if request.method == 'POST':
        if ('stockname' in request.POST):
            form = nameofstock(request.POST)
            n = form.data['stockname']
            api_key = 'BJQZ9I2H012Q7FDD'
            ts = TimeSeries(key=api_key, output_format='json')
            data, meta_data = ts.get_quote_endpoint(n)
            price = float(data['05. price'])
            price = round(price, 2)
            if (price != 0.0):
                if (amount > price):
                    amount = amount - price
                    amount = round(amount, 2)
                    m.mymoney = amount
                    m.save()
                    t = time.localtime()
                    current_time = str(time.strftime("%H:%M:%S", t))
                    a = investments(name=n.upper(),
                                    price=price,
                                    date_created=str(date.today()),
                                    current_time=current_time)
                    a.save()
                    rem = 1000000 - amount
                    rem = round(rem, 2)
            #rem=investments.objects.filter(price__isnull=True).aggregate(Sum('price'))

            #if form.is_valid():
            #	pass
        elif ('sn' in request.POST):
            DataFrame3 = yf.download(request.POST['sn'],
                                     request.POST['sdate1'],
                                     request.POST['edate1'])
            DataFrame3 = DataFrame3.to_html()
        else:
            DataFrame = yf.download(request.POST['s'], request.POST['sdate'],
                                    request.POST['edate'])
            DataFrame1 = yf.download("AAPL", request.POST['sdate'],
                                     request.POST['edate'])
            DataFrame2 = yf.download("TSLA", request.POST['sdate'],
                                     request.POST['edate'])
            close = DataFrame['Close'].tolist()
            close1 = DataFrame1['Close'].tolist()
            close2 = DataFrame2['Close'].tolist()
            s = str(request.POST['s'])
            for i in range(len(close)):
                no.append(i + 1)
            for i in range(len(close1)):
                no1.append(i + 1)
            for i in range(len(close2)):
                no2.append(i + 1)

    d = dict()
    queryset = investments.objects.order_by('name')
    for stock in queryset:
        labels.append(stock.name)
        datap.append(stock.price)
    for i in range(len(labels)):
        if (labels[i] in d.keys()):
            d[labels[i]] += datap[i]
        else:
            d[labels[i]] = datap[i]
    labels = list(d.keys())
    datap = list(d.values())

    return render(
        request, 'portfolio/index.html', {
            'labels': labels,
            'datap': datap,
            'form': form,
            'price': price,
            'amount': amount,
            'query_results': query_results,
            'rem': rem,
            'close': close,
            'no': no,
            's': s,
            'close1': close1,
            'close2': close2,
            'no1': no1,
            'no2': no2,
            'DataFrame3': DataFrame3
        })
Exemple #24
0
def timeSeries(API_key, ticker):
  from alpha_vantage.timeseries import TimeSeries
  import matplotlib.pyplot as plt
  import mplfinance as mpf
  ts=TimeSeries(key=API_key, output_format='pandas')
  option=input('1. Intraday\n2. Daily\n3. Weekly\n4. Monthly\n5. Quote Endpoint\n6. Search Endpoint\n').lower()

  if option=='intraday' or option=='1':
    interval=int(input("Enter the interval:\n\t1. 1 minute\n\t2. 5 minutes\n\t3. 15 minutes\n\t4. 30 minutes\n\t5. 60 minutes\n"))
    inter=['','1min','5min','15min','30min','60min']
    data=ts.get_intraday(symbol=ticker, interval=inter[interval])[0]
    data.columns = ['Open', 'High', 'Low', 'Close', 'Volume']
    data.index.name = "Date"
    mpf.plot(data,
             type='candle', 
             title=f"Intraday Time series for the {ticker} stock {inter[interval]}",
             mav=(20), 
             volume=True, 
             tight_layout=True,
             style='yahoo')
   
    return data

  elif option=='daily' or option=='2':
    data=ts.get_daily_adjusted(symbol=ticker)[0]
    data.columns = ['Open', 'High', 'Low', 'Close', 'Adjusted_close','Volume','Dividend Amount','Split Coefficient']
    data.index.name = "Date"
    mpf.plot(data,
             type='candle', 
             title=f'Daily Time series for the {ticker} stock',
             mav=(20), 
             volume=True, 
             tight_layout=True,
             style='yahoo')
    return data

  elif option=='weekly' or option=='3':
    data=ts.get_weekly_adjusted(symbol=ticker)[0]
    data.columns = ['Open', 'High', 'Low', 'Close', 'Adjusted_close','Volume','Dividend Amount']
    data.index.name = "Date"
    mpf.plot(data,
             type='candle', 
             title=f'Weekly Time series for the {ticker} stock',
             mav=(20), 
             volume=True, 
             tight_layout=True,
             style='yahoo')
    return data

  elif option=='monthly' or option=='4':
    data=ts.get_monthly_adjusted(symbol=ticker)[0]
    data.columns = ['Open', 'High', 'Low', 'Close', 'Adjusted_close','Volume','Dividend Amount']
    data.index.name = "Date"
    mpf.plot(data,
             type='candle', 
             title=f'Monthly Time series for the {ticker} stock',
             mav=(20), 
             volume=True, 
             tight_layout=True,
             style='yahoo')
    return data

  elif option=='quote endpoint' or option=='5':
    data=ts.get_quote_endpoint(symbol=ticker)[0]
    return data

  elif option=='search endpoint' or option=='6':
    keywords=input('Enter the Name of the Stock:\n')
    data=ts.get_symbol_search(keywords=keywords)[0]
    return data
    
  else:
    print("CANNOT RECOGNIZE")
Exemple #25
0
class Strat(object):
    def __init__(self):
        self.key = 'your_alphavantage_key_here'
        self.ts = TimeSeries(self.key, output_format='pandas')
        self.ti = TechIndicators(self.key, output_format='pandas')
        self.secinfo = {}

    def dt64_to_dt(self, date):
        # Takes in the numpy dt64 and returns a dt object
        timestamp = ((date - np.datetime64('1970-01-01T00:00:00')) /
                     np.timedelta64(1, 's'))
        return datetime.datetime.utcfromtimestamp(timestamp)

    def get_daily_ts(self, ticker):
        # Gets 5min intraday from alpha vantage, unless has an existing updated one stored within last 6.5h
        # That way, will still be updated if I try on the last minute of any trading day if was called at its start
        if self.secinfo.get(ticker) and self.is_up_to_date(ticker, 390):
            return self.secinfo[ticker][0]
        else:
            data, inf = self.ts.get_daily(symbol=ticker, outputsize='full')
            # Store data in dict to avoid API calls if possible, include timestamp to know when update needed
            data.index = data.index.map(self.dt64_to_dt)
            self.secinfo[ticker] = (data, datetime.datetime.now())
            return data

    def get_intraday_ts(self, ticker, interv):
        # Gets 5min intraday from alpha vantage, unless has an existing updated one stored
        strint = str(interv)
        if self.secinfo.get(ticker + strint + 'min') and self.is_up_to_date(
                ticker + strint + 'min', 5):
            return self.secinfo[ticker + strint + 'min'][0]
        else:
            data, inf = self.ts.get_intraday(symbol=ticker,
                                             interval=strint + 'min',
                                             outputsize='full')
            # Store data in dict to avoid API calls if possible, include timestamp to know when update needed
            data.index = data.index.map(self.dt64_to_dt)
            self.secinfo[ticker + strint + 'min'] = (data,
                                                     datetime.datetime.now())
            return data

    def get_ts_for_day(self, ticker, interv, offset=0):
        data = self.get_intraday_ts(ticker, interv)
        tod = datetime.datetime.now().date() - datetime.timedelta(days=offset)
        todaydata = data[data.index.date == tod]
        return todaydata

    def get_curr_price_chng(self, ticker, offset=0):
        # Returns the percent price change since beginning of day
        if self.secinfo.get(ticker + 'price_change') and self.is_up_to_date(
                ticker + 'price_change', 5):
            return self.secinfo[ticker + 'price_change'][0]

        else:
            # Alpha vantage doesn't have a way to select just current day's price, so
            # Get 5 min intraday and select first entry, calculate % difference
            todaydata = self.get_ts_for_day(ticker, 5, offset)
            price_change = (todaydata['4. close'].values[-1] -
                            todaydata['4. close'].values[0]
                            ) / todaydata['4. close'].values[0]
            self.secinfo[ticker + 'price_change'] = (price_change,
                                                     datetime.datetime.now())
            return price_change

    def get_quote(self, ticker):
        # Gets quote from alpha vantage, unless has an existing updated one stored
        if self.secinfo.get(ticker + 'quote') and self.is_up_to_date(
                ticker + 'quote', 5):
            return self.secinfo[ticker + 'quote'][0]
        else:
            data = self.ts.get_quote_endpoint(symbol=ticker)
            # Store data in dict to avoid API calls if possible, include timestamp to know when update needed
            self.secinfo[ticker + 'quote'] = (data, datetime.datetime.now())
            return data

    def get_curr_price_vol(self, ticker):
        # returns current price and volume of stock

        data = self.get_quote(ticker)
        price = float(data[0]['05. price'].values[0])
        vol = float(data[0]['06. volume'].values[0])
        self.secinfo[ticker + 'price_vol'] = (price, vol,
                                              datetime.datetime.now())

        return (price, vol)

    def is_up_to_date(self, info, recency):
        # Takes type of info (ticker+price_change,quote,price_vol,etc), and recency in minutes
        # Checks whether data has been updated in the last 5 min
        return datetime.datetime.now(
        ) - self.secinfo[info][-1] <= datetime.timedelta(minutes=recency)

    def has_bodyless_sticks(self, ticker, offset=0):
        # Checks if and how many bodyless sticks the stock has since day start
        if self.secinfo.get(ticker + 'bodyless') and self.is_up_to_date(
                ticker + 'bodyless', 5):
            return self.secinfo[ticker + 'bodyless'][0]

        else:
            # Alpha vantage doesn't have a way to select just current day's price, so
            # Get 5 min intraday and select first entry, calculate % difference
            todaydata = self.get_ts_for_day(ticker, 5, offset=offset)
            body = (todaydata['4. close'].values -
                    todaydata['1. open'].values) / todaydata['1. open'].values
            noofbodyless = len([b for b in body if abs(b) < 1.0e-4])
            too_many_bodyless = noofbodyless >= 2
            self.secinfo[ticker + 'bodyless'] = (too_many_bodyless,
                                                 datetime.datetime.now())
            return too_many_bodyless

    def get_intra_sma(self, ticker, interv, period, plot=False, offset=0):
        # Takes ticker, period, and interval as strings, and returns the daily sma as pd series for noof offset days ago
        strint, strper = str(interv), str(period)
        tod = (datetime.datetime.now() -
               datetime.timedelta(days=offset)).date()
        strtod = tod.strftime("%Y/%m/%d")
        # Check if updated data already exists in dict
        if self.secinfo.get(ticker+strint+'m_sma_'+strper+'p_'+strtod) and \
        self.is_up_to_date(ticker+strint+'m_sma_'+strper+'p_'+strtod,5):
            return self.secinfo[ticker + strint + 'm_sma_' + strper + 'p_' +
                                strtod][0]

        else:
            close = self.get_intraday_ts(ticker, interv)['4. close']
            sma = talib.SMA(close, timeperiod=period)
            todsma = sma[sma.index.date == tod]
            smadf = pd.DataFrame({'SMA': todsma})
            self.secinfo[ticker + strint + 'm_sma_' + strper + 'p_' +
                         strtod] = (smadf, datetime.datetime.now())
        if plot:
            plt.figure(figsize=(20, 6))
            plt.plot(todaydata)
            plt.show()

        else:
            pass
        return smadf

    def get_daily_sma(self, ticker, period=20, plot=False):
        # Takes ticker, interval, period, plot, returns the sma as pd series for longer period
        strper = str(period)
        # Check if updated data exists in dict
        if self.secinfo.get(ticker+'daily_sma_'+strper+'p') and \
        self.is_up_to_date(ticker+'daily_sma_'+strper+'p',5):
            return self.secinfo[ticker + 'daily_sma_' + strper + 'p'][0]

        else:
            close = self.get_daily_ts(ticker)['4. close']
            sma = talib.SMA(close, timeperiod=period)
            self.secinfo[ticker + 'daily_sma_' + strper +
                         'p'] = (sma, datetime.datetime.now())

        if plot:
            plt.figure(figsize=(20, 6))
            plt.plot(sma)
            plt.show()
        return sma

    def check_sticks_sma(self, ticker, tolerance=80, mov=True, offset=0):
        # Checks if tolerance% of sticks for given day are above/below the SMA (depending on mov:1up,0down)
        # True if fe. 80% sticks are above sma on an upward trend
        data = self.get_ts_for_day(ticker, 5, offset)
        sma = self.get_intra_sma(ticker, 5, 8)
        datalen = len(data)
        newdata = pd.concat([data, sma], axis=1)
        if mov:
            sticks = newdata['4. close'] - newdata['SMA']
            return len(sticks[sticks > 0]) >= 0.01 * tolerance * datalen
        else:
            sticks = newdata['SMA'] - newdata['1. open']
            return len(sticks[sticks > 0]) >= 0.01 * tolerance * datalen

    def check_noof_plbcks(self, ticker, tolerance=80, mov=True, offset=0):
        # Returns true if pullbacks account for fe. 1-tolerance% or less of all 5min movements
        data = self.get_ts_for_day(ticker, 5, offset)
        datalen = len(data)
        if mov:
            mvmnt = data['4. close'] - data['1. open']
            return len(mvmnt[mvmnt > 0]) >= 0.01 * tolerance * datalen
        else:
            mvmnt = data['1. open'] - newdata['4. close']
            return len(mvmnt[mvmnt > 0]) >= 0.01 * tolerance * datalen

    def check_sizeof_plbcks(self, ticker, tolerance=3, mov=True, offset=0):
        #Returns true if each pullback ends no lower than the hit tolerance periods ago
        data = self.get_ts_for_day(ticker, 5, offset)
        datalen = len(data)
        if mov:
            myser = data['1. open'].shift(periods=tolerance)
            data = data.iloc[tolerance:].assign(before=myser.iloc[tolerance:])
            checkdata = data[data['4. close'] < data['before']]
            return len(checkdata) == 0
        else:
            myser = data['1. open'].shift(periods=tolerance)
            data = data.iloc[tolerance:].assign(before=myser.iloc[tolerance:])
            checkdata = data[(data['4. close'] > data['before'])]
            return len(checkdata) == 0

    def get_opt_info(self):
        # Expand to pass as params the ticker, date, other things that interest us
        atr = AllyTrader()
        res = atr.get_option_info()
        return res

    def analyze_stonks(self, l, offset=0):
        # Takes a list of stock tickers, prints dict of strategy stats for each,
        # The count of 5 is due to alpha vantage hits limitations
        dict = {}
        counter = 0

        for s in l:
            if counter != 5:
                try:
                    d={'prc_chng':st.get_curr_price_chng(s,offset=offset),\
                    'bodyless_sticks':st.has_bodyless_sticks(s,offset=offset),\
                    'sticks_sma':st.check_sticks_sma(s,offset=offset),\
                    'noof_plbcks':st.check_noof_plbcks(s,offset=offset),\
                    'sizeof_plbcks':st.check_sizeof_plbcks(s,offset=offset)}
                    print("Got stats for", s)
                    dict[s] = d
                    counter += 1
                except:
                    print("could not get data for ", s)
                    print(sys.exc_info()[0])
            else:
                print("sleeping")
                time.sleep(60)
                counter = 0

        for k, v in zip(dict.keys(), dict.values()):
            print(k, ":", v, '\n')
Exemple #26
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
Exemple #27
0
from qifparse.parser import QifParser
from alpha_vantage.timeseries import TimeSeries
import time

ts = TimeSeries(key='5I186NCN3TF27H5P', output_format='csv')
file = open('QuickenExport.QIF')
qif = QifParser.parse(file)

print("Parsed it ...")

quotes = set()
for price in qif.get_prices():
    quotes.add(price.name)

print(quotes)

newquotes = {}
outstring = ""
for quote in quotes:
    data, meta_data = ts.get_quote_endpoint(quote)
    data = list(data)
    if len(data) == 2:
        price = float(list(data)[1][4])
        #print(quote)
        outstring += "%s, %.3f\n" % (quote, price)
    # unpayed acces to apha vantage needs 12 seconds between every parse
    time.sleep(12)
outfile = open('LatestStockPrices.csv', 'w')
outfile.write(outstring)
file.close()
Exemple #28
0
client.on_publish = on_publish

################################################################
# Main Loop                                                    #
################################################################
while True:
    # Start Time
    start = time.time()

    try:
        # Poll for data
        tickers = getConfigList(config.get("CONFIG", "tickers"))
        ts = TimeSeries(key=config.get("SECRET", "api_key"))

        with ThreadPoolExecutor() as executer:
            data = executer.map(
                      lambda stock:ts.get_quote_endpoint(symbol=stock),
                      tickers)
        for item in data:
            publish(item[0]["01. symbol"], item[0]["05. price"])

    except Exception as e:
        log.error(
            "Error polling data: {}".format(e))

    # Calculate Sleep Timer
    interval = time.time() - start
    sleep = config.getint("CONFIG", "interval") - interval
    if sleep > 0:
        time.sleep(sleep)
Exemple #29
0
def stockQuote(symbol):
    ts = TimeSeries(key=key, output_format='pandas')
    data, meta_data = ts.get_quote_endpoint(symbol)

    cPrice = data.iloc[0, 4]
    currentPrice = float(cPrice)
Exemple #30
0
class AlphaVantageClient:
    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 = TimeSeries(key=default_api_key,
                                     output_format='pandas')
        else:
            self.ts = TimeSeries(key=api_key, output_format='pandas')

    def get_data(self,
                 symbol,
                 freq='daily',
                 adjusted=True,
                 interval='15min',
                 outputsize='full'):
        """ Return time series in pandas formet.
        Keyword Arguments:
            symbol:  the symbol for the equity we want to get its data
            freq: frequency of data, supported values are 'daily', 'weekly', 'monthly' (default 'daily'). Currently not support for 'intraday'
            adjusted: adjust the OHLC value (default True)
            interval:  time interval between two conscutive values, used when freq is intraday
                supported values are '1min', '5min', '15min', '30min', '60min'
                (default '15min')
            outputsize:  The size of the call, supported values are
                'compact' and 'full; the first returns the last 100 points in the
                data series, and 'full' returns the full-length intraday times
                series, commonly above 1MB (default 'compact')
        """
        key = '{}-{}'.format(freq, adjusted)

        # elif key == 'intraday-True':
        #     data, _ = self.ts.get_intraday(symbol=symbol, interval=interval, outputsize=outputsize)
        # elif key == 'intraday-False':
        #     data, _ = self.ts.get_intraday(symbol=symbol, interval=interval, outputsize=outputsize)

        if key == 'daily-True':
            data, _ = self.ts.get_daily_adjusted(symbol=symbol,
                                                 outputsize=outputsize)
        elif key == 'daily-False':
            data, _ = self.ts.get_daily(symbol=symbol, outputsize=outputsize)
        elif key == 'weekly-True':
            data, _ = self.ts.get_weekly_adjusted(symbol=symbol)
        elif key == 'weekly-False':
            data, _ = self.ts.get_weekly(symbol=symbol)
        elif key == 'monthly-True':
            data, _ = self.ts.get_monthly_adjusted(symbol=symbol)
        elif key == 'monthly-False':
            data, _ = self.ts.get_monthly(symbol=symbol)
        else:
            raise Warning(
                'Freq: {} or Adjusted: {} is not valid. Default to Daily Adjusted.'
            )
            data, _ = self.ts.get_daily_adjusted(symbol=symbol,
                                                 outputsize=outputsize)

        if freq == 'intraday':
            data.columns = ['Open', 'High', 'Low', 'Close', 'Volume']
        else:
            columns_name = [
                'Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume',
                'Dividends', 'Stock Splits'
            ]
            data.columns = columns_name[:len(data.columns)]

        data = data.rename(index={'date': 'Date'})

        return data.sort_index(ascending=True)

    def get_latest_data(self, symbol):
        """ Return the latest price and volume information for a security of your choice 
        Keyword Arguments:
            symbol:  the symbol for the equity we want to get its data
        """
        data, _ = self.ts.get_quote_endpoint(symbol=symbol)

        columns_name = [
            'Open', 'High', 'Low', 'Price', 'Volume', 'Date', 'Previous Close',
            'Change', 'Change Pct'
        ]
        data = data.iloc[:, 1:]
        data.columns = columns_name
        data = data.set_index(['Date'])

        return data