当前位置: 首页>>代码示例>>Python>>正文


Python Share.get_days_high方法代码示例

本文整理汇总了Python中yahoo_finance.Share.get_days_high方法的典型用法代码示例。如果您正苦于以下问题:Python Share.get_days_high方法的具体用法?Python Share.get_days_high怎么用?Python Share.get_days_high使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在yahoo_finance.Share的用法示例。


在下文中一共展示了Share.get_days_high方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_quote

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
def get_quote(symbol):
    share = Share(symbol)

    if not share.get_price():
        return {}

    change_f = float(share.get_change())
    change_str = '+%.02f' % change_f if change_f >= 0 else '%.02f' % change_f

    change_percent_f = change_f / float(share.get_open()) * 100
    change_percent = '+%.02f' % change_percent_f if change_percent_f >= 0 else '%.02f' % change_percent_f

    return {
        'price': share.get_price(),
        'change': change_str,
        'change_percent': change_percent,
        'open_price': share.get_open(),
        'market_cap': share.get_market_cap(),
        'year_low': share.get_year_low(),
        'year_high': share.get_year_high(),
        'day_low': share.get_days_low(),
        'day_high': share.get_days_high(),
        'volume': share.get_volume(),
        'pe_ratio': share.get_price_earnings_ratio() or '-'
    }
开发者ID:karan,项目名称:slashStock,代码行数:27,代码来源:share.py

示例2: find_quote

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
def find_quote(word):
    """Given an individual symbol, 
    find and return the corresponding financial data

    word -- the symbol for which you're finding the data (ex. "GOOG")
    """
    cleanword=re.sub('[@<>]', '', word)
    share = Share(cleanword)
    price = share.get_price()
    if price != None:
        
        # Extract data
        day_high = share.get_days_high()
        day_low = share.get_days_low()
        market_cap = share.get_market_cap()
        year_high = share.get_year_high()
        year_low = share.get_year_low()
        yoy = calculate_YoY(share)
        
        output_string = ('*Stock*: \'{}\' \n*Current Price*: ${} \n*Day Range*: '
        '${} - ${} \n*52 Wk Range*: ${} - ${} \n*YoY Change*: {}\n*Market Cap*: ' 
        '${}').format(word.upper(), str(price), str(day_low), str(day_high), 
                      str(year_low), str(year_high), str(yoy), str(market_cap))
    else:
        output_string = "Can't find a stock with the symbol \'" + cleanword.upper() + "\'"
    return output_string
开发者ID:cristhiandick,项目名称:stock-quote-slackbot,代码行数:28,代码来源:stockbot.py

示例3: get_stock_info

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
def get_stock_info(symbols, moreInfo=False):
	""" 
	Scrape stock info from Yahoo finance
	@Param 'moreInfo': False for getting price, True for getting more information
	@Return 'message': "symbol: Price-number, Open Price-number, Pre Close Price-number, High Price-number, 
						Low price-number"
	"""
	message = ''
	for symbol in symbols:
		try:
			stock = Share(symbol)
			price = stock.get_price()
		except AttributeError:
			price = None
		
		if price == None: # Stock symbol not exists, replace with an alert message
			message += '#' + symbol + ': ' + 'The stock symbol does not exit' + '\n'
		elif moreInfo: 
			message += '#%s: Price-%s, Open Price-%s, Pre Close Price-%s, High Price-%s, Low price-%s\n' \
						% (symbol, price, stock.get_open(), stock.get_prev_close(), stock.get_days_high(), stock.get_days_low())
		else:
			message += '#' + symbol + ': ' + price + '\n'

	alert_message = 'Please type #1 followed by stock symbols to get more information' if moreInfo == True else \
					'Please type #0 followed by stock symbols to get stock price'
	return message if message != '' else alert_message
开发者ID:HugoZhang33,项目名称:StockTicker,代码行数:28,代码来源:views.py

