def get_info_share(symbol): #print symbol #symbol = sys.argv[1] share1 = Share(symbol) try: share1.get_info() if not share1:# is None: print symbol," is not a valid share symbol. \nPlease re-run the program with correct share symbol" else: #print "here" print(datetime.datetime.now()) company = get_symbol(symbol) print company print share1.get_price() print share1.get_change() #print share1.get_short_ratio() open = share1.get_open() price = share1.get_price() percChange = float(Decimal(price) - Decimal(open))/float(Decimal(open)) print "%f" % percChange +"%" except Exception as e: print symbol," is not a valid share symbol. \nPlease re-run the program with correct share symbol" except AttributeError as ae: print "att error" except yahoo_finance.YQLQueryError as ye: print symbol," is not a valid share symbol in ye error. \nPlease re-run the program with correct share symbol"
def debug(): # create character print("Welcome, brave adventurer!") name = input("What is your name?") print("Ah, I see. So your name is", name, "?") share1 = input("Pick a share.") option1 = Share(share1) print("Ah, so you chose", option1.get_info(), "?") share2 = input("Pick a second share") option2 = Share(share2) print("Ah, so you chose", option2.get_info(), "?") name = characters.character(name, 100, 10, 10, 100, Share1, Share2) while(1): a = 1
def lookup_by_symbol(symbol='', service='y'): """ TODO : Not calling this method anywhere now; think about this method's purpose again """ query_symbol = Symbol.symbol_dict.get(symbol) if query_symbol is None: try: if service == 'g': g_get_quotes(symbol) query_symbol = Symbol(g_symbol=symbol) elif service == 'y': print 'creating Share instance to check whether valid symbol' y_obj = Share(symbol) if 'start' not in y_obj.get_info(): raise Exception( 'Given symbol doesn\'t exist in Yahoo finance') query_symbol = Symbol(y_symbol=symbol) query_symbol.yahoo_handle = y_obj except urllib2.HTTPError: print('{symbol} is invalid'.format(symbol=symbol)) except Exception as e: print(e.args) return query_symbol
def lookup_by_symbol(symbol='', service='y'): """ TODO : Not calling this method anywhere now; think about this method's purpose again """ query_symbol = Symbol.symbol_dict.get(symbol) if query_symbol is None: try: if service == 'g': g_get_quotes(symbol) query_symbol = Symbol(g_symbol=symbol) elif service == 'y': print 'creating Share instance to check whether valid symbol' y_obj = Share(symbol) if 'start' not in y_obj.get_info(): raise Exception('Given symbol doesn\'t exist in Yahoo finance') query_symbol = Symbol(y_symbol=symbol) query_symbol.yahoo_handle = y_obj except urllib2.HTTPError: print('{symbol} is invalid'.format(symbol=symbol)) except Exception as e: print(e.args) return query_symbol
def make_csv(self,name,now_time): if os.path.exists(self.DIR_NAME+name+".csv"): print "Already have a %s.csv"%name return print "making %s.csv....." %name from yahoo_finance import Share share=Share(name) info=share.get_info() if "start" not in info: print "Cant make a %s.csv"%name return -1 start=info["start"] #wrong date if re.match("\d{4}-\d{2}-\d{2}",start)== None: print "invalid date cant make a file" return -1 obj=share.get_historical(start,now_time) filename=name+".csv" fieldnames=("Date","High","Low","Volume" ) headers = dict( (n,n) for n in fieldnames ) f=open(self.DIR_NAME+filename,"w") writer=csv.DictWriter(f,fieldnames) writer.writerow(headers) for o in obj: row="" writer.writerow({"Date":o["Date"],"High":o["High"],"Low":o["Low"],"Volume":o["Volume"]}) f.close()
def getStockInfo(req): result = req.get("result") parameters = result.get("parameters") stock_symbol = parameters.get("stock_symbol") if stock_symbol is None: return None stock = Share(stock_symbol) info = stock.get_info() return str(info)
def main(): apple = Share('AAPL') # Which stock to monitor and invest in Base.metadata.create_all(engine) session.commit() b = session.query( Wallet.balance).first() # Check if there is already a wallet if b == None: primary_wallet = Wallet( name='Primary Wallet', balance=100000) # Create the wallet with a balance of $100,000 session.add(primary_wallet) session.commit() mean_reversion = Strategy( apple.get_info() ['symbol']) # Run the EMA, and Bollinger band calculations enter_position(mean_reversion, apple) # Buy stock if applicable exit_position(mean_reversion, apple) # Sell stock if applicable session.commit()
def history(): # If a user goes to the display page and a session is not active if session.get('active') != True: sym = 'SPY' session['active'] = True session['sym'] = sym else: sym = session['sym'] # if a session is active leave the sym alone share = Share(sym) historical = share.get_historical('2016-03-13', '2016-04-15') canvas_list = [] for day in historical: canvas_list.append([int(day['Date'][:4]), int(day['Date'][5:7]) - 1, int(day['Date'][-2:]), float(day['Open']), float(day['High']), float(day['Low']), float(day['Close']) ]) info = share.get_info() open = share.get_open() high = share.get_days_high() low = share.get_days_low() price = share.get_price() canvas_list.append([int(info['end'][:4]), int(info['end'][5:7]) - 1, int(info['end'][-2:]), float(open), float(high), float(low), float(price) ]) return render_template('history.html', canvas_list=canvas_list, sym=sym)
class TestShare(TestCase): def setUp(self): self.yahoo = Share('YHOO') def test_yhoo(self): # assert that these are float-like float(self.yahoo.get_open()) float(self.yahoo.get_price()) def test_get_info(self): info = self.yahoo.get_info() self.assertEqual(info['start'], '1996-04-12') self.assertEqual(info['symbol'], 'YHOO') def test_get_historical(self): history = self.yahoo.get_historical('2014-04-25', '2014-04-29') self.assertEqual(len(history), 3) expected = { 'Adj_Close': '35.83', 'Close': '35.83', 'Date': '2014-04-29', 'High': '35.89', 'Low': '34.12', 'Open': '34.37', 'Symbol': 'YHOO', 'Volume': '28736000' } self.assertDictEqual(history[0], expected) def test_get_historical_longer_than_1y(self): # issue #2 history = self.yahoo.get_historical('2012-04-25', '2014-04-29') self.assertEqual(history[-1]['Date'], '2012-04-25') self.assertEqual(history[0]['Date'], '2014-04-29') self.assertEqual(len(history), 505)
def stock_info(symbol="YHOO"): stock = Share(symbol) return str(stock.get_info())
def print_menu(menuid, errorid): global selected_Ticker namesTicker = ["Stocks", "Exchanges", "Catagory", "Number Selection"] if selected_Ticker is not None: print("Selected:\t"+selected_Ticker.name) print("Type:\t\t"+namesTicker[selected_Ticker.typeof]) if selected_Ticker.typeof == 0: stock = Share(selected_Ticker.name) stock.refresh() print(stock.get_info()) print(stock.get_price()) print(stock.get_change()) print(stock.get_volume()) print("\n\n") if menuid == 0: print("------Menu------") print(" (e) exit") print(" (l) list") print(" (s) stats") error(errorid) elif menuid == 1: print("------Stats Menu------") print(" (a) all") print(" (u) uniques") print(" (b) back") if selected_Ticker is not None: print(" (r) run data collector") print(" (c) clear") error(errorid) elif menuid == 2: print("------All Data Menu------") print(" (e) exchanges") print(" (c) catagories") print(" (n) catagory Number") print(" (b) back") error(errorid) elif menuid == 3: print("------Unique Menu------") print(" (s) stock") print(" (e) exchange") print(" (c) catagories") print(" (n) catagory Number") print(" (b) back") error(errorid) elif menuid == 4: print("------Stock Tickers Selection------") exchanges_display(0) error(errorid) elif menuid == 5: print("------Exchanges Selection------") exchanges_display(1) error(errorid) elif menuid == 6: print("------Catagory Selection------") exchanges_display(2) error(errorid) elif menuid == 7: print("------Number Catagory Selection------") exchanges_display(3) error(errorid)
from yahoo_finance import Share, Currency yahoo = Share('AAPL') yahoo.refresh() print yahoo.get_info() print yahoo.get_avg_daily_volume() print yahoo.get_stock_exchange() print yahoo.get_book_value() print yahoo.get_ebitda() print yahoo.get_dividend_share() print yahoo.get_price_earnings_ratio() print yahoo.get_short_ratio() print yahoo.get_price_book() # f = open('nasdaqlisted.txt', 'r') # print (f.readline()) # print (f.readline())
def predict(): today = dt.date.today() if today.isoweekday() == 6: pred_date = today - dt.timedelta(1) elif today.isoweekday() == 7: pred_date = today - dt.timedelta(2) else: pred_date = today pred_day = int(pred_date.day) pred_month = int(pred_date.month) pred_year = int(pred_date.year) # If a user goes to the display page and a session is not active if session.get('active') != True: sym = 'SPY' session['active'] = True session['sym'] = sym else: sym = session['sym'] # if a session is active leave the sym alone try: # Error handling... Some Stock symbols exist but there is no historical information in Yahoo Finance... share = Share(sym) historical = share.get_historical(str(today - dt.timedelta(5)), str(today - dt.timedelta(1))) # need to auto input the date... canvas_list = [] info = share.get_info() open = share.get_open() high = share.get_days_high() low = share.get_days_low() price = share.get_price() canvas_list.append([int(info['end'][:4]), int(info['end'][5:7]) - 1, int(info['end'][-2:]), float(price) ]) for day in historical: canvas_list.append([int(day['Date'][:4]), int(day['Date'][5:7]) - 1, int(day['Date'][-2:]), float(day['Close']) ]) df_preds = pd.read_csv('data/predictions.csv') date = df_preds[df_preds['sym'] == sym]['date'].values[0] historical_day = float(share.get_historical(date, date)[0]['Close']) year = date[:4] month = date[5:7] day = date[-2:] predicted_value = historical_day + df_preds[df_preds['sym'] == sym]['regressor_mse'].values[0] predicted_rmse = df_preds[df_preds['sym'] == sym]['mse'].values[0] ** .5 box1_low = predicted_value - (predicted_rmse / 2.) box1_high = predicted_value + (predicted_rmse / 2.) box2_low = predicted_value - (predicted_rmse) box2_high = predicted_value + (predicted_rmse) return render_template('predict.html', canvas_list=canvas_list, sym=sym, box1_low=box1_low, box1_high=box1_high, box2_low = box2_low, box2_high=box2_high, year=year, month=month, day=day, pred_day=pred_day, pred_month=pred_month, pred_year=pred_year) except: return redirect("/error")
def facebookYahooCrawl(): start = datetime.datetime(2019, 5, 29) end = datetime.datetime(2019, 5, 30) samsung = Share('005930.KS') samsung.get_info()
class TestShare(TestCase): def setUp(self): self.yahoo = Share('YHOO') def test_yhoo(self): # assert that these are float-like float(self.yahoo.get_open()) float(self.yahoo.get_price()) def test_get_info(self): info = self.yahoo.get_info() self.assertEqual(info['start'], '1996-04-12') self.assertEqual(info['symbol'], 'YHOO') def test_get_historical(self): history = self.yahoo.get_historical('2014-04-25', '2014-04-29') self.assertEqual(len(history), 3) expected = { 'Adj_Close': '35.830002', 'Close': '35.830002', 'Date': '2014-04-29', 'High': '35.889999', 'Low': '34.119999', 'Open': '34.369999', 'Symbol': 'YHOO', 'Volume': '28736000' } self.assertDictEqual(history[0], expected) def test_get_historical_longer_than_1y(self): # issue #2 history = self.yahoo.get_historical('2012-04-25', '2014-04-29') self.assertEqual(history[-1]['Date'], '2012-04-25') self.assertEqual(history[0]['Date'], '2014-04-29') self.assertEqual(len(history), 505) def test_get_historical_1d(self): # issue #7 history = self.yahoo.get_historical('2014-04-29', '2014-04-29') self.assertEqual(len(history), 1) expected = { 'Adj_Close': '35.830002', 'Close': '35.830002', 'Date': '2014-04-29', 'High': '35.889999', 'Low': '34.119999', 'Open': '34.369999', 'Symbol': 'YHOO', 'Volume': '28736000' } self.assertDictEqual(history[0], expected) def test_edt_to_utc(self): edt = '5/26/2014 4:00pm' utc = '2014-05-26 20:00:00 UTC+0000' self.assertEqual(edt_to_utc(edt), utc) def test_edt_to_utc_issue15(self): # date string for yahoo can contains 0 rather than 12. # This means that it cannot be parsed with %I see GH issue #15. edt = '4/21/2015 0:13am' utc = '2015-04-21 04:13:00 UTC+0000' self.assertEqual(edt_to_utc(edt), utc) def test_get_date_range(self): result = [i for i in get_date_range('2012-04-25', '2014-04-29')] expected = [ ('2013-04-29', '2014-04-29'), ('2012-04-28', '2013-04-28'), ('2012-04-25', '2012-04-27'), ] self.assertEqual(result, expected)
class TestShare(TestCase): def setUp(self): self.yahoo = Share('YHOO') def test_yhoo(self): # assert that these are float-like float(self.yahoo.get_open()) float(self.yahoo.get_price()) def test_get_info(self): info = self.yahoo.get_info() self.assertEqual(info['start'], '1996-04-12') self.assertEqual(info['symbol'], 'YHOO') def test_get_historical(self): history = self.yahoo.get_historical('2014-04-25', '2014-04-29') self.assertEqual(len(history), 3) expected = { 'Adj_Close': '35.83', 'Close': '35.83', 'Date': '2014-04-29', 'High': '35.89', 'Low': '34.12', 'Open': '34.37', 'Symbol': 'YHOO', 'Volume': '28736000' } self.assertDictEqual(history[0], expected) def test_get_historical_longer_than_1y(self): # issue #2 history = self.yahoo.get_historical('2012-04-25', '2014-04-29') self.assertEqual(history[-1]['Date'], '2012-04-25') self.assertEqual(history[0]['Date'], '2014-04-29') self.assertEqual(len(history), 505) def test_get_historical_1d(self): # issue #7 history = self.yahoo.get_historical('2014-04-29', '2014-04-29') self.assertEqual(len(history), 1) expected = { 'Adj_Close': '35.83', 'Close': '35.83', 'Date': '2014-04-29', 'High': '35.89', 'Low': '34.12', 'Open': '34.37', 'Symbol': 'YHOO', 'Volume': '28736000' } self.assertDictEqual(history[0], expected) def test_edt_to_utc(self): edt = '5/26/2014 4:00pm' utc = '2014-05-26 20:00:00 UTC+0000' self.assertEqual(edt_to_utc(edt), utc) def test_get_date_range(self): result = [i for i in get_date_range('2012-04-25', '2014-04-29')] expected = [ ('2013-04-29', '2014-04-29'), ('2012-04-28', '2013-04-28'), ('2012-04-25', '2012-04-27'), ] self.assertEqual(result, expected)
#getYahooAPIData.py # sudo -H pip install yahoo-finance from yahoo_finance import Share from pprint import pprint yahoo = Share('YHOO') start = '2015-01-01' end = '2015-12-31' yahoo_prices = yahoo.get_historical(start,end) yahoo_info = yahoo.get_info() print type(yahoo_prices) print yahoo_prices[0] # Methods # get_price() # get_change() # get_volume() # get_prev_close() # get_open() # get_avg_daily_volume() # get_stock_exchange() # get_market_cap() # get_book_value() # get_ebitda()
known_sectors = set() known_unwrs = set() for symbol in symbols[0:100]: count += 1 if count % 10 == 0: print count if "-" in symbol: continue if Company.query.filter_by(symbol=symbol).first(): continue data = {"symbol": symbol} stock = Share(symbol) data["name"] = stock.get_info()["CompanyName"] data[":q"] #data = scraper.scrape_nasdaq(symbol) #if not data: # continue #elif len(data.keys()) == 1: # data.update(scraper.scrape_yahoo(symbol, full=True)) #else: # data.update(scraper.scrape_yahoo(symbol)) if len(data) == 1: continue if Company.query.filter_by(name=data["name"]).first(): continue
from yahoo_finance import Share # https://minjejeon.github.io/learningstock/2016/07/12/getting-data-from-yahoo-finance.html samsung = Share("005930.KS") print(samsung.get_info())
def display(): today = dt.date.today() # Is the user coming from the form page? try: sym = str(request.form['user_input']).strip().upper() or 'SPY' session['active'] = True session['sym'] = sym except: # If a user goes to the display page and a session is not active if session.get('active') != True: sym = 'SPY' session['active'] = True session['sym'] = sym else: sym = session['sym'] # if a session is active leave the sym alone share = Share(sym) if 'start' not in share.get_info(): # is there information related to the stock symbol in Yahoo Finance? # if request.method == 'POST': # print "This is a test" # # if request.form['submit'] == 'Submit': # # print "before change session" # # session['active'] = False print "before return" return redirect("/error") # return render_template('error.html', # sym=session['sym']) else: try: # Error handling... Some Stock symbols exist but there is no historical and/or daily information in Yahoo Finance... quote = float(share.get_price()) com_name = sym #hand_made_list()[sym][0] historical = share.get_historical(str(today - dt.timedelta(31)), str(today - dt.timedelta(1))) canvas_list = [] for day in historical: canvas_list.append([int(day['Date'][:4]), int(day['Date'][5:7]) - 1, int(day['Date'][-2:]), float(day['Open']), float(day['High']), float(day['Low']), float(day['Close']) ]) info = share.get_info() open = share.get_open() high = share.get_days_high() low = share.get_days_low() price = share.get_price() canvas_list.append([int(info['end'][:4]), int(info['end'][5:7]) - 1, int(info['end'][-2:]), float(open), float(high), float(low), float(price) ]) return render_template('display.html', sym=session['sym'], com_name=com_name, quote=quote, canvas_list=canvas_list) except: return redirect("/error")
daily_VA_D = np.array([], dtype='float') if TRAIN_RATIO == 1.0: train_file = open('./stock_data/' + name + '.csv', 'w') else: train_file = open('./stock_data/' + name + '_train.csv', 'w') test_file = open('./stock_data/' + name + '_test.csv', 'w') print "Days in total:", data_size print "slice data into..." print "Train:", int( data_size * TRAIN_RATIO), " Test:", data_size - int(data_size * TRAIN_RATIO) train_file.write( Stock.get_info()['symbol'] + ',' + 'High,Low,Open,Close,d_Close,RSI9,RSI15,MA5,MA20,MA60,d_CO,d_HL,Adj_Close,Volume,VA/D,d_VA/D,%R8,%R21,DIF,DEM,d_MA5/20\n' ) if not TRAIN_RATIO == 1.0: test_file.write( Stock.get_info()['symbol'] + ',' + 'High,Low,Open,Close,d_Close,RSI9,RSI15,MA5,MA20,MA60,d_CO,d_HL,Adj_Close,Volume,VA/D,d_VA/D,%R8,%R21,DIF,DEM,d_MA5/20\n' ) VA_D_tm1 = 0. EMA12_tm1 = 0. EMA26_tm1 = 0. DEM_tm1 = 0. for i in xrange(data_size): data = history_data[i] volume = float(data['Volume'])
for cfound in list_founds: name_found1 = cfound[0].replace('+', '').replace('.', '').replace(' ', '').replace('&','%26').replace('-', '') + ".MX" name_found2 = cfound[0].replace('+', '').replace('.', '').replace(' ', '').replace('&','%26') + ".MX" hdata_found = 0 list_nfounds = list() list_nfounds.append(name_found1) if name_found1 != name_found2: list_nfounds.append(name_found2) print '{0} ({1}): "{2}"'.format(cfound[0], cfound[1], list_nfounds) for name_found in list_nfounds: try: ofound = Share(name_found) # Found object sleep(1) # Pause time (1 segs.) to avoid server rejections try: info = ofound.get_info() print info if info.get('start') == None: found_error.write("-Error-[{}]: No 'start' and 'end' dates for historical data. Used code: '{}'\n".format(cfound[0], name_found)) #elif not validate(info['start']): # found_error.write("-Error-[{}]: No valid 'start' date for historical data. Used code: '{}', fault date: '{}'\n".format(cfound[0], name_found, info['start'])) else: if not validate(info['start']): found_error.write("Warning[{}]: No valid 'start' date for historical data. Used code: '{}', fault date: '{}', substitute date: '{}'\n".format(cfound[0], name_found, info['start'], info['start'].replace('-NaN-', '-01-'))) info['start'] = info['start'].replace('-NaN-', '-01-') if validate(info['start']): print " ---> 'start': '{}'".format(info['start']) sdate = datetime.datetime.strptime(info['start'], '%Y-%m-%d') idate = datetime.datetime.strptime(cfound[1], '%Y-%m-%d') if idate <= sdate:
#getYahooAPIData.py # sudo -H pip install yahoo-finance from yahoo_finance import Share from pprint import pprint yahoo = Share('YHOO') start = '2015-01-01' end = '2015-12-31' yahoo_prices = yahoo.get_historical(start, end) yahoo_info = yahoo.get_info() print type(yahoo_prices) print yahoo_prices[0] # Methods # get_price() # get_change() # get_volume() # get_prev_close() # get_open() # get_avg_daily_volume() # get_stock_exchange() # get_market_cap() # get_book_value() # get_ebitda() # get_dividend_share() # get_dividend_yield()
def write_technical_files(stock_code, start_time, end_time): # """ Experiment on quandl """ # print('quandl data') # mydata = quandl.get("FRED/GDP") # print(mydata) # print('hello') # data = quandl.get("WIKI/FB.11", start_date="2014-01-01", end_date="2014-12-31", collapse="monthly", transform="diff") # print(data) stock = Share(stock_code) print('stock.get_info()') print(stock.get_info()) print('get_price()') print(stock.get_price()) print('get_change()') print(stock.get_change()) print('get_stock_exchange()') print(stock.get_stock_exchange()) print('get_market_cap()') print(stock.get_market_cap()) print('get_book_value()') print(stock.get_book_value()) print('get_ebitda()') print(stock.get_ebitda()) print('get_dividend_share()') print(stock.get_dividend_share()) print('get_dividend_yield()') print(stock.get_dividend_yield()) print('get_earnings_share()') print(stock.get_earnings_share()) print('get_50day_moving_avg()') print(stock.get_50day_moving_avg()) print('get_200day_moving_avg()') print(stock.get_200day_moving_avg()) print('get_price_earnings_ratio()') print(stock.get_price_earnings_ratio()) print('get_price_earnings_growth_ratio()') print(stock.get_price_earnings_growth_ratio()) print('get_price_sales()') print(stock.get_price_sales()) print('get_price_book()') print(stock.get_price_book()) print('get_short_ratio()') print(stock.get_short_ratio()) print('historical_data') print(stock.get_historical(start_time, end_time)) historical_data = stock.get_historical(start_time, end_time) info_text = "Symbol\t" + "Stock Exchange\t" + "Price\t" + "Market Cap\t" + "Book Value\t" + "EBITDA\t" + "50d Moving Avg\t" + "100d Moving Avg\n" info_text += str(stock.get_info()['symbol']) + "\t" + str(stock.get_stock_exchange()) + "\t" + str(stock.get_price()) + "\t" + str(stock.get_market_cap()) + "\t" + str(stock.get_book_value()) + "\t"; info_text += str(stock.get_ebitda()) + "\t" + str(stock.get_50day_moving_avg()) + "\t" + str(stock.get_200day_moving_avg()) + "\n"; info_directory = '/data/info.tsv' write_to_file(info_directory, info_text) high_low_text = "date\t" + "High\t" + "Low\n" open_close_text = "date\t" + "Open\t" + "Close\n" volume_text = "date\t" + "Volume\n" for index, value in enumerate(historical_data): date = str(historical_data[len(historical_data) - 1 - index]['Date']) date = date.replace('-','') stock_high = str(historical_data[len(historical_data) - 1 - index]['High']) stock_low = str(historical_data[len(historical_data) - 1 - index]['Low']) stock_open = str(historical_data[len(historical_data) - 1 - index]['Open']) stock_close = str(historical_data[len(historical_data) - 1 - index]['Close']) stock_volume = str(int(historical_data[len(historical_data) - 1 - index]['Volume']) / 1000) high_low_text += date + "\t" + stock_high + "\t" + stock_low + "\n" open_close_text += date + "\t" + stock_open + "\t" + stock_close + "\n" volume_text += date + "\t" + stock_volume + "\n" high_low_directory = '/data/highlow.tsv' open_close_directory = '/data/openclose.tsv' volume_directory = '/data/volume.tsv' write_to_file(high_low_directory, high_low_text) write_to_file(open_close_directory, open_close_text) write_to_file(volume_directory, volume_text) ratio_text = "name\t" + "value\n" if stock.get_change() != None: name = "Change" value = str(stock.get_change()) ratio_text += name + "\t" + value + "\n" if stock.get_dividend_share() != None: name = "Dividend Share" value = str(stock.get_dividend_share()) ratio_text += name + "\t" + value + "\n" if stock.get_dividend_yield() != None: name = "Divident Yield" value = str(stock.get_dividend_yield()) ratio_text += name + "\t" + value + "\n" if stock.get_earnings_share() != None: name = "Earning Share" value = str(stock.get_earnings_share()) ratio_text += name + "\t" + value + "\n" if stock.get_price_earnings_ratio() != None: name = "Price Earning" value = str(stock.get_price_earnings_ratio()) ratio_text += name + "\t" + value + "\n" if stock.get_price_earnings_growth_ratio() != None: name = "Price Earning Growth" value = str(stock.get_price_earnings_growth_ratio()) ratio_text += name + "\t" + value + "\n" if stock.get_price_sales() != None: name = "Price Sales" value = str(stock.get_price_sales()) ratio_text += name + "\t" + value + "\n" if stock.get_price_book() != None: name = "Price Book" value = str(stock.get_price_book()) ratio_text += name + "\t" + value + "\n" if stock.get_short_ratio() != None: name = "Short" value = str(stock.get_short_ratio()) ratio_text += name + "\t" + value + "\n" ratio_directory = '/data/ratio.tsv' write_to_file(ratio_directory, ratio_text)
print(yahoo.get_ebitda()) print(yahoo.get_earnings_share()) print(yahoo.get_price_book()) print(goog.get_ebitda()) print(goog.get_earnings_share()) print(goog.get_price_book()) from yahoo_finance import Share IBB = Share('IBB') print(IBB.get_ebitda()) from yahoo_finance import Share li = ['YHOO','GOOG'] yahoo = Share('YHOO') goog = Share('GOOG') print(yahoo.get_book_value()) for i in li: t = Share(i) print(i) print(t.get_book_value()) from pprint import pprint from yahoo_finance import Share yahoo = Share('YHOO') print(yahoo.get_ebitda()) pprint(yahoo.get_info())
def get_history(symbol, exchange): ## Check if symbol is in our database path = join(dirname(realpath(__file__)),'data', exchange, symbol + '.history') subprocess.call("touch " + path , shell=True) last_line = subprocess.Popen("tail -n1 "+ path, shell=True, stdout=subprocess.PIPE).stdout.read() last_date = last_line.split('\t')[0] if isdate(last_date): if yesterday == last_date: stupdate( symbol + ' already up to date.') del path del last_date return True stupdate( symbol + ' updating..') share = Share(symbol) else: subprocess.call("echo \"Date\\tVolume\\tOpen\\tClose\\tHigh\\tLow\" > " + path, shell=True) try: share = Share(symbol) last_date = share.get_info()['start'] except: last_date = '2000-01-04' dates = [last_date, '2000-01-04', '2005-01-04', '2010-01-04'] for i, date in enumerate(dates): try: yahoo_history = share.get_historical(date, today) break except: error(sys.exc_info()[0]) error('Yahoo error, inputs => date: ' + date + ' symbol: ' + symbol) if i == 3: return False bad_line = 0 for day in yahoo_history[-2::-1]: try: echo = ( day['Date'] + '\\t' + day['Volume'] + '\\t' + day['Open'] + '\\t' + day['Close'] + '\\t' + day['High'] + '\\t' + day['Low']) subprocess.call( "echo \"{0}\" >> {1}".format(echo, path), shell=True) del echo except: error(sys.exc_info()[0]) del day if bad_line > 4: error(" aborting... bad symbol data: "+ symbol) global bad_symbols bad_symbols.append(symbol) del share del dates del exchange del bad_line del path del yahoo_history error(locals()) return False bad_line += 1 continue del yahoo_history del share return True
import time from yahoo_finance import Share # Download price of a company price = Share("YHOO") # New a file to record its current price f = open("COMPANY_NAME" + "_STOCKPRICE.txt", "wb") f.write(str(price.get_info()) + "\n") # Get open stock value f.write(str(price.get_open()) + "\n") # Get next price f.write(str(price.get_price()) + " at " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) + "\n") for i in range(0, 28): # Sleep one min time.sleep(1) # Get next price f.write(str(price.get_price()) + " at " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) + "\n") f.write("Complete!") f.close()
## From Yahoo Finance from yahoo_finance import Share yahoo = Share('YHOO') print yahoo.get_open() print yahoo.get_price() print yahoo.get_trade_datetime() yahoo.refresh() print yahoo.get_price() print yahoo.get_trade_datetime() print yahoo.get_historical('2014-04-25', '2014-04-29') from pprint import pprint pprint(yahoo.get_historical('2014-04-25', '2014-04-29')) pprint(yahoo.get_info()) # get_price() # get_change() # get_volume() # get_prev_close() # get_open() # get_avg_daily_volume() # get_stock_exchange() # get_market_cap() # get_book_value() # get_ebitda() # get_dividend_share() # get_dividend_yield() # get_earnings_share() # get_days_high()