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


Python Share.get_price方法代码示例

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


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

示例1: sell

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [as 别名]
def sell():
    if 'username' in session:
        # Get symbol name
        s = request.args.get('symbol')
        # recreate users stock information
        if not models.new_stock:
            models.Users.reload_user()
        # symbol name is valid
        if s is not None and s != '':
            symbol = Share(s)
            if symbol.get_price() is None:
                return render_template('apology.html', message=['Something went wrong. Please try again.'])
            else:
                # Get user's stock info
                holding = models.Stockholding.objects.get(username=session['username'], symbol=s)
                amount_to_add = int(holding.shares) * float(symbol.get_price())
                # add value of shares to user's cash
                models.Users.objects(username=session['username']).update(inc__cash=amount_to_add)
                # log transaction
                transaction = models.Transaction(username=session['username'], date=time.strftime("%d/%m/%Y"), \
                                            type=models.Transaction.SELL, symbol=s, shares=holding.shares)
                transaction.save()
                holding.delete() # Remove stock
                flash('Stock sold successfully', 'text-success')
                models.Users.reload_user()
                print models.new_stock
                return redirect('portfolio')
        return render_template('sell.html', stocks=models.new_stock)
    return render_template('apology.html', message=['Log In to see this page'])
开发者ID:jarifibrahim,项目名称:finance,代码行数:31,代码来源:main.py

示例2: recentdata

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [as 别名]
def recentdata(companyname):
    try:
        companydata = Share(companyname)
        print "This morning, it opened for $" + companydata.get_open() + ", and right now is at $" + companydata.get_price() + "."
        if companydata.get_open() > companydata.get_price():
            difference = float(companydata.get_open()) - float(companydata.get_price())
            if len(str(difference)) < 3:
                print "Since this morning, the price has fallen by $" + str(difference) + "0"
            else:
                print "Since this morning, the price has fallen by $" + str(difference)
        elif companydata.get_open() < companydata.get_price():
            difference = float(companydata.get_price()) - float(companydata.get_open())
            if len(str(difference)) < 3:
                print "Since this morning, the price has risen by $" + str(difference) + "0"
            else:
                print "Since this morning, the price has risen by $" + str(difference)
        print ""
        selection = raw_input(
            "Would you like some info about what the stock has been like in the past few days? Yes/No: ")
        if str.lower(selection) == "no":
            end()
        elif str.lower(selection) == "yes":
            print "Okay, please wait a moment"
    except (RuntimeError, TypeError, NameError):
        print "Whoops, something went wrong there. Are you sure you entered a valid company abbreviation?"

    finally:
        longterm(companyname)
开发者ID:robbiebarrat,项目名称:Stock_advisor,代码行数:30,代码来源:Stocks.py