示例4: stock_summary

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
def stock_summary(request, symbol=None):
    if symbol == None:
        symbol = request.POST['symbol']

    current_stock = Stock()
    stock = Share(symbol)
    current_stock.symbol = symbol.upper()
    current_stock.price = stock.get_price()
    current_stock.change = stock.get_change()
    current_stock.volume = stock.get_volume()
    current_stock.prev_close = stock.get_prev_close()
    current_stock.stock_open = stock.get_open()
    current_stock.avg_daily_volume = stock.get_avg_daily_volume()
    current_stock.stock_exchange = stock.get_stock_exchange()
    current_stock.market_cap = stock.get_market_cap()
    current_stock.book_value = stock.get_book_value()
    current_stock.ebitda = stock.get_ebitda()
    current_stock.dividend_share = stock.get_dividend_share()
    current_stock.dividend_yield = stock.get_dividend_yield()
    current_stock.earnings_share = stock.get_earnings_share()
    current_stock.days_high = stock.get_days_high()
    current_stock.days_low = stock.get_days_low()
    current_stock.year_high = stock.get_year_high()
    current_stock.year_low = stock.get_year_low()
    current_stock.fifty_day_moving_avg = stock.get_50day_moving_avg()
    current_stock.two_hundred_day_moving_avg = stock.get_200day_moving_avg()
    current_stock.price_earnings_ratio = stock.get_price_earnings_ratio()
    current_stock.price_earnings_growth_ratio = stock.get_price_earnings_growth_ratio()
    current_stock.price_sales = stock.get_price_sales()
    current_stock.price_book = stock.get_price_book()
    current_stock.short_ratio = stock.get_short_ratio()

    date_metrics = []
    url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+symbol+'/chartdata;type=quote;range=1y/csv'
    page = urllib2.urlopen(url).read()
    pagebreaks = page.split('\n')
    for line in pagebreaks:
        items = line.split(',')
        if 'Company-Name:' in line:
            current_stock.company_name = line[13:len(line)]
            current_stock.save()
        if 'values' not in items:
            if len(items)==6:
                hd = HistoricalData(
                    stock_id = Stock.objects.get(id=int(current_stock.id)).id,
                    date = items[0][4:6]+'/'+items[0][6:9]+'/'+items[0][0:4],
                    close = items[1][0:(len(items[1])-2)],
                    high = items[2][0:(len(items[2])-2)],
                    price_open = items[3][0:(len(items[3])-2)],
                    low = items[4][0:(len(items[4])-2)],
                    volume = items[5][0:-6]+","+items[5][-6:-3]+","+items[5][-3:len(items[5])])
                hd.save()
                date_metrics.append(hd)
    del date_metrics[0]
    return render(request, "stock_summary.html", {'current_stock': current_stock, 'date_metrics': date_metrics})
开发者ID:dannyshafer,项目名称:Chrysalis-Mutual-Funds-Python-Django-,代码行数:57,代码来源:views.py

示例5: post

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
def post():
	## Update stock info
	try:
		stock_list = Stock.objects.all()
		for stock in stock_list:
			try:
				s = Share(stock.symbol)
				stock.price = s.get_price()
				stock.open_price = s.get_open()
				stock.pre_close_price = s.get_prev_close()
				stock.high_price = s.get_days_high()
				stock.low_price = s.get_days_low()
				stock.save()
			except Exception, e:
				pass
	except Exception, e:
		pass
开发者ID:HugoZhang33,项目名称:StockTicker,代码行数:19,代码来源:tasks.py

示例6: get_today_stock_data

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
 def get_today_stock_data(ticker):
     try:
         s = Share(ticker)
         data = {
             'Open': float(s.get_open()),
             'Close': float(s.get_prev_close()),
             'High': float(s.get_days_high()),
             'Low': float(s.get_days_low()),
             'Volume': int(s.get_volume()),
             'Date': datetime.date.today(),
         }
         return data
     except YQLQueryError:
         logger.error("Daily data not found for {}".format(ticker))
     except Exception as e:
         logger.error("Unexpected error occurred: {}".format(e))
     return {}
开发者ID:kacperadach,项目名称:stock_market_analysis,代码行数:19,代码来源:Data_Fetcher.py

