def refresh(): yahoo = Share('YHOO') yahoo.get_open() val = yahoo.get_price() yahoo.get_trade_datetime() #rndm = Random() #val = rndm.randint(0,4) x = np.linspace(0, 4 * np.pi, N) + val y = np.sin(x) + val source.data = dict(x=x, y=y)
def create_files(): for i in range(0, TIME_IN_MIN * 60 / TIME_BETWEEN_ITERATIONS): reader = csv.DictReader(open('Yahoo_symbols.csv', 'rb')) for sym in reader: company = sym["COMPANY"] symbol = sym["SYMBOL"] while (1): try: share_name = Share(symbol) if share_name: break except: time.sleep(1) filename = "./Q4_files/" + company + ".csv" try: file = open(filename, "a") except: file = open(filename, "w") file.write("Time,Price") timestamp = share_name.get_trade_datetime() price = share_name.get_price() writer = csv.DictWriter(file, fieldnames=["Time", "Price"], delimiter=",", lineterminator="\n") writer.writerow({"Time": timestamp, "Price": price}) time.sleep(TIME_BETWEEN_ITERATIONS) file.close()
def create_files(): for i in range(0,TIME_IN_MIN*60/TIME_BETWEEN_ITERATIONS): reader=csv.DictReader(open('Yahoo_symbols.csv','rb')) for sym in reader: company=sym["COMPANY"] symbol=sym["SYMBOL"] while(1): try: share_name=Share(symbol) if share_name: break except: time.sleep(1) filename = "./Q4_files/"+company+".csv" try: file=open(filename,"a") except: file=open(filename,"w") file.write("Time,Price") timestamp = share_name.get_trade_datetime() price = share_name.get_price() writer = csv.DictWriter(file, fieldnames=["Time","Price"], delimiter=",", lineterminator="\n") writer.writerow({"Time":timestamp ,"Price":price}) time.sleep(TIME_BETWEEN_ITERATIONS) file.close()
def get_updates(self): dict = {} r_list = [] for symbol in self.list: try: s = Share(symbol) tmp = s.get_trade_datetime().split() timestamp = tmp[0] + 'T' + tmp[1] + '.00' price = int(s.get_price().split(".")[self.PRICE]) #print("type for price:{}".format(type(price))) dict[symbol] = [price, timestamp] del s except: pass #print ("Could not find {} in yahoo finance".format(symbol)) for item in dict: r_list.append((item, datetime.strptime(dict[item][self.TIME], "%Y-%m-%dT%H:%M:%S.%f"), dict[item][self.PRICE])) # r_list.append((item, datetime.now(), dict[item])) for i in r_list: yield i return ["GOOG", datetime(2104, 2, 13), 37]
def get_item_info(self, item): name = "" if (item >= self.top): yahoo = Share(self.updated_list[item]) name = self.updated_list[item] else: yahoo = Share(self.list_indexes[item]) name = self.list_indexes[item] string = name + " " + str(yahoo.get_price()) + " " + str( yahoo.get_change()) symbol_info = [] symbol_info.append(name) symbol_info.append(str(yahoo.get_price())) symbol_info.append(str(yahoo.get_change())) symbol_info.append(str(yahoo.get_trade_datetime())) if "None" in symbol_info[2]: symbol_info[2] = symbol_info[2][:-4] for i in range(0, len(symbol_info)): if i == 3: font = pygame.font.Font(self.display_font, self.font_size_lower) else: font = pygame.font.Font(self.display_font, self.font_size) font.set_bold(self.bold) symbol_info[i] = (symbol_info[i], font.size(symbol_info[i])) return symbol_info
def main(): PATH_OF_DATA = 'data' error_log_file = open('error.log', 'a') index_lists = [f[:-4] for f in listdir(PATH_OF_DATA) if f[-4:] == '.csv'] skipFlag = True if len(sys.argv) > 1 else False tillFlag = True if len(sys.argv) > 2 else False for stock_index in index_lists: if skipFlag: if stock_index != sys.argv[1]: continue else: skipFlag = False if tillFlag: if stock_index == sys.argv[2]: break filename = join(PATH_OF_DATA, stock_index + '.csv') if isfile(filename): # 如果已經有檔案,就讀出最後一行然後插入在後面 lastline = get_last_row(filename) print 'lastline = ', lastline try: st = Share(stock_index + '.tw') if not time_after(lastline[0], st.get_trade_datetime()[:10]): print 'time : ', st.get_trade_datetime()[:10] fo = open(filename, 'ab') cw = csv.writer(fo, delimiter=',') # 更新當天資料 cw.writerow([ st.get_trade_datetime()[:10], st.get_open(), st.get_days_high(), st.get_days_low(), st.get_price(), st.get_volume(), '0.0' ]) print "更新一筆!" else: print "不需要更新" except: print stock_index, "update error!" error_log_file.write('%s, Update Error\n' % (stock_index))
def get_database(stock): """Return stock database""" now = date.today() mystock = Share(stock) now_price = mystock.get_price() #ราคาปัจจุบัน import_time = mystock.get_trade_datetime() #เวลาที่ดึงฐานข้อมูล stock_db = mystock.get_historical("2015-01-01", now.isoformat()) #ฐานข้อมูลหุ้นตั้งแต่วันที่ 1 มกราคม 2558 ถึงปัจจุบัน return now, stock, now_price, import_time, stock_db
def getStock(name_of_company): global company_name,company_symbol stock = [] k=0 stock.append([]) stock.append("NA") stock.append("NA") stock.append("NA") stock.append("NA") stock.append("NA") stock.append("NA") stock.append("NA") j=0 for i in company_symbol: if i == name_of_company: break j=j+1 print "j is "+str(j)+"link is " stock[0]=company_name[j] yahoo = Share(name_of_company) stock[1] = yahoo.get_open() stock[2] = yahoo.get_price() stock[3] = yahoo.get_trade_datetime() stock[4] = company_symbol[j] stock[5] = yahoo.get_volume() stock[6] = yahoo.get_dividend_yield() stock[7] = google_links[j] print stock conn = mysql.connect() cur = conn.cursor() if 'username' in session: username = session['username'] cur.execute("SELECT purse FROM user WHERE username = %s;", [username]) print username for row in cur.fetchall(): for lol in row: purse=lol companystock = [dict( name=stock[0], open=stock[1], lasttradeprice=stock[2], lasttradetime=stock[3], stocksymbol=stock[4], MarketCapital=stock[5], dividend=stock[6], link=stock[7] )] cur.execute("SELECT stock FROM user WHERE username = %s;", [username]) print username for row in cur.fetchall(): for lol in row: newarray = lol.split(',') currentstock = newarray[j] print purse return companystock,stock,purse,currentstock
def get_database(stock): """Return stock database""" now = date.today() mystock = Share(stock) now_price = mystock.get_price() #ราคาปัจจุบัน import_time = mystock.get_trade_datetime() #เวลาที่ดึงฐานข้อมูล stock_db = mystock.get_historical( "2015-01-01", now.isoformat()) #ฐานข้อมูลหุ้นตั้งแต่วันที่ 1 มกราคม 2558 ถึงปัจจุบัน return now, stock, now_price, import_time, stock_db
def get(self, ticker): quote = Share(ticker.upper()) quote.refresh() result = { 'quote': [{ 'ticker': ticker.upper(), 'price': quote.get_price(), 'trade_dt': quote.get_trade_datetime() }] } return jsonify(result)
def getAllStockData(ticker): '''Get a few random tickers.''' stock = Share(ticker) stock.refresh() data = { 'name': stock.get_name(), 'price': stock.get_price(), 'change': stock.get_change(), 'volume': stock.get_volume(), 'prev_close': stock.get_prev_close(), 'open': stock.get_open(), 'avg_daily_volume': stock.get_avg_daily_volume(), 'stock_exchange': stock.get_stock_exchange, 'market_cap': stock.get_market_cap(), 'book_value': stock.get_book_value(), 'ebitda': stock.get_ebitda(), 'dividend_share': stock.get_dividend_share(), 'dividend_yield': stock.get_dividend_yield(), 'earnings_share': stock.get_earnings_share(), 'days_high': stock.get_days_high(), 'days_low': stock.get_days_low(), 'year_high': stock.get_year_high(), 'year_low': stock.get_year_low(), '50day_moving_avg': stock.get_50day_moving_avg(), '200day_moving_avg': stock.get_200day_moving_avg(), 'price_earnings_ratio': stock.get_price_earnings_ratio(), 'price_earnings_growth_ratio': stock.get_price_earnings_growth_ratio(), 'get_price_sales': stock.get_price_sales(), 'get_price_book': stock.get_price_book(), 'get_short_ratio': stock.get_short_ratio(), 'trade_datetime': stock.get_trade_datetime(), 'percent_change_from_year_high': stock.get_percent_change_from_year_high(), 'percent_change_from_year_low': stock.get_percent_change_from_year_low(), 'change_from_year_low': stock.get_change_from_year_low(), 'change_from_year_high': stock.get_change_from_year_high(), 'percent_change_from_200_day_moving_average': stock.get_percent_change_from_200_day_moving_average(), 'change_from_200_day_moving_average': stock.get_change_from_200_day_moving_average(), 'percent_change_from_50_day_moving_average': stock.get_percent_change_from_50_day_moving_average(), 'change_from_50_day_moving_average': stock.get_change_from_50_day_moving_average(), 'EPS_estimate_next_quarter': stock.get_EPS_estimate_next_quarter(), 'EPS_estimate_next_year': stock.get_EPS_estimate_next_year(), 'ex_dividend_date': stock.get_ex_dividend_date(), 'EPS_estimate_current_year': stock.get_EPS_estimate_current_year(), 'price_EPS_estimate_next_year': stock.get_price_EPS_estimate_next_year(), 'price_EPS_estimate_current_year': stock.get_price_EPS_estimate_current_year(), 'one_yr_target_price': stock.get_one_yr_target_price(), 'change_percent_change': stock.get_change_percent_change(), 'divended_pay_date': stock.get_dividend_pay_date(), 'currency': stock.get_currency(), 'last_trade_with_time': stock.get_last_trade_with_time(), 'days_range': stock.get_days_range(), 'years_range': stock.get_year_range() } return data
def main(): PATH_OF_DATA = 'data' error_log_file = open('error.log', 'a') index_lists = [ f[:-4] for f in listdir(PATH_OF_DATA) if f[-4:] == '.csv' ] skipFlag = True if len(sys.argv) > 1 else False tillFlag = True if len(sys.argv) > 2 else False for stock_index in index_lists: if skipFlag: if stock_index != sys.argv[1]: continue else: skipFlag = False if tillFlag: if stock_index == sys.argv[2]: break filename = join(PATH_OF_DATA, stock_index+'.csv') if isfile(filename):# 如果已經有檔案,就讀出最後一行然後插入在後面 lastline = get_last_row(filename) print 'lastline = ', lastline try: st = Share(stock_index+'.tw') if not time_after(lastline[0], st.get_trade_datetime()[:10]): print 'time : ', st.get_trade_datetime()[:10] fo = open(filename, 'ab') cw = csv.writer(fo, delimiter=',') # 更新當天資料 cw.writerow([st.get_trade_datetime()[:10], st.get_open(), st.get_days_high(), st.get_days_low(), st.get_price(), st.get_volume(), '0.0']) print "更新一筆!" else: print "不需要更新" except: print stock_index, "update error!" error_log_file.write('%s, Update Error\n' % (stock_index))
def quote(self, tag, n=3): try: stock = Share(tag) p = stock.get_price() t = stock.get_trade_datetime() self.lastKnowPrices[tag] = p return ([t, p]) except: if (n > 0): return (self.quote(tag, n=n - 1)) else: return (self.lastKnowPrices[tag])
def trytryagain(k,n=3): try: tag = k[0] print(tag) stock = Share(tag) p = stock.get_price() t = stock.get_trade_datetime() return(k+[str(t),str(p),str((float(p)/float(k[2])-1)*100)+"%"]) except: if(n>0): return(trytryagain(k)) else: raise("YahooFinanceError","Mal-Formed Response 3x")
def getCurrent(ticker): """ Return the most recent stock data through yahoo_finance. """ stock = Share(ticker) stock.refresh() #refresh the query open_ = stock.get_open() volume = stock.get_volume() high = stock.get_days_high() price = stock.get_price() time = stock.get_trade_datetime() low = stock.get_days_low() return (open_, high, volume, price, time, low)
def get_current_stock_info(stock_short): stock_share = Share(stock_short) stock_current_info = {} stock_current_info['stock_short'] = stock_short stock_latest_price = stock_share.get_price() stock_current_info['stock_latest_price'] = stock_latest_price stock_trade_datetime = stock_share.get_trade_datetime() stock_current_info['stock_trade_datetime'] = stock_trade_datetime stock_exchange = stock_share.get_stock_exchange() stock_current_info['stock_exchange'] = stock_exchange stock_company_name = stock_share.get_name() stock_current_info['stock_company_name'] = stock_company_name return stock_current_info
def fetch(): for share in Share.objects.all(): try: sh = YahooShare(share.share) except: print('exception occurred while fetching stock...') continue sv, created = ShareValue.objects.get_or_create(share=share, price=sh.get_price(), open=sh.get_open(), volume=sh.get_volume(), time=datetime.strptime(sh.get_trade_datetime(), '%Y-%m-%d %H:%M:%S %Z%z')) if not created: print('%s market is closed' % sv.share)
def process_symbol(net, symbol): settings = load(symbol+'.set') if(len(settings)==0): return yahoo = Share(symbol) mp = 2.0*settings['maxc'] p = float(yahoo.get_price())/mp d = yahoo.get_trade_datetime() wd = datetime.datetime.strptime(d[:10],"%Y-%m-%d").weekday()/6.0 v = float(yahoo.get_volume())/(2*settings['maxv']) ts = UnsupervisedDataSet(3,) ts.addSample((wd,p,v),) ret = net.activate([wd,p,v]) print "IK, K, V ", ret
def scraping_data(self): for key in self.tickers: yahoo = Share(key) print(key + ": saving data...") #print(yahoo.get_name(), yahoo.get_price(), yahoo.get_trade_datetime()) row = [ key, yahoo.get_name(), yahoo.get_trade_datetime(), yahoo.get_price() ] self.writer.writerow(row) self.csv_file.close() print('\nAll done successfully!!!')
def get_price_YAHOO(ticker): #for ticker in list_of_symbols: try: from yahoo_finance import Share yahoo = Share(ticker) yahoo.refresh() price_finance = yahoo.get_price() print("IN->", ticker) print("Open -> ", yahoo.get_open()) print("Current Price -> ", yahoo.get_price()) print("Ave Volume -> ", yahoo.get_avg_daily_volume()) print("Volume -> ", yahoo.get_volume()) print("Time -> ", yahoo.get_trade_datetime()) return float(price_finance) except: get_price_YAHOO(ticker)
def yahoo_aktuell(self): #symbol = '^NDX' # symbol = 'FB' wp = Share(self.wertpapier.ric) open = wp.get_open() high = wp.get_days_high() low = wp.get_days_low() close = wp.get_price() time = wp.get_trade_datetime() # MEZ: +1 Stunde # MESZ: +2 Stunden # Close KO: Uhrzeit: 2017-04-04 20:00:00 UTC+0000 => 22 Uhr # Close NDX: Uhrzeit: 2017-04-04 21:15:00 UTC+0000 => 23:15 Uhr print('Symbol:', self.wertpapier.ric, 'Kursdaten:', open, high, low, close) print('Uhrzeit:', time)
def lookup2(symbol): try: share = Share(symbol) except: return None if share.get_name() is None: return None return { "name": share.get_name(), "symbol": symbol.upper(), "price": share.get_price(), "change": share.get_change(), "pc_change": share.get_percent_change(), "trade_time": share.get_trade_datetime() }
def get_trade_date_series(country): # get the data of 000001 by tushare if country == "CN": # now = datetime.datetime.today() # before = now - datetime.timedelta(days=30) # start = before.strftime("%Y-%m-%d") # end = now.strftime("%Y-%m-%d") # df = ts.get_hist_data(code='sh', start=start, end=end) # date_cn = datetime.datetime.strptime(df.index.values[0],"%Y-%m-%d") + datetime.timedelta(hours=15, minutes=5) df = ts.get_realtime_quotes("sh") date_cn = datetime.datetime.strptime(df["date"].values[0].encode("utf8"), "%Y-%m-%d") + datetime.timedelta(hours=9, minutes=25) return date_cn elif country == "US": yahoo = Share('QQQ') time_str = yahoo.get_trade_datetime() date_us = datetime.datetime.strptime(time_str[:10], "%Y-%m-%d") + datetime.timedelta(hours=28, minutes=5) return date_us
class TickerData: def __init__(self, ticker_symbol): self._name = ticker_symbol self._yahoo = None self._google = None self._csv_data = HistoricCsvFile(ticker_symbol) if self._csv_data.is_google_data(): self._google = googlefinance.getQuotes(ticker_symbol)[0] #print (json.dumps(self._google, indent=2)) else: self._yahoo = Share(ticker_symbol) def get_name(self): return self._name def get_long_name(self): return self._yahoo.get_name() if self._yahoo else self._name def get_last_price(self): return self._yahoo.get_price( ) if self._yahoo else self._google['LastTradePrice'] def get_last_trade_datetime(self): return self._yahoo.get_trade_datetime( ) if self._yahoo else self._google['LastTradeDateTime'] def get_price_change(self): return self._yahoo.get_change( ) if self._yahoo else self._google['ChangePercent'] def get_price_open(self): return self._yahoo.get_open( ) if self._yahoo else self._google['PreviousClosePrice'] def get_percent_change(self): return self._yahoo.get_percent_change( ) if self._yahoo else get_ratio_percent(self.get_last_price(), self.get_price_open()) def get_yahoo(self): return self._yahoo def get_csv_data(self): return self._csv_data
def get_trade_date_series(country): # get the data of 000001 by tushare if country == "CN": # now = datetime.datetime.today() # before = now - datetime.timedelta(days=30) # start = before.strftime("%Y-%m-%d") # end = now.strftime("%Y-%m-%d") # df = ts.get_hist_data(code='sh', start=start, end=end) # date_cn = datetime.datetime.strptime(df.index.values[0],"%Y-%m-%d") + datetime.timedelta(hours=15, minutes=5) df = ts.get_realtime_quotes("sh") date_cn = datetime.datetime.strptime( df["date"].values[0].encode("utf8"), "%Y-%m-%d") + datetime.timedelta(hours=9, minutes=25) return date_cn elif country == "US": yahoo = Share('QQQ') time_str = yahoo.get_trade_datetime() date_us = datetime.datetime.strptime( time_str[:10], "%Y-%m-%d") + datetime.timedelta(hours=28, minutes=5) return date_us
def inter_minute_data_get(Ticker, Market, Target_File): start, end = get_market_times(Market) while True: prices = open(Target_File, "a") # concerning this "open" "close" within the loop; this means that regardless of how the program exits we still # write to the file (as opposed to what we were doing which was saving only temporarily t1 = datetime.datetime.utcnow().time() if not start <= t1 <= end: # This finds the current time and waits until the market should next open (does not account for weekends) p = datetime.datetime.utcnow() y = p.replace(hour=start.hour, minute=start.minute, second=start.second) delta_t = y - p if "-1" in str(delta_t): # in case of the "start" time being before the current time we shift to the next day y = p.replace(day=p.day + 1, hour=start.hour, minute=start.minute, second=start.second) delta_t = y - p h, m, s = str(delta_t).split(":") new_delta = datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds() time.sleep(new_delta) prices.write("Time: {}Ticker: {} Price: {} \n".format(Share.get_trade_datetime(x).strip("UTC+0000"), Ticker, Share.get_price(x))) time.sleep(3) prices.close()
TEXT, ) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(gmail_user, gmail_pwd) server.sendmail(FROM, TO, message) server.close() print "successfully sent the mail" except: print "failed to send mail" """ Function: main """ # pull info for a well known ticker to establish date of pulled stock data seedDate = Share("SPY") currentTradeDate = seedDate.get_trade_datetime()[:10] currentRunDate = date.today().strftime("%Y-%m-%d") # only run the script/code if the current date matches the current trade date from the above well known ticker (SPY). # this allows us to ensure multiple runs of the script does not produce redundant data if currentTradeDate == currentRunDate: with open("tickers.csv") as f: for line in f: ticker = line.rstrip("\n") calculate(ticker)
#!/usr/bin/python #coding=utf-8 from yahoo_finance import Share yahoo = Share('0405.HK') print yahoo.get_open() print yahoo.get_price() print yahoo.get_prev_close(); print yahoo.get_trade_datetime() #87001.HK 1426.HK 1275.HK 6139.HK yahoo = Share('87001.HK') print yahoo.get_open() print yahoo.get_price() print yahoo.get_trade_datetime()
def RealTime(stocks, count): cnx = mysql.connector.connect(user='******', password='******', host='127.0.0.1', database='DBtest') cursor = cnx.cursor() waitsec = 60 waitmessage = "Wait 1 minute for the next real-time values..." #The following lines avoid running the program multiple times if the market it's closed now = datetime.datetime.utcnow() # Check the current time today14 = now.replace(hour=14, minute=25, second=0, microsecond=0) today21 = now.replace(hour=21, minute=5, second=0, microsecond=0) if (now >= today21 or today14 >= now): count = 1 waitsec = 1 waitmessage = "" print( "The market opens at 14:30 UTC and closses at 21:00 UTC, \n***Data will be retrieved only once." ) print("Current datetime " + str(now)) while 0 < count: for i in stocks: print("Stock of " + i) stock = Share(i) stock.refresh() price = stock.get_price() stime = stock.get_trade_datetime() # Needed to fix the format the date is retrieved from Yahoo Finance timefixed = stime[:-8] volume = stock.get_volume() print("Price: " + price + " Time: " + timefixed + " Volume: " + volume) # Don't forget to use the config file to avoid writing the password on the source add_realtime = ("INSERT INTO realtime " "(tricker, price, time, volume) " "VALUES (%s, %s, %s, %s)") data_realtime = (i, price, timefixed, volume) try: cursor.execute(add_realtime, data_realtime) cnx.commit() # Make sure data is committed to the database except mysql.connector.IntegrityError as err: #print(err) # Ussually a Duplicate value error pass print("Database sucessfuly udpated. " + waitmessage) time.sleep(waitsec) count -= 1 cursor.close() cnx.close()
plt.ylabel('close_price') plt.title('Interesting graph\nCheck it out') plt.legend() plt.show() graph_data('TSLA') from yahoo_finance import Share yahoo = Share('YHOO') yahoo.get_open() yahoo.get_price() yahoo.get_trade_datetime() yahoo.refresh() #Refresh data from market yahoo.get_historical('2014-04-25', '2014-04-29') from yahoo_finance import Currency eur_pln = Currency('EURPLN') eur_pln.get_bid() eur_pln.get_ask() eur_pln.get_rate() eur_pln.get_trade_datetime() eur_pln.refresh() #reading google finance data import pandas_datareader.data as web import datetime
def query_trade_time(ticker): from yahoo_finance import Share company = Share(ticker) datetime = float(company.get_trade_datetime()) return datetime
def populateStock(shareString, sqlConnection): timedout = True curShare = None while timedout: try: curShare = Share(shareString) timedout=False except: timedout=True time.sleep(5) print('Stock querry timed out, retrying') if curShare.get_price() == 0: return detailShare = None try: detailShare = stockretriever.get_current_info([shareString]) pprint(detailShare) except: print('Yql error caught, continuing excluding analyst estimates for ' + shareString) EPSEstimateNextYear = None EPSEstimateCurrentYear = None EPSEstimateNextQuarter = None if(detailShare != None): if(detailShare['PriceBook']==None): print('No data on this stock, will not populate table.') return if(detailShare['EPSEstimateNextYear']!=None): EPSEstimateNextYear = float(detailShare['EPSEstimateNextYear']) if(detailShare['EPSEstimateCurrentYear']!=None): EPSEstimateCurrentYear = float(detailShare['EPSEstimateCurrentYear']) if(detailShare['EPSEstimateNextQuarter']!=None): EPSEstimateNextQuarter = float(detailShare['EPSEstimateNextQuarter']) sqlStatement = 'default statement' if EPSEstimateNextYear != None and EPSEstimateCurrentYear != None and EPSEstimateNextQuarter != None: sqlStatement = ("REPLACE INTO SM_Stock_Data \n" "VALUES('%s',\"%f\",%i,%i,\"%f\",\"%f\",'%s',\"%f\",\"%f\",\"%f\");" % (shareString, moneyStringToFloat(curShare.get_price()), moneyStringToInt(curShare.get_volume()), moneyStringToInt(curShare.get_market_cap()), moneyStringToFloat(curShare.get_earnings_share()), moneyStringToFloat(curShare.get_dividend_share()), curShare.get_trade_datetime(), EPSEstimateNextYear, EPSEstimateCurrentYear, EPSEstimateNextQuarter)) else: sqlStatement = ("REPLACE INTO SM_Stock_Data (ticker,price,volume,mktcap,eps,dividend,refreshdate) \n" "VALUES('%s',\"%f\",%i,%i,\"%f\",\"%f\",'%s');" % (shareString, moneyStringToFloat(curShare.get_price()), moneyStringToInt(curShare.get_volume()), moneyStringToInt(curShare.get_market_cap()), moneyStringToFloat(curShare.get_earnings_share()), moneyStringToFloat(curShare.get_dividend_share()), curShare.get_trade_datetime())) print('Populating stock with command: ' + sqlStatement) sqlConnection.execute(("REPLACE INTO SM_Stock \n" "VALUES('%s','%s')") % (shareString, doubleApost(nameForTicker(shareString)))) sqlConnection.execute(sqlStatement)
def yahoo_get_price(symbol): yahoo = Share(symbol) price = yahoo.get_price() trade_date = yahoo.get_trade_datetime() dict={"p":price,"d":trade_date} return dict
''' from yahoo_finance import Share from Parser.models import EtfInfo, EtfData, StockInfo, StockDetail etfResult = StockInfo.objects.values('ticker', 'name') #for etfIdx in range(0, len(etfResult)) : tickerStr = etfResult[0]['ticker'] share = Share(tickerStr) dateStr = share.get_trade_datetime()[0:11].replace('-','') ma_200Str = convert(share.get_200day_moving_avg()) ma_50Str = convert(share.get_50day_moving_avg()) book_valueStr = convert(share.get_book_value()) volume_avgStr = convert(share.get_avg_daily_volume()) ebitdaStr = convert(share.get_ebitda()) dividend_yieldStr = convert(share.get_dividend_yield()) market_capStr = convert(share.get_market_cap()) year_highStr = convert(share.get_year_high()) year_lowStr = convert(share.get_year_low()) print tickerStr, dateStr, ma_200Str, ma_50Str, book_valueStr, volume_avgStr, ebitdaStr, dividend_yieldStr, market_capStr, year_highStr, year_lowStr # print share.get_change() # print share.get_days_high()
def checkUpdate(self): myShare = Share(self.ticker) return myShare.get_trade_datetime(), self.ticker, myShare.get_price()
message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(gmail_user, gmail_pwd) server.sendmail(FROM, TO, message) server.close() print 'successfully sent the mail' except: print "failed to send mail" ''' Function: main ''' # pull info for a well known ticker to establish date of pulled stock data seedDate = Share('SPY') currentTradeDate = seedDate.get_trade_datetime()[:10] currentRunDate = date.today().strftime('%Y-%m-%d') # only run the script/code if the current date matches the current trade date from the above well known ticker (SPY). # this allows us to ensure multiple runs of the script does not produce redundant data if currentTradeDate == currentRunDate: with open("tickers.csv") as f: for line in f: ticker = line.rstrip('\n') calculate(ticker)
# find the date of yesterday now = datetime.datetime.now() # connect the sqlite conn = lite.connect('StockHistory.db') cursor = conn.cursor() # every time empty data cursor.execute('DELETE FROM TrueTimeValue') conn.commit() # get the records ranging from max date in DB to yesterday BeginTime = now.replace(hour=9, minute=0, second=0, microsecond=0) EndTime = now.replace(hour=16, minute=0, second=0, microsecond=0) # LocalTime = T.strftime('%Y-%m-%d ',T.localtime(T.time())) while now > BeginTime and now < EndTime: StockList = ['YHOO', 'GOOG', 'AAPL', 'TWTR', 'AMZN'] for stock in StockList: Symbol = stock Company = Share(stock) Price = Company.get_price() Time = Company.get_trade_datetime() Volume = Company.get_volume() purchases = (Symbol, Price, Time, Volume) cursor.execute('INSERT INTO TrueTimeValue VALUES (?,?,?,?)', purchases) conn.commit() Company.refresh() cursor.execute('SELECT * FROM TrueTimeValue') print(cursor.fetchall()) T.sleep(60) cursor.close() conn.close()
def getHistoricalData(ticker, daysAgo): try: yahooHoo = Share(ticker) except ValueError: print "Couldn't 'Share("+str(ticker)+")'" data=yahooHoo.get_historical(dateDaysAgo(daysAgo), today()) try: empty={} element={'Volume': yahooHoo.get_volume(), 'Symbol': ticker, 'High': yahooHoo.get_days_high(), 'Low': yahooHoo.get_days_low(), 'Open': yahooHoo.get_open(), 'Close': yahooHoo.get_price(), 'Date': yahooHoo.get_trade_datetime()[0:10]} data.append(element) except ValueError: print "LALALA" if len(data) > 0: data = sorted(data, key=lambda k: k['Date'], reverse=False) #Sort by Date of json element #try: # if data[-1]['Date'] != element['Date']: # data.append(element) #except ValueError: # print "DOH" #data = sorted(data, key=lambda k: k['Date'], reverse=False) #Sort by Date of json element return data
from yahoo_finance import Share from pprint import pprint stock = Share('GOOG') print stock.get_open() print stock.get_price() print stock.get_trade_datetime() pprint(stock.get_historical('2017-06-01', '2017-06-02'))
"' refresh=true") elif change[:1] == "-": print("\033[1;31m" + change + "\033[0m) | href='https://ca.finance.yahoo.com/quote/" + i + "' refresh=true") elif change[:1] == "0": print("0.00) | href='https://ca.finance.yahoo.com/quote/" + i + "' refresh=true") if times == 1: print("---") print("Trade Times") for i in stocks: price = Share(i) name = i if len(i) > 4: name = i[:4] print(name + ": " + price.get_trade_datetime()) if portfolio == 1: print("---") print( "Portfolio... | href='https://ca.finance.yahoo.com/portfolio/p_0/view/v1'" ) except: print("[Error]") print("---") print("[Refresh] | refresh=true") exit()
from yahoo_finance import Share from pprint import pprint yahoo = Share('SPY') print yahoo.get_open() print yahoo.get_price() print yahoo.get_trade_datetime() yahoo.refresh() spyprice = yahoo.get_historical('2000-01-01', '2016-04-25') pprint(yahoo.get_historical('2014-04-25', '2014-04-29'))
# Fix bug: https://github.com/ranaroussi/fix-yahoo-finance (The future, I think that the bug is solved) # pip install fix_yahoo_finance --upgrade --no-cache-dir print("+++++pandas_datareader+++++") from pandas_datareader import data as pdr import fix_yahoo_finance as yf # <== that's all it takes :-) # For Stock of Thailand, the symbol must be followed with '.BK' # download dataframe ptt = pdr.get_data_yahoo("PTT.BK", start="2017-01-01", end="2017-04-30") print(ptt.tail()) print() # Forth example # How to install yahoo_finance package # Reference: https://pypi.python.org/pypi/yahoo-finance # pip install yahoo_finance from yahoo_finance import Share yahoo = Share("YHOO") print("\n++++YHOO stock++++") print (yahoo.get_open()) print (yahoo.get_price()) print (yahoo.get_trade_datetime()) from yahoo_finance import Currency eur_pln = Currency('EURPLN') print("\n++++Currency of EURPLN++++") print (eur_pln.get_bid()) print (eur_pln.get_ask()) print (eur_pln.get_rate()) print (eur_pln.get_trade_datetime())
def real_data(code): stockData = Share(code) # stockData.refresh() # print([stockData.get_trade_datetime(), stockData.get_price()]) return json.dumps([stockData.get_trade_datetime(), stockData.get_price()])
from yahoo_finance import Share yahoo = Share("YHOO") print(yahoo.get_open()) print(yahoo.get_trade_datetime()) yahoo.refresh()
def current_time_stock(name): stock = Share('{}'.format(name)) return stock.get_trade_datetime()