本文整理汇总了Python中yahoo_finance.Share.get_days_low方法的典型用法代码示例。如果您正苦于以下问题:Python Share.get_days_low方法的具体用法?Python Share.get_days_low怎么用?Python Share.get_days_low使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类yahoo_finance.Share
的用法示例。
在下文中一共展示了Share.get_days_low方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_quote
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [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 '-'
}
示例2: find_quote
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [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
示例3: stock_summary
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [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})
示例4: get_today_stock_data
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [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 {}
示例5: post
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [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
示例6: rec
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [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()
示例7: main
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [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))
示例8: fetch_current_data
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [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)
示例9: history
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [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)
示例10: get_stock_info
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [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
示例11:
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [as 别名]
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:
ebitda = stock.get_ebitda()
print ebitda
if myargs.ps is True:
示例12: main
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [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
示例13: getHistoricalData
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [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
示例14: len
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [as 别名]
if len(ticker) == 0:
continue
stock = Share(ticker)
stock.refresh()
change = (float(stock.get_price()) - float(stock.get_prev_close()))/float(stock.get_prev_close())
change = round(change *100.0, 2)
if change > 0.0:
change= '+' + str(change)
else:
change =str(change)
line = ticker.ljust(7)
line += stock.get_price().ljust(9)+ change.ljust(8)+ stock.get_volume().ljust(11) + \
str(round(float(stock.get_volume())/float(stock.get_avg_daily_volume())*100.0)).ljust(8) +\
stock.get_open().ljust(10)+ \
stock.get_days_low().ljust(10)+ \
stock.get_days_high().ljust(10)+ \
stock.get_year_low().ljust(10)+ \
stock.get_year_high().ljust(10)
line = line + str(stock.get_market_cap()).ljust(11) + \
str(stock.get_price_earnings_ratio()).ljust(8)+\
stock.get_50day_moving_avg().ljust(10) +\
stock.get_200day_moving_avg().ljust(10)
print(line)
except Exception as e:
print("Exception error:", str(e))
traceback.print_exc()
i+=1
#you get get a spy.txt and then filter everything by yourself
示例15: main
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_days_low [as 别名]
def main():
global shareName
global stream
global buyPrice
global shareAmount
global currentBallance
global beforePrice
global dayOpen
global dayHigh
global dayLow
cls()
start = 1
prevPrice = 0
textNum = 1
textNumLimit = 6
sellPriceReached = False
buyPrice = 131.09
beforePrice = buyPrice
shareAmount = 10
shareName = raw_input("Enter The Share You Would Like To Monitor:\n" + "--"*25 + "\n> ").strip().upper() #YHOO
alertPrice = buyPrice * 1.20
riskThreshold = buyPrice / 1.20
cls()
waitTime = 1 #Until Starts
initDatabase()
UpDownValues = [""]
print ">" + "-"*52 + ":Monitoring_Share_[" + shareName + "]:" + "-"*52 + "<"
while True:
try:
status = most_common(UpDownValues)
share = Share(shareName)
price = getPrice(share, "false", None)
dayOpen = share.get_open()
dayHigh = share.get_days_high()
dayLow = share.get_days_low()
if price == prevPrice:
pass
else:
info = getPrice(share, "true", status)
saveToDatabase(info, 1)
print info
if price > prevPrice:
UpDownValues.append("UP")
elif price < prevPrice:
UpDownValues.append("DOWN")
if len(UpDownValues) > 15: #Risk Threshold to pull out
UpDownValues.pop()
if float(price) >= float(alertPrice):
if str(status) == "DOWN":
if price < riskThreshold:
sellShares(shareAmount/2)
#sendMessage("Current Status:\n" + str(sellProfit("phone")) + "\n>" + "---"*5 + "<\nSell Half of Shares.")
elif str(status) == "UP":
if price >= buyPrice:
if price >= alertPrice:
sellPriceReached = True
sellShares(shareAmount)
if textNum <= textNumLimit:
#sendMessage("Current Status:\n" + str(sellProfit("phone")) + "\n>" + "---"*5 + "<\nBen's Monitor.")
pass
else:
pass
if sellPriceReached == True:
if price < alertPrice - 10:
sellShares("All")
prevPrice = price
xValue = getTime()
yValue = price
time.sleep(0.3) #Default: (0.3)
except Exception, e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
if "'str' and 'NoneType'" in str(e):
raw_input("-"*75 + "\nCurrent Share Status:\n[Error] | Unable to find the share: [" + shareName + "] | Press (Enter) To Go Back To Main Menu.\n" + "> ")
main()
elif "object has no attribute" in str(e):
pass
elif "Query failed with error" in str(e):
pass
elif "Expecting value: line 1 column 1 (char 0)" in str(e):
pass
elif "float() argument must be a string or a number" in str(e):
cls()
raw_input("[Input Error] | Unable To Find Share(" + shareName + ")\nPress Enter To Retry:\n>------------------------------------------------<\n> ")
main()
else:
print "[Error] " + str(exc_tb.tb_lineno) + " | > " + str(e)
except KeyboardInterrupt:
print "\n"*2 + sellProfit("pause")
chs = raw_input(">"+"---"*16 + "<\n> Main Menu----------------(1)\n> Continue Monitoring------(Any Key)\n>" + "-"*36 + "<\n> ")
if "2" in chs:
#.........这里部分代码省略.........