示例7: rec

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
def rec(p):
	yahoo = Share(p)
	a=yahoo.get_prev_close()
	b=yahoo.get_year_high()
	c=yahoo.get_year_low()
	d=yahoo.get_open()
	e=yahoo.get_ebitda()
	f=yahoo.get_market_cap()
	g=yahoo.get_avg_daily_volume()
	h=yahoo.get_dividend_yield()
	i=yahoo.get_earnings_share()
	j=yahoo.get_days_low()
	k=yahoo.get_days_high()
	l=yahoo.get_50day_moving_avg()
	m=yahoo.get_200day_moving_avg()
	n=yahoo.get_price_earnings_ratio()
	o=yahoo.get_price_earnings_growth_ratio()
	print p
	print "Previous Close: ",a
	print "Year High",b
	print "Year Low",c
	print "Open:",d
	print "EBIDTA",e 
	print "Market Cap",f
	print "Average Daily Volume",g 
	print "Dividend Yield",h
	print "Earnings per share",i 
	print "Days Range:", j ,"-",k
	print "50 Days Moving Average",l 
	print "200 Days Moving Average",m
	print"Price Earnings Ratio", n
	print"Price Earnings Growth Ratio",o

	import MySQLdb
	db = MySQLdb.connect(host="127.0.0.1", user="root",passwd="1111", db="stocks",local_infile = 1)  
	cur=db.cursor()
	cur.execute ("""
	            INSERT INTO stockapp_info (symbol, prev_close, year_high, year_low, open_price , ebidta, market_cap, avg_daily_vol , dividend_yield, eps , days_low ,days_high, moving_avg_50, moving_avg_200, price_earnings_ratio, price_earnings_growth_ratio)
	            VALUES
	                (%s, %s, %s, %s, %s, %s, %s,%s,%s,%s,%s,%s,%s,%s,%s,%s)

	        """, (p,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o))
	db.commit() 
	cur.close()
开发者ID:rpandya1990,项目名称:Stock-Prediction-Web-Application,代码行数:46,代码来源:stockinfo.py

示例8: sp500info

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
def sp500info(): #gets the S&P 500 price, ticker, changes, etc.
	sp500ticker = '^GSPC' 
	sp500desc = "S&P 500 Index: "
	sp500index = Share(sp500ticker)
	#sp500price = sp500index.get_price()
	sp500price = scraper(sp500ticker)
	#sp500change = sp500index.get_change()
	sp500open = sp500index.get_open()
	#print sp500index.get_50day_moving_avg()
	#print sp500index.get_200day_moving_avg()
	#print sp500ma50, sp500ma200
	sp500price = str(sp500price).strip('[]')
	sp500price = sp500price.replace(",", "")
	#print(repr(sp500price)) #scrub the ticker for hidden values; troubleshooting
	sp500change = float(sp500price) - float(sp500open)
	sp500dayhigh = sp500index.get_days_high()
	sp500percentchange = getPercentChange(sp500index, sp500change, sp500open)

	return sp500percentchange, sp500dayhigh, sp500open, sp500change, sp500price, sp500index, sp500desc
开发者ID:nhsb1,项目名称:config,代码行数:21,代码来源:sp500dailychanges.py

示例9: main

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
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))
开发者ID:shihyu,项目名称:crawl-stock,代码行数:43,代码来源:crawl.py

示例10: fetch_current_data

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
 def fetch_current_data(self, sym):
     ts = get_latest_trading_date(get_cur_time())
     if ts in self.datasets_daily[sym].keys() or ts > self.endDate:
         return
     try:
         sdata = Share(sym)
         gquote = gQuotes(sym)
     except:
         # live with the fact that data from the most recent day is missing
         return
     self.datasets_daily[sym][ts] = t = {}
     t['Date']  = '3000-01-01' #debugging purposes, so we know this is current. This won't be saved to file
     t['High']  = float(sdata.get_days_high())
     t['Low']   = float(sdata.get_days_low())
     t['Open']  = float(sdata.get_open())
     # t['Close'] = sdata.get_price()
     t['Close'] = float(gquote[0]['LastTradePrice']) # use google data for latest 'Close', which is more accurate
     t['Volume'] = float(sdata.get_volume())
     for k in t.keys():
         if t[k] == None:
             raise Exception('missing most recent daily', sym)
