def download_json_data(companies, mode): ts = TimeSeries(key='8T5R3MKIOEJGAL8F', output_format='json', retries=10) data, meta_data = {}, {} for company in companies: if mode == 'daily': data[company], meta_data[company] = ts.get_daily_adjusted( symbol=company, outputsize='full') elif mode == 'monthly': data[company], meta_data[company] = ts.get_monthly_adjusted( symbol=company) elif mode == 'intraday': data[company], meta_data[company] = ts.get_intraday( symbol=company, interval='1min', outputsize='full') elif mode == 'batch': data[company], meta_data[company] = ts.get_batch_stock_quotes( companies) return data else: print( "Only supported modes are 'daily','monthly', 'intraday', 'batch'" ) return data print("Finished: " + company) time.sleep(12) return data
def alphaVantage(tickers=ListSymbols().listSymbols()): ts = TimeSeries(key='XYI5EZUJ5CS5BI3E', output_format='pandas', retries=5) engine = mod.engine('Symbols', 'test_user', 'password', 'localhost') listTickers = [] count = 0 for tick in tickers: end.end() count = count + 1 listTickers.append(tick) if count == 100: time.sleep(10) try: dfHolder, meta_data = ts.get_batch_stock_quotes(listTickers) dfSymbols = dfHolder['1. symbol'] if counter == 0: dfSymbols.to_sql('AlphaSymbols', engine, if_exists='replace') else: dfSymbols.to_sql('AlphaSymbols', engine, if_exists='append') except: print("except") pass count = 0 listTickers = [] print(dfSymbols)
async def price(ctx, *symbols: str): output_msg = "" ts = TimeSeries(key=os.environ['ALPHA_VANTAGE_API_KEY']) data = ts.get_batch_stock_quotes(symbols)[0] for quote in data: output_msg += get_formatted_data(quote) + "\n" await bot.say(output_msg)
def get_current_value(self, obj): stock = TimeSeries('WN9UYF2SGX9V3P0S') data, meta_data = stock.get_batch_stock_quotes(symbols=obj.ticker) current_market = data[0] currency = ForeignExchange(key='WN9UYF2SGX9V3P0S') data = currency.get_currency_exchange_rate(from_currency='EUR', to_currency='USD') currency_value = data[0] return_statmenet = float(currency_value['5. Exchange Rate'])*float(current_market['2. price'])*obj.shares return return_statmenet
from alpha_vantage.timeseries import TimeSeries import matplotlib.pyplot as plt ts = TimeSeries(key='MYQVQFDERJGBAOM5', output_format='pandas') data, meta_data = ts.get_batch_stock_quotes(symbols='MSFT,FB,AAPL') plt.plot() plt.title('Intraday Times Series for the MSFT stock (1 min)') plt.show()
class Tracker: def __init__(self): self.ALPHA_VANTAGE_KEY = 'EY2QBMV6MD9FX9CP' self.TODAY = datetime.datetime.today() self.WAGO_DT = 7 self.MAGO_DT = 28 self.ts = TimeSeries(key=self.ALPHA_VANTAGE_KEY) self.stocks = None self.period = None self.opens = None self.currents = {} return def read_stocks(self, stockfile): """ Specify stocks to track via an input file. Expected to be upgraded to hit a majority of S&P stocks or industries in future :param stockfile: file with new line separated stock tickers to track :return: Nothing """ with open(stockfile, 'r') as f: stocks = [line.strip() for line in f] stocks = [x for x in stocks if x] # In case there's an extra blank space self.stocks = stocks return def specify_stocks(self, list_of_stocks): """ Input specific stocks to check instead of going fromt he list :param list_of_stocks: List of str tickers :return: Nothing """ self.stocks = list_of_stocks return def set_update_period(self, period): """ Set the interval with which to update stock prices. Note that alpha_vantage has some issues with rapid stock grabbing. Over 1 min should be plenty :param period: Period between updates, in seconds :return: N/A """ self.period = period return def get_date_days_ago(self, dt): """ Get the date a certain number of days ago :param dt: Days difference, in number of days :return: Historical Date as a string """ return str(self.TODAY - datetime.timedelta(dt)).split()[0] def grab_av_stock_data(self, fun, s): """ Continuously attempt to grab alpha_vantage stock data Time delay of 10 seconds if we over-ping outputsize flag allows us to only get last 100 days fun lets us use this same function for batch quotes and opens :param fun: Function to ping alpha vantage with :param s: stock to get :return: daily opens for a stock for last 100 days """ successful_grab = False stock_data = None while successful_grab is not True: try: if fun == 'opens': stock_data, _ = self.ts.get_daily_adjusted( s, outputsize='compact') elif fun == 'quotes': stock_data, _ = self.ts.get_batch_stock_quotes( symbols=self.stocks) else: print("Function Not Valid") return successful_grab = True except ValueError: print('Sleeping for 10') time.sleep(10) return stock_data def get_opens(self): """ Get the opens from today, a week ago (WAGO) and a month ago (MAGO) for stocks If today, month or week ago was a holiday or weekend, look at the nearest earlier date with data This might shit itself on weekends Store as self.opens for bugfixing and checking later :return: nx3 DataFrame, n is number of stocks to look at """ opens = pd.DataFrame(index=self.stocks, columns=['Today', 'WAGO', 'MAGO']) for s in self.stocks: print('Collecting {} data'.format(s)) daily_opens = self.grab_av_stock_data('opens', s) three_opens = [] for days_ago in [0, self.WAGO_DT, self.MAGO_DT]: date = self.get_date_days_ago(days_ago) while date not in daily_opens: days_ago += 1 date = self.get_date_days_ago(days_ago) open_price = float(daily_opens[date]['1. open']) three_opens.append(open_price) opens.loc[s, :] = three_opens time.sleep(1) # AlphaVantage don't hate me self.opens = opens return opens def get_currents(self): """ Get current quotes from stocks and store with a time index :return: nx3 DataFrame with current price as all three columns per stock """ currents = pd.DataFrame(index=self.stocks, columns=['Today', 'WAGO', 'MAGO'], dtype=float) data = self.grab_av_stock_data('quotes', None) price_quotes = [(s['1. symbol'], float(s['2. price'])) for s in data] for (a, b) in price_quotes: currents.loc[a, :] = b # Store all the calls within the object, for looking at later self.store_currents(currents['Today']) return currents def generate_block_update(self, opens, currents): """ Create a single update df with changes and opens for today, MAGO, WAGO, and current quote :param opens: dataframe of open prices for stocks, from get_opens :param currents: Current stock prices, outputted from get_currents :return: nx7 df with Changes (x3), Current, Opens (x3) """ change = ((currents / opens) - 1) * 100 update = pd.concat([change, currents['Today'], self.opens], axis=1) update.columns = [ 'Today_Chg', 'WAGO_Chg', 'MAGO_Chg', 'Current', 'Today_Open', 'WAGO_Open', 'MAGO_Open' ] return update def store_currents(self, current_prices): """ Every time current prices are called, store them This is for future debugging and evaluating purposes :param current_prices: df of current prices :return: N/A """ time_now = datetime.datetime.now().time() self.currents[time_now] = current_prices return def run(self): """ Run the entire stock tracking system :return: """ opens = self.get_opens() while True: currents = self.get_currents() update = self.generate_block_update(opens, currents) print(update) print('\n') time.sleep(self.period)
'given-name': 'Michael', 'number': '11111', 'currentmarketvalue': 'yes' } ts1 = TimeSeries(key=apikey, output_format='pandas', indexing_type='integer') fname = parameters['given-name'] currentvalue = parameters['currentmarketvalue'] folio = parameters['number'] invst['Name'] = invst['Name'].astype('category') invst = invst[(invst['Name'].str.contains(fname, case=False)) & (invst['Folio No'] == int(folio))] tckr = invst['Ticker'].tolist() print(tckr) start = time.time() data, meta_data = ts1.get_batch_stock_quotes(symbols=tckr) data.rename({'2. price': 'Current Market Price (USD)'}, axis=1, inplace=True) data.rename({'1. symbol': 'Ticker'}, axis=1, inplace=True) data.rename({'4. timestamp': 'Current Date'}, axis=1, inplace=True) current = pd.merge(invst, data, on='Ticker', how='inner').drop(['date', '3. volume'], axis=1) current['Current Market Price (USD)'] = current[ 'Current Market Price (USD)'].astype('float') current['Current Investment (USD)'] = current[ 'Current Market Price (USD)'] * current['Stocks'] print(current) end = time.time() print(end - start)
# plt.title('Intraday Times Series for the MSFT stock (1 min)') # plt.show() # from alpha_vantage.timeseries import TimeSeries from pprint import pprint ts = TimeSeries(key='YOUR_API_KEY', output_format='pandas') # data, meta_data = ts.get_daily(symbol='ADHI.JKT', outputsize='full') # pprint(data) # print(meta_data) print('Masukkan kode saham: ') simbol = input() print('kode saham: ' + simbol) data, metadata = ts.get_batch_stock_quotes(simbol) # data, meta_data = ts.get_daily(symbol=simbol+'.JKT', outputsize='full') # pprint(data) # print(meta_data) # pprint(meta_data) # result = [] # for line in open(data): # fields = line.split(",") # name = fields[0] # shares = int(fields[1]) # prices = float(fields[2]) # stock = (name,shares, prices) # result.append(stock) pprint(data) pprint(metadata) # print(result)
def check(self, *args): ts = TimeSeries(key='EJ69MPM068NGTJ30', output_format='pandas') data, meta_data = ts.get_batch_stock_quotes(symbols=args) print(data.loc[:, ["1. symbol", "2. price", "4. timestamp"]]) choose_command()
# see what stock splits happened GE.iloc[:,-1].value_counts() # get timestamp of particular one GE[GE.iloc[:,-1]==3] # make index datetimeindex instead of string GE.index=pd.to_datetime(GE.index) # get 1 min data # ts.get_intraday('MSFT',outputsize='full',interval='1min')[0] # get batch stock quotes (most recent) ticker_list=[]'AAPL','MSFT','FB'] stocks=ts.get_batch_stock_quotes(ticker_list) # technical indicators ti=TechIndicators(key=free_api_key, output_format='pandas') sma=ti.get_sma('MSFT',interval='daily',time_period=50)[0] bbands=ti.get_bbands('MSFT',interval='daily',time_period=50)[0] # add close price to bollinger bands df (want to adadjusted!!) bbands['close']=close.iloc[:,0] macd=ti.get_macd('MSFT',interval='daily')[0]
# #You need to run daily_1.py and daily_2.py #This will create xdb4.json #You can update anytime you want as long as xdb2.json is golden #Remember you need to copy xdb4.json to xdb2.json after market close #analysis program access xdb4.json # # org = json.load(f) symx = list(org.keys()) symbole = symx[0:99] print(symbole) ts = TimeSeries(key='AS0C1JP1LQY65GBK') data, meta_data = ts.get_batch_stock_quotes(symbole) #print(data) #print(type(data)) mydict = {} for item in data: dsym = list(item.values())[0] dpri = list(item.values())[1] mydict[dsym] = dpri dd = list(item.values())[3] latest_day = dd.split(" ")[0] symb = list(mydict.keys())
# Make sure you use the right name here. sheet = client.open("GM Test").sheet1 # Extract and print all of the values list_of_hashes = sheet.get_all_records() # rint(list_of_hashes) numberlist = [] # Parse Phone Numbers for i in list_of_hashes: numberlist.append(i['Phone Number']) """ numberlist = ['9018286567'] #, #'9012860576','4043172600'] api = '23LPQNOOOJSFP5T2' from alpha_vantage.timeseries import TimeSeries ts = TimeSeries(key=api) data = ts.get_batch_stock_quotes(symbols=['TSLA']) print(data[0][0]['2. price']) for i in numberlist: i = '+1' + i print(i) message = txt_service.messages.create( from_='+19014259501', body='Hey Mr. Doug ( ͡° ͜ʖ ͡°)The current TSLA price is: ' + data[0][0]['2. price'], to=i) print(message.status)
import alpha_vantage import requests import pandas as pd import matplotlib.pyplot as plt import json import os import datetime from alpha_vantage.timeseries import TimeSeries ts = TimeSeries(key="E82V6HPLXDMUN5TM") # Get json object with the intraday data and another with the call's metadata data, meta_data = ts.get_intraday('GOOGL') #print(data) balls = TimeSeries(key="E82V6HPLXDMUN5TM") data, meta_data = ts.get_batch_stock_quotes("GOOGL,MSFT") print(data) box = ["WMT", "AAPL"] for i in box: data2, meta_data2 = ts.get_daily(i) print(meta_data2) #print(datetime.date()) bullshit = str(os.path.basename(__file__)) #print(bullshit) bullshit = bullshit[:-3] #print(bullshit) #CALL/CRAFT "message" you will send to "API" and... url = "https://www.alphavantage.co/query"
for entry in js: if entry == jstring: i = js[jstring].keys() for jkeys in i: if jkeys == '2018-09-27': return((jkeys, symbol, js[jstring][jkeys]['1. open'], js[jstring][jkeys]['2. high'], js[jstring][jkeys]['3. low'], js[jstring][jkeys]['4. close'], js[jstring][jkeys]['5. volume'])) return 'api limit' for items in symbols: stock_values.append((get_daily_data(items))) stock_df = pd.DataFrame(stock_values) stock_df = stock_df[[1,3,4,5]][0:4] vol.average_true_range(stock_df[3].astype(float), stock_df[4].astype(float), stock_df[5].astype(float), n=1, fillna=False) class TimeSeries(av): def get_batch_stock_quotes(self, symbols): _FUNCTION_KEY = "BATCH_STOCK_QUOTES" return _FUNCTION_KEY, 'Stock Quotes', 'Meta Data' ts.get_batch_stock_quotes(symbols)
def results(): # build a request object req = request.get_json(force=True) print('input request', req) # fetch action from json action = req.get('queryResult').get('action') #print('action',action) if action == 'read_excel': parameters = req['queryResult']['parameters'] print('action', action) print('parameters', parameters) exl = pd.read_excel('Portfolio.xlsx') fname = parameters['given-name'] lname = parameters['last-name'] folio = parameters['number'] exl['Name'] = exl['Name'].astype('category') exl = exl[(exl['Name'].str.contains(fname, case=False)) & (exl['Folio No'] == int(folio))] filtered_exl = exl[[ 'Companies', 'Stocks', 'Purchase Date', 'Purchase Price(USD)', 'Purchase Investment (USD)' ]] total_investment = filtered_exl['Purchase Investment (USD)'].sum() filtered_exl_dict = filtered_exl.to_dict(orient='records') #print(filtered_exl_dict) #print(type(filtered_exl_dict)) filtered_exl_dict.append( {'Total Purchase Investments (USD)': round(total_investment, 2)}) print(filtered_exl_dict) # return a fulfillment response if len(filtered_exl) != 0: return {'Here, are your details': filtered_exl_dict} else: return { 'fulfillmentText': 'User Authetication Error.We are not able to authenticate your details. Please enter correct Name & Folio Number. Thanks.' } elif action == 'marketvalueaction': parameters = req['queryResult']['parameters'] print('action', action) print('parameters', parameters) apikey = 'JL9GIGT0KVN581XQ' invst = pd.read_excel('Portfolio.xlsx') ts1 = TimeSeries(key=apikey, output_format='pandas', indexing_type='integer') fname = parameters['given-name'] currentvalue = parameters['currentmarketvalue'].lower() folio = parameters['number'] if ( (currentvalue == 'current market value') ): #or (currentvalue == 'sure') or (currentvalue == 'ok') or (currentvalue == 'okay')) : invst['Name'] = invst['Name'].astype('category') invst = invst[(invst['Name'].str.contains(fname, case=False)) & (invst['Folio No'] == int(folio))] tckr = invst['Ticker'].tolist() start = time.time() data, meta_data = ts1.get_batch_stock_quotes(symbols=tckr) data.rename({'2. price': 'Current Market Price (USD)'}, axis=1, inplace=True) data.rename({'1. symbol': 'Ticker'}, axis=1, inplace=True) data.rename({'4. timestamp': 'Current Date'}, axis=1, inplace=True) current = pd.merge(invst, data, on='Ticker', how='inner').drop(['date', '3. volume'], axis=1) current['Current Market Price (USD)'] = current[ 'Current Market Price (USD)'].astype('float') current['Current Investment (USD)'] = current[ 'Current Market Price (USD)'] * current['Stocks'] filtered_current = current[[ 'Companies', 'Stocks', 'Purchase Price(USD)', 'Purchase Investment (USD)', 'Current Market Price (USD)', 'Current Investment (USD)' ]] current_total = filtered_current['Current Investment (USD)'].sum() filtered_current_dict = filtered_current.to_dict(orient='records') filtered_current_dict.append({ 'Current Market Value of All Investments (USD)': round(current_total, 2) }) print(filtered_current_dict) end = time.time() print('API time ', end - start) # return a fulfillment response if len(filtered_current) != 0: return {'Here, are your details': filtered_current_dict} else: return { 'fulfillmentText': 'Please enter whether you would like to see current market value of your investments or not.Thanks.' } elif ((currentvalue == 'no') or (currentvalue == 'nope') or (currentvalue == 'not')): return {'fulfillmentText': 'Alright.'} elif action == 'performeractions': parameters = req['queryResult']['parameters'] print('action', action) print('parameters', parameters) apikey = 'K9HSCD76XIMHD8VJ' invst = pd.read_excel('Portfolio.xlsx') ts1 = TimeSeries(key=apikey, output_format='pandas', indexing_type='integer') fname = parameters['given-name'] performer = parameters['performerentity'].lower() folio = parameters['number'] invst['Name'] = invst['Name'].astype('category') invst = invst[(invst['Name'].str.contains(fname, case=False)) & (invst['Folio No'] == int(folio))] tckr = invst['Ticker'].tolist() start = time.time() data, meta_data = ts1.get_batch_stock_quotes(symbols=tckr) data.rename({'2. price': 'Current Market Price (USD)'}, axis=1, inplace=True) data.rename({'1. symbol': 'Ticker'}, axis=1, inplace=True) data.rename({'4. timestamp': 'Current Date'}, axis=1, inplace=True) current = pd.merge(invst, data, on='Ticker', how='inner').drop(['date', '3. volume'], axis=1) current['Current Market Price (USD)'] = current[ 'Current Market Price (USD)'].astype('float') current['Current Investment (USD)'] = current[ 'Current Market Price (USD)'] * current['Stocks'] filtered_current = current[[ 'Companies', 'Stocks', 'Purchase Price(USD)', 'Purchase Investment (USD)', 'Current Market Price (USD)', 'Current Investment (USD)' ]] current_total = filtered_current['Current Investment (USD)'].sum() filtered_current['Stock Profit/Loss (USD)'] = filtered_current[ 'Current Investment (USD)'] - filtered_current[ 'Purchase Investment (USD)'] filtered_current['Stock Profit/Loss (USD)'] = round( filtered_current['Stock Profit/Loss (USD)'], 2) best = filtered_current[ filtered_current['Stock Profit/Loss (USD)'] == filtered_current['Stock Profit/Loss (USD)'].max()] worst = filtered_current[ filtered_current['Stock Profit/Loss (USD)'] == filtered_current['Stock Profit/Loss (USD)'].min()] end = time.time() print('API time ', end - start) if performer == 'good': best = best[['Companies', 'Stocks', 'Stock Profit/Loss (USD)']] filtered_current_dict = best.to_dict(orient='records') print(filtered_current_dict) return { 'Here is your best performing stock': filtered_current_dict } elif performer == 'bad': worst = worst[['Companies', 'Stocks', 'Stock Profit/Loss (USD)']] filtered_current_dict = worst.to_dict(orient='records') print(filtered_current_dict) return { 'Here is your worst performing stock': filtered_current_dict } #print(filtered_current_dict) #print(type(filtered_current_dict)) #filtered_current_dict.append({'Current Market Value of All Investments (USD)':round(current_total,2)}) else: return { 'fulfillmentText': 'Please provide input for either a best or worst performing stock.Thanks.' } elif action == 'goodbyeaction': parameters = req['queryResult']['parameters'] print('action', action) print('parameters', parameters) goodbye = parameters['goodbyeentity'].lower() if ( (goodbye == 'yes') ): #or (currentvalue == 'sure') or (currentvalue == 'ok') or (currentvalue == 'okay')) : return { 'fulfillmentText': 'Alright sure, I can help you with your investment history, current market value of your investments or your best/worst performing stocks.' } elif ((goodbye == 'no' )): #or (currentvalue == 'nope') or (currentvalue == 'not')): return { 'fulfillmentText': 'Thanks for using Portfolio Bot.Have a good day!.' } else: return {'fulfillmentText': 'Sorry,i am not able to understand this.'}