def btnSearchScript(self): try: ts = TimeSeries(self.key, output_format='pandas') self.searchTuple = ts.get_symbol_search( self.search_symbol_combo.get()) #print(searchTuple[0].columns) #print(searchTuple[0].values) search_values_list = list() self.search_symbol_combo['values'] = search_values_list for i in range(len(self.searchTuple[0].values)): search_values_list.append(self.searchTuple[0].values[i][0] + "--" + self.searchTuple[0].values[i][1]) self.search_symbol_combo['values'] = search_values_list self.search_symbol_combo.focus_force() self.search_symbol_combo.event_generate('<Down>') except Exception as e: msgbx.showerror("Search Symbol Error", str(e)) self.search_symbol_combo.focus_force() return
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
def company_search(query): found = [] ts = TimeSeries(key=settings.ALPHA_VANTAGE_API_KEY) companies, _ = ts.get_symbol_search(query) for company in companies: found.append(save_company(company)) return found
def StockSearch(searchQuery): # try to search for stock try: # initiate timeseries alpha vantage api ts = TimeSeries(key=apiKey, output_format='json') # get data from search query data = ts.get_symbol_search(searchQuery) # take the first item from data data = data[0] # create list for search results searchResults = [] # for each item in data for item in data: # add item ticker and item name to the search results searchResults.append([item['1. symbol'], item['2. name']]) # sort results based on stock ticker searchResults = sorted(searchResults, key=lambda x: x[0]) # if search results are empty if searchResults == []: # return error message return '> Sorry, there were no results for this search term!' # create string for filtered search results filteredSearchResults = '**Search Results** \n' # for each item in search results for item in searchResults: # open text file of listings with open('StockListings.txt', 'r') as file: # read each line from file for line in file: # check if line contains stock ticker + '|' if (str(item[0]) + '|') in line: # if line contains stock ticker + '|' add to result string filteredSearchResults += '> ' + str( item[0]) + ' - ' + str(item[1]) + '\n' break # close file file.close() # return search results string return filteredSearchResults # if an error occurs except: # print error message print('An error occurred in AlphaVantage.StockSearch') # return error string return '> Sorry, an error occurred while getting the search results!'
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("Конец обработки исключения")
def look_it_up(keyword): #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=keyword) x[0].reset_index(inplace=True) x[0].columns = [ 'date', 'symbol', 'name', 'type', 'region', 'marketOpen', 'marketClose', 'timezone', 'currency', 'matchScore' ] x[0] return x[0]
def searchPage(request): try: api_key = 'EADU97JO5Z1TCYPV' input_symbol = request.POST['s'] ts = TimeSeries(key=api_key, output_format='pandas') tz_NY = pytz.timezone('US/Pacific') datetime_NY = datetime.now(tz_NY) current_time = datetime_NY.strftime("%a %b %d %H:%M:%S %Z %Y") # r = requests.get('https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords='+value_A & 'apikey='+api_key) r = ts.get_symbol_search(keywords=input_symbol) data, meta_data1 = ts.get_daily(symbol=input_symbol, outputsize='full') # result = r.json() # full_name = result['bestMatches'][0]['2. name'] full_name = r[0]['2. name'][0] close_data = data['4. close'] num_change = round(close_data[0] - close_data[1], 2) percentage_change = round(num_change / close_data[1] * 100, 2) if num_change > 0: num_change = '+' + str(num_change) else: num_change = '-' + str(num_change) if percentage_change > 0: percentage_change = '+' + str(percentage_change) + '%' else: percentage_change = '-' + str(percentage_change) + '%' return render(request, 'search.html', context={ 'data1': current_time, 'data2': full_name, 'data3': close_data[0], 'data4': num_change, 'data5': percentage_change }) except Exception: return render(request, 'err.html')
class MarketData: """ Class for holding market data """ def __init__(self): """ Initialize the MarketData object """ # Create storage for each stock. Each stock is represented as an entry # in the following dictionary. This allows caching each stock that is # queried so we don't need to look it up a second time. Each stock id # references a pandas dataframe storing open, close, high, low, and # volume trading data for the past 20 years self.stock_data = dict() # Keep track of some information associated with the stock self.stock_info = dict() # Update the column names self.data_cols = { '1. open': 'open', '2. high': 'high', '3. low': 'low', '4. close': 'close', '5. adjusted close': 'closeAdj', '6. volume': 'volume', '7. dividend amount': 'dividend', '8. split coefficient': 'splitcoeff' } # Stock info column names self.info_cols = {'1. symbol': 'symbol', '2. name': 'name'} # Set the bar colors self.line_colors = ['black', 'red', 'blue', 'green', 'orange'] self.setcolors(False) # Setup the query objects self.timeseries = TimeSeries(os.environ['AVTOKEN'], output_format='pandas') def setcolors(self, cbf=False): """ Sets the bar colors for candlestick plot Parameters ---------- cbf : bool True if color-blind friendly colors should be used """ # Colorblind friendly colors? if cbf: self.colors = {'inc': 'blue', 'dec': 'orange'} # Red/green are fine else: self.colors = {'inc': 'lightgreen', 'dec': 'red'} def queryStocks(self, symbols): """ Extracts the latest stock information and stores it Parameters ---------- symbols : list(str) List of symbols to query for Returns ------- Error message string if an error occurs. """ # Track whether there was an error errMsg = None # Loop on each symbol for sym in symbols: if sym not in self.stock_data.keys(): try: # Get info regarding this symbol if sym not in ['DJI', 'SPX']: try: # Download information about the stock symbol info = self.timeseries.get_symbol_search(sym) info_df = pd.DataFrame(info[0]) info_df.index = info_df.index.astype(int) info_df['9. matchScore'] = info_df[ '9. matchScore'].astype(float) except IndexError as err: errMsg = f'Symbol not found: {sym}' break # If the first symbol does not return a 100% value if (info_df['9. matchScore'][0] < 1.0): raise ValueError( self.format_symbol_opts(sym, info_df)) break # Handle stock indexes for Dow and S&P else: info_df = pd.DataFrame( [[sym, sym]], columns=['1. symbol', '2. name']) # Get the data for this symbol dat = self.timeseries.get_daily_adjusted(symbol=sym, outputsize='full') except ValueError as err: errMsg = err break # Store the data in a dataframe market_df = pd.DataFrame(dat[0]) market_df['datetime'] = pd.to_datetime(market_df.index) # Store the dataframe self.stock_data[sym] = market_df.rename(columns=self.data_cols) self.stock_info[sym] = info_df.rename(columns=self.info_cols) return errMsg def format_symbol_opts(self, sym, df): """ Format returned symbol information for easy to read info Parameters ---------- df : pandas.DataFrame Represents the returned information Returns ------- Formatted list of similar sybols """ n = '<br/>' # Setup the message message = f"No symbol matching \"{sym}\" found.{n}Try one of the following:{n}{n}" message += f" Symbol (<i>Name, Region</i>){n}" message += f"------------------------{n}" # Append each possible match for row in df.itertuples(): new_sym = row[1] new_name = row[2] region = row[4] message += f" {new_sym: <8} (<i>{new_name}, {region}</i>){n}" return message def moving_avg(self, values, window=5): """ Compute the moving average for a distribution Parameters ---------- values : array Array object of values to compute the moving avarage of window : int Number of values to compute the average for Returns ------- Array representing the moving average """ # Create a return array size = len(values) mvavg = np.zeros(size) # Loop through the list of values w2 = int(window / 2) for i in range(size): # Get the range for summing start = i - w2 if i >= w2 else 0 stop = i + w2 if i < size - w2 else size - 1 # Compute moving average mvavg[i] = np.sum(values[start:stop + 1]) / (stop - start + 1) return mvavg def plotCandlesticks(self, symbol, days2show=100): """ Plots the stock information for all symbols in 'symbols'. Parameters ---------- symbols : list(str) Python list of symbols to be plotted days2show : int Initial number of days to show data for when plot first loads Returns ------- bokeh.plotting.figure object """ # Get the data associated with this symbol df = self.stock_data[symbol] info = self.stock_info[symbol] # Get indices for increasing/decresing market days inc = df.close > df.open dec = df.open > df.close # Specify the width of the bars w = 20 * 60 * 60 * 1000 # half day in ms # Define over tooltips hover = HoverTool(tooltips=[('Date', '@datetime{%F}'), ('Open', '$@open{0.2f}'), ('Adj. Close', '$@closeAdj{0.2f}'), ('High', '$@high{0.2f}'), ('Low', '$@low{0.2f}'), ('Volume', '@volume{0.00 a}')], formatters={'@datetime': 'datetime'}, names=['segments']) # Define the tools for user manipulation of figure TOOLS = ['pan', 'wheel_zoom', 'box_zoom', 'reset', 'save', hover] # Specify the range of the x,y axes for visibility xstop = df.datetime[0] + relativedelta(days=3) xstart = xstop - relativedelta(days=days2show) ystart = 0.95 * np.min(df.low[:days2show]) ystop = 1.05 * np.max(df.high[:days2show]) # Setup the figure for plotting p1 = figure( x_axis_type='datetime', tools=TOOLS, x_range=(xstart, xstop), y_range=(ystart, ystop), x_axis_location='above', y_axis_label='Price ($USD)', plot_width=750, plot_height=300, title=f"Stock Price Data: {info['name'][0]} ({info['symbol'][0]})") p1.grid.grid_line_alpha = 0.3 # Generate the plots p1.segment('datetime', 'high', 'datetime', 'low', source=ColumnDataSource(df), color="black", line_width=2, name='segments') p1.vbar(df.datetime[inc], w, df.open[inc], df.close[inc], name='incbar', fill_color=self.colors['inc'], line_color="black", line_width=0.5) p1.vbar(df.datetime[dec], w, df.open[dec], df.close[dec], name='decbar', fill_color=self.colors['dec'], line_color="black", line_width=0.5) # Get moving average of high and low mvavg_lo = self.moving_avg(df.low.to_numpy()) mvavg_hi = self.moving_avg(df.high.to_numpy()) # p.line(df.datetime, mvavg_hi, line_color='blue') # p.line(df.datetime, mvavg_lo, line_color='red') p2 = figure(x_axis_type="datetime", x_range=p1.x_range, x_axis_label='Date', y_axis_label=r'Volume (millions)', plot_width=750, plot_height=140) p2.grid.grid_line_alpha = 0.3 p2.vbar(df.datetime[inc], w, 0, df.volume[inc] * 1e-6, fill_color=self.colors['inc'], line_color='black', line_width=0.5) p2.vbar(df.datetime[dec], w, 0, df.volume[dec] * 1e-6, fill_color=self.colors['dec'], line_color='black', line_width=0.5) # Combine all the plots p = gridplot([p1, p2], ncols=1) return p def plotStocks(self, symbols, param, days2show=100): """ Plots the stock information for all symbols in 'symbols'. Parameters ---------- symbols : list(str) Python list of symbols to be plotted param : str Parameter to plot (open, close, high, low, volume) days2show : int Initial number of days to show data for when plot first loads Returns ------- bokeh.plotting.figure object """ # Define the tools for user manipulation of figure TOOLS = ['pan', 'wheel_zoom', 'box_zoom', 'reset', 'save'] # Define the starting range to be the last 100 days xstop = datetime.datetime.now() + relativedelta(days=3) xstart = xstop - relativedelta(days=days2show) ystart = 1e30 ystop = -1e30 # Setup the figure for plotting p = figure(x_axis_type="datetime", tools=TOOLS, x_range=(xstart, xstop), plot_width=750, plot_height=400, x_axis_label='Date', y_axis_label=param, title=f"{param.upper()} Data: {', '.join(symbols)}") for s, sym in enumerate(symbols): # Get the data associated with this symbol df = self.stock_data[sym] info = self.stock_info[sym] # Specify the range of the x,y axes ystart = min(ystart, np.min(df[param][:days2show])) ystop = max(ystop, np.max(df[param][:days2show])) # Add the next line plot color_indx = s % len(self.line_colors) p.line(df.datetime, df[param], line_color=self.line_colors[color_indx], legend_label=info.name[0]) # Update the range of x,y p.y_range = Range1d(0.95 * ystart, 1.05 * ystop) # Setup the legend p.legend.location = "top_left" return p def plot(self, symbols, param='closeAdj', cbf=False): """ Parameters ---------- symbols : list() Python list of symbols to be plotted param : str Parameter to be plotted for multi-symbol plots cbf : bool Whether color blind friendly colors should be used Returns ------- (script,div) for showing the plots in the webpage """ # Update colors if colorblind friendly self.setcolors(cbf) # Get the actual figure to be plotted p = None if len(symbols) == 1: p = self.plotCandlesticks(symbols[0]) else: p = self.plotStocks(symbols, param) return components(p)
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")