开发者ID:codelol,项目名称:pstock,代码行数:23,代码来源:usdata.py

示例11: history

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
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)
开发者ID:gravity226,项目名称:NASDAQ,代码行数:40,代码来源:mp_app.py

示例12: getHistoricalData

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
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
开发者ID:CreepOn,项目名称:StockMeUpScotty,代码行数:26,代码来源:loadDataFunctions.py

示例13:

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
		print getbook

	if myargs.dividendshare is True:
		getdiv = stock.get_dividend_share()
		print getdiv

	if myargs.dividendyield is True:
		dividendyield = stock.get_dividend_yield()
		print dividendyield

	if myargs.eps is True:
		eps = stock.get_earnings_share()
		print eps

	if myargs.dayh is True:
		dayhigh = stock.get_days_high()
		print dayhigh

	if myargs.dayl is True:
		daylow = stock.get_days_low()
		print daylow

	if myargs.yearhigh is True:
		yearhigh = stock.get_year_high()
		print yearhigh

	if myargs.yearlow is True:
		yearlow = stock.get_year_low()
		print yearlow

	if myargs.ebitda is True:
开发者ID:nhsb1,项目名称:config,代码行数:33,代码来源:yfcmd.py

示例14: main

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
def main():
    # 1. get the time
    day = Time.get_utc_day()
    hours_mins = Time.get_utc_hours_minutes()

    # 1. Get all the list of stocks
    stocks = base.managers.stock_manager.get_many()

    # 2. go through stock and update the desired values
    for stock in stocks:
        ticker = stock.get('ticker')

        try:
            # 2.1 Get the info from the yahoo API
            updated_stock = Share(ticker)
        except:
            print "-->Failed to update: %s with Yahoo API" % ticker
            continue

        price = updated_stock.get_price()
        open = updated_stock.get_open()
        days_high = updated_stock.get_days_high()
        days_low = updated_stock.get_days_low()
        year_high = updated_stock.get_year_high()
        year_low = updated_stock.get_year_low()
        volume = updated_stock.get_volume()
        market_cap = updated_stock.get_market_cap()
        pe_ratio = updated_stock.get_price_earnings_ratio()
        div_yield = updated_stock.get_dividend_yield()
        change = updated_stock.get_change()
        change_percent = updated_stock.data_set.get('ChangeinPercent')

        # 2.2 Get the stock body
        stock_body = stock.get('body')

        stock_price = {hours_mins: price}

        if stock_body:
            # 1. Get the stock info for the day:
            stock_info = stock_body.get(day)

            if stock_info:
                stock_price = stock_info.get('price')
                stock_price.update({hours_mins: price})
        else:
            stock_body = {}

        # 2.2.4 update the stock info dict
        stock_info = {'price': stock_price}
        stock_info.update({'open': open})
        stock_info.update({'days_high': days_high})
        stock_info.update({'days_low': days_low})
        stock_info.update({'year_high': year_high})
        stock_info.update({'year_low': year_low})
        stock_info.update({'volume': volume})
        stock_info.update({'market_cap': market_cap})
        stock_info.update({'pe_ratio': pe_ratio})
        stock_info.update({'div_yield': div_yield})
        stock_info.update({'change': change})
        stock_info.update({'change_percent': change_percent})

        # update the stock body
        stock_body.update({day: stock_info})

        stock.body = stock_body

        # 3. update the stock in the DB
        try:
            base.managers.stock_manager.update_one(stock)
        except:
            print "-->Failed to update: %s in DB" % ticker
            continue
开发者ID:dontlivetwice,项目名称:westock,代码行数:74,代码来源:cron_stocks.py

示例15: predict

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_high [as 别名]
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")
开发者ID:gravity226,项目名称:NASDAQ,代码行数:79,代码来源:mp_app.py


注:本文中的yahoo_finance.Share.get_days_high方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。