示例3: get_quote

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [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

示例4: getPrice

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [as 别名]
def getPrice(share):
	for x in range(0, 30):
	
		price = Share(share)
		print price.get_price()
		stocks_price.append(price.get_price)
		
		time.sleep(60)
	print 'Share information recieved'
开发者ID:PalashMatey,项目名称:AdvBigData,代码行数:11,代码来源:FinanceBasic.py

示例5: get_stock_prices

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [as 别名]
def get_stock_prices(stock_symbol_list):
    """Returns a string that includes a list of stocks and their prices"""
    stock_response_line_list = []
    for stock_symbol in stock_symbol_list:
        stock = Share(stock_symbol)
        stock_response_line = stock_symbol + ": " + (
            stock.get_price() if stock.get_price() is not None else "Not Found")
        stock_response_line_list.append(stock_response_line)

    return "\n".join(stock_response_line_list)
开发者ID:jisaji,项目名称:stockServer,代码行数:12,代码来源:run.py

示例6: print_stats

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [as 别名]
def print_stats(ticker,is_trading_hours):
  stock = Share(ticker)
  stock.refresh()
  
  if(is_trading_hours == True):
    print("Current Price:  $" + stock.get_price() + "\n--------------------------------------")
  else:
    print("Previous Close: $" + stock.get_prev_close())
    print("Opening Price:  $" + stock.get_open())
    print("Current Price:  $" + stock.get_price() + "\n--------------------------------------")
开发者ID:ppourmand,项目名称:stockchecker,代码行数:12,代码来源:stocks.py

示例7: create_files

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [as 别名]
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()
开发者ID:maanitmehra,项目名称:big-data,代码行数:31,代码来源:Q4.py

示例8: report_current_from_yahoo

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [as 别名]
def report_current_from_yahoo(symbol):
    yahoo = Share(symbol)
    price_cur = yahoo.get_price()
    eps = yahoo.get_earnings_share()
    pe = yahoo.get_price_earnings_ratio()

    print 'yahoo: price=%s eps=%s, pe=%s'%(price_cur, eps, pe)
开发者ID:sp500,项目名称:investment,代码行数:9,代码来源:download_gf_data.py

示例9: get_stock_info

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [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

示例10: find_quote

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [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

示例11: combine

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [as 别名]
def combine(onedayago, twodaysago, threedaysago, fivedaysago, oneweekago, companyname):
    print "Analyzing data from the past few days..."
    dates = [onedayago, twodaysago, threedaysago, fivedaysago, oneweekago]
    for i in dates:
        i == i.format('YYYY-MM-DD')


    # Just gets the info and puts it into programmer friendly names
    def getclosing(date, company):
        # Thanks to stackoverflow user 'TessellatingHeckler' for helping me out with this next function! At the time dictionaries were a foreign concept to me.
        readings = company.get_historical(date, date)
        for reading in readings:
            close = reading['Close']
            return close

    company = Share(companyname)
    closingonedayago = getclosing(str(dates[0]), company)
    closingtwodaysago = getclosing(str(dates[1]), company)
    closingthreedaysago = getclosing(str(dates[2]), company)
    closingfivedaysago = getclosing(str(dates[3]), company)
    closingoneweekago = getclosing(str(dates[4]), company)
    twohundredavg = company.get_200day_moving_avg()
    fiftyavg = company.get_50day_moving_avg()
    today = company.get_price()
    decision(today, closingonedayago, closingtwodaysago, closingthreedaysago, closingfivedaysago, closingoneweekago, twohundredavg, fiftyavg)
开发者ID:robbiebarrat,项目名称:Stock_advisor,代码行数:27,代码来源:Stocks.py

示例12: check_sell

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [as 别名]
    def check_sell(self):
        #UNCOMMENT WHEN USING ACTUAL DATA
        if self.owned_shares == 0:
            return False
        
        share = Share(self.code)

        current_price_u = share.get_price()
        if current_price_u is None:
            self.log('Current Price is None for Stock')
            return 0
        
        current_price = float(current_price_u)
        
        #UNCOMMENT WHEN USING ACTUAL DATA
        if self.bought_value < current_price:
            return False
        
        avg50 = self.get_short_moving_avg()
        avg200 = self.get_long_moving_avg()
        if avg50 < avg200:
            #trend change, buy
            sell(self, self.owned_shares,current_price)
            return True
        return False
开发者ID:nfullersl,项目名称:Outsider,代码行数:27,代码来源:Outsider.py

示例13: check_buy

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [as 别名]
 def check_buy(self):
     #one-time buy
     if self.owned_shares != 0:
         return False
     share = Share(self.code)
     avg50 = self.get_short_moving_avg()
     avg200 = self.get_long_moving_avg()
     if avg50 == -1.0 or avg200 == -1.0:
         self.log('Short or Long moving average cannot be obtained due to yahoo API error')
         return 0
     
     current_price_u = share.get_price()
     if current_price_u is None:
         self.log('Current Price is None for Stock')
         return 0
     
     current_price = float(current_price_u)
     if avg50 > avg200:
         #trend change, buy
         buy_count = self.how_many_shares_to_buy(current_price)
         if buy_count != 0:
             if buy(self, buy_count, current_price) == True:
                 self.owned_shares = buy_count
                 self.bought_value = float(current_price * self.owned_shares)
         return self.owned_shares
     return 0
开发者ID:nfullersl,项目名称:Outsider,代码行数:28,代码来源:Outsider.py

示例14: stocks

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [as 别名]
    def stocks(self, message, params=None, **kwargs):
        """Display current stock value for user provided symbol(s)
        (ex: .stock rax,yhoo,aapl)
        """

        if not params:
            message.dispatch("No stock symbol provided, please provide "
                             "at least one symbol. Example: .stock rax or "
                             ".stock rax,yhoo,aapl")
            return

        text = ""
        try:
            symbols = params.upper().split(',')
            for s in symbols:
                share = Share(s)
                text = (text + "%s: %s (%s) | " %
                        (s, share.get_price(), share.get_change()))
            text = text.rstrip(" ")
            text = text.rstrip("|")
        except Exception:
            text = ("Unable to fetch stocks data. "
                    "Please ensure the symbols you've provided are valid")

        message.dispatch(text)
开发者ID:bdelliott,项目名称:pyhole,代码行数:27,代码来源:stocks.py

示例15: get_stock_price_and_volume

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_price [as 别名]
def get_stock_price_and_volume(symbol, start_date, end_date, dates):
	share = Share(symbol)
	hist_data = share.get_historical(start_date, end_date)
	hist_data.reverse()
	volume = []
	price = []
	i = 0
	for d in dates:
		if i < len(hist_data):
			if (hist_data[i]['Date'] == d):
				# Weekday
				price.append(hist_data[i]['Close'])
				volume.append(hist_data[i]['Volume'])
				i += 1
			else:
				# Weekend
				price.append(0)
				volume.append(0)
		else:
			# Get the current price and volume instead from historical data
			price.append(share.get_price())
			volume.append(share.get_volume())
	if len(dates) != len(volume) and len(dates) != len(price):
		print 'Dates and volume and/or price lists are not of same lenght!'
	return [price, volume]
开发者ID:benzemann,项目名称:TwitterStockAnalyzer,代码行数:27,代码来源:stock_data_downloader.py


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