本文整理汇总了Python中yahoo_finance.Share方法的典型用法代码示例。如果您正苦于以下问题:Python yahoo_finance.Share方法的具体用法?Python yahoo_finance.Share怎么用?Python yahoo_finance.Share使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类yahoo_finance
的用法示例。
在下文中一共展示了yahoo_finance.Share方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getStockData
# 需要导入模块: import yahoo_finance [as 别名]
# 或者: from yahoo_finance import Share [as 别名]
def getStockData(theTicker, startDate):
stock = Share(theTicker)
print("Getting Data for ... " + theTicker)
now = datetime.now()
DateNow = str(now.year) + "-" + str(now.month) + "-" + str(now.day)
data = stock.get_historical(startDate, DateNow)
stockData = []
for d in data:
tmp = []
volume = int(d['Volume'])
adjclose = float(d['Adj_Close'])
high = float(d['High'])
low = float(d['Low'])
close = float(d['Close'])
date = d['Date']
open = float(d['Open'])
tmp.append(date)
tmp.append(open)
tmp.append(high)
tmp.append(low)
tmp.append(close)
tmp.append(adjclose)
tmp.append(volume)
stockData.append(tmp)
return stockData
示例2: stock_Prices
# 需要导入模块: import yahoo_finance [as 别名]
# 或者: from yahoo_finance import Share [as 别名]
def stock_Prices():
# exit if the output already existed
# if os.path.isfile('./input/stockPrices.json'):
# sys.exit("Prices data already existed!")
priceSet = {}
fin = open('./input/tickerList.csv')
for num, line in enumerate(fin):
line = line.strip().split(',')
ticker, name, exchange, MarketCap = line
if 1:
print(num, ticker)
yahoo = Share(ticker)
time.sleep(np.random.poisson(3))
prices = yahoo.get_historical('2005-01-01', '2020-01-01')
priceDt = {}
for i in range(len(prices)):
date = ''.join(prices[i]['Date'].split('-'))
priceDt[date] = round(log(float(prices[i]['Close']) / float(prices[i]['Open'])), 6)
priceSet[ticker] = priceDt
#except:
#continue
with open('./input/stockPrices.json', 'w') as outfile:
json.dump(priceSet, outfile, indent=4)
开发者ID:WayneDW,项目名称:Sentiment-Analysis-in-Event-Driven-Stock-Price-Movement-Prediction,代码行数:27,代码来源:crawler_stockPrices.py
示例3: get_stock_info_and_historical_data
# 需要导入模块: import yahoo_finance [as 别名]
# 或者: from yahoo_finance import Share [as 别名]
def get_stock_info_and_historical_data(symbol):
"""Retrieve stock info and historical data for `symbol`
Leverages yahoo-finance for Python
https://github.com/lukaszbanasiak/yahoo-finance
"""
share = yahoo_finance.Share(symbol)
info = share.get_info()
start_date = info['start']
end_date = info['end']
historical = share.get_historical(start_date, end_date)
data = {
'info' : info,
'historical' : historical,
}
return data
示例4: get_quote
# 需要导入模块: import yahoo_finance [as 别名]
# 或者: from yahoo_finance import Share [as 别名]
def get_quote(self, session, stock, data=None):
update_time = pd.Timestamp(datetime.datetime.now()) - pd.DateOffset(minutes=15)
if stock is None or not hasattr(stock, 'quotes') or not hasattr(stock, 'symbol'):
return None
seconds = self.seconds_until_market_open()
quote = self.get_quote_latest(session, stock)
market_closed = (seconds > 15*60)
if quote is None \
or (not market_closed and quote.date_inserted <= update_time)\
or (market_closed and quote.date_inserted.minute < 30 and quote.date_inserted.hour == 13):
if data is None:
data = get_stock_data(Share(stock.symbol), field_map)
quote = Quote(**{k: v
for k, v in data.items()
if k in quote_keys})
logger.info("UPDATED QUOTE: {}".format(quote))
stock.quotes.append(quote)
else:
logging.info("EXISTING QUOTE: {}".format(quote))
return quote
示例5: getReturns
# 需要导入模块: import yahoo_finance [as 别名]
# 或者: from yahoo_finance import Share [as 别名]
def getReturns(stocks = 'MSFT,AAPL,NFLX,JPM,UVXY,RSX,TBT', period_days = 100, end = '2016-12-09'):
stocks = stocks.split(",")
index = 'SPY'
stocks.append(index)
if end is None:
end = datetime.today().strftime("%Y-%m-%d")
start = (datetime.today() - timedelta(period_days)).strftime("%Y-%m-%d")
i = 0
w= pd.DataFrame()
t = []
for s in stocks:
z = Share(s)
px = pd.DataFrame(z.get_historical(start,end))[['Close','Date']]
px['Close']=px['Close'].astype(float)
px.index = px['Date']
del px['Date']
px.columns = [s]
t.append(px)
w = pd.concat(t,axis=1, join='inner')
w = w.sort_index().pct_change() #returns => w.cov() covariance matrix of returns
#calculate betas
betas = []
for s in stocks:
if s != index:
col = np.column_stack((w[s],w[index]))
b = np.cov(col)/np.var(w[index])
betas.append(b)
stocks.remove(index)
del w[index]
returns = w
return returns,stocks,np.round(betas,4)
示例6: get_stock_price
# 需要导入模块: import yahoo_finance [as 别名]
# 或者: from yahoo_finance import Share [as 别名]
def get_stock_price(symbol):
"""Retrieve the latest price for `symbol` representing stock
"""
share = yahoo_finance.Share(symbol)
price = share.get_price()
return price
示例7: _add_stock
# 需要导入模块: import yahoo_finance [as 别名]
# 或者: from yahoo_finance import Share [as 别名]
def _add_stock(self, session, name, data=None):
if data is None:
try:
data = get_stock_data(Share(name), field_map)
except:
return None
stock = Stock(**{k: v for k, v in data.items() if k in stock_keys})
try:
session.add(stock)
except:
pass
return data
示例8: update_historical
# 需要导入模块: import yahoo_finance [as 别名]
# 或者: from yahoo_finance import Share [as 别名]
def update_historical(self, session, stock, start_date, end_date):
share = Share(stock.symbol)
try:
data = get_stock_data_historical(share, start_date, end_date)
except YQLResponseMalformedError as e:
logger.error(e)
return None
matching_quotes = session.query(Quote).filter(and_(Quote.stock_id == stock.id,
Quote.date_last_traded >= pd.Timestamp(start_date),
Quote.date_last_traded <= pd.Timestamp(end_date)))\
.order_by(Quote.date_inserted.asc())
dates = [pd.Timestamp(q.date_last_traded).date() for q in matching_quotes.all()
if pd.Timestamp(q.date_last_traded).hour > 13]
quotes = []
for record in data:
try:
if record[Quote.date_last_traded.name].date() not in dates:
quote = Quote(**{k: v
for k, v in record.items()
if k in quote_keys})
quote.symbol_name = stock.symbol_name
quote.stock_exchange = stock.stock_exchange
quote.trade_currency = stock.trade_currency
quotes.append(quote)
stock.quotes.append(quote)
except (KeyError, ValueError) as e:
logger.error("Error parsing historical quote - {} - {}".format(e, record))
[session.add(q) for q in quotes]
return quotes
示例9: generate_stock_updates
# 需要导入模块: import yahoo_finance [as 别名]
# 或者: from yahoo_finance import Share [as 别名]
def generate_stock_updates(file_path=None):
if file_path is None:
file_path = 'C:/Users/Zeke/Google Drive/Documents/Financial/td_ameritrade/'\
'Watchlist_Uranium_2017-02-18.xlsx'
df = read_excel(file_path)
new_data = []
for i in range(df.index.size):
row = df.iloc[i]
share = Share(row['Symbol'])
new_data.append(share.__dict__.get('data_set', {}))
path_out = os.path.splitext(file_path)[0] + '-updated.csv'
new_df = DataFrame(new_data, index=range(len(new_data)))
new_df.to_csv(path_out)
示例10: get_quotes
# 需要导入模块: import yahoo_finance [as 别名]
# 或者: from yahoo_finance import Share [as 别名]
def get_quotes(self):
self.debug("getting quotes")
try:
quotes = {}
for i in self.assets:
yahoo = Share(i)
quotes[i] = {
"source": "yahoo",
"last": float(yahoo.get_price())
}
return quotes
except OSError:
self.error("Network Error")