本文整理汇总了Python中yahoo_finance.Share.get_historical方法的典型用法代码示例。如果您正苦于以下问题:Python Share.get_historical方法的具体用法?Python Share.get_historical怎么用?Python Share.get_historical使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类yahoo_finance.Share
的用法示例。
在下文中一共展示了Share.get_historical方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_data
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [as 别名]
def get_data(symbol='^GSPC'):
symbol1 = symbol
if symbol1[0] == '^':
symbol1 = symbol[1:]
fileName = 'c:/data/%s.csv' % symbol1
keys = ['Date', 'Close'] # only save these fields
gspc = Share(symbol)
if os.path.isfile(fileName):
result = read_data(fileName)
oneday = timedelta(1)
yesterday = datetime.today().date() - oneday
latest = datetime.strptime(result[0]['Date'], '%Y-%m-%d').date()+oneday
if latest < yesterday:
print('Extending from %s to %s ...' % (str(latest), str(yesterday)))
result = gspc.get_historical(str(latest), str(yesterday)) + result
write_data(fileName, result, keys)
else:
print('No need to update')
else:
result = gspc.get_historical('1976-02-01', '2016-02-21')
write_data(fileName, result, keys)
return result
示例2: getDifferencePercentage
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [as 别名]
def getDifferencePercentage(self):
closing = []
shareName = Share(self.company)
self.getTimeStamp()
startDate=''
endDate=''
hist=''
for t in self.times:
todayTimeStamp = t
yesterdayTimeStamp = t-86400
startDate = str(datetime.datetime.fromtimestamp(todayTimeStamp).strftime('%Y-%m-%d'))
yesterdayDate=str(datetime.datetime.fromtimestamp(yesterdayTimeStamp).strftime('%Y-%m-%d'))
todayHist = shareName.get_historical(startDate, startDate)
yesterdayHist = shareName.get_historical(yesterdayDate,yesterdayDate)
while(len(todayHist)==0):
todayTimeStamp = todayTimeStamp+86400
startDate = str(datetime.datetime.fromtimestamp(todayTimeStamp).strftime('%Y-%m-%d'))
todayHist = shareName.get_historical(startDate, startDate)
while(len(yesterdayHist)==0):
yesterdayTimeStamp= yesterdayTimeStamp-86400
yesterdayDate=str(datetime.datetime.fromtimestamp(yesterdayTimeStamp).strftime('%Y-%m-%d'))
yesterdayHist = shareName.get_historical(yesterdayDate,yesterdayDate)
closingPriceToday = float(todayHist[0]['Close'])
closingPriceYesterday = float(yesterdayHist[0]['Close'])
difference = (float(closingPriceYesterday) - float(closingPriceToday))*100.0/float(closingPriceYesterday)
diff2 = float(format(difference, '.3f'))
closing.append(diff2)
self.differencePercentage = closing
return closing
示例3: compare_stock
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [as 别名]
def compare_stock(stock_1, stock_2, start_date, end_date):
share_1 = Share( stock_1 )
hist_1 = share_1.get_historical( start_date, end_date )
share_2 = Share( stock_2 )
hist_2 = share_2.get_historical( start_date, end_date )
total_date = 0
correct_prediction = 0
len_1 = len( hist_1 )
len_2 = len( hist_2 )
length = min(len_1, len_2)
i = 0
j = 0
# for i in range (0, length):
while ( i < len_1 and j < len_2 ):
x = hist_1[i]
y = hist_2 [i];
open = float( x['Open'])
close = float( x['Close'])
x_change = (close - open) * 100 / open
open = float( y['Open'] )
close = float( y['Close'] )
y_change = (close - open) * 100 / open
if x['Date'] != y['Date']:
print "Error! DATE doesn't match"
i += 1
j += 1
continue
total_date += 1
if y_change * x_change > 0:
# print "Wow, They have Same performance"
correct_prediction += 1
else:
print x['Date'] + ": " + stock_1 + " "+ str( x_change ) + " vs. " + stock_2 + " " + str( y_change )
# print "Dam, they differs!"
i += 1
j += 1
print "Total date is: " + str(total_date) + ", and correct prediction has " + str(correct_prediction )
if total_date > 0:
print "Correction rate is: " + str( correct_prediction * 1.0 / total_date )
else:
print "ERROR: Nothing compared!"
示例4: refresh_data
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [as 别名]
def refresh_data(self, s_date=None, e_date=None):
if s_date and e_date:
try:
share=Share(self.name)
self.begin=s_date
self.end=e_date
share.get_historical(s_date, e_date)
self.log.refresh("{} data collected".format(self.name))
except:
self.log.error("platform is offline or not connecting")
示例5: readLast5DaysStockPrice
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [as 别名]
def readLast5DaysStockPrice():
with open('stock_features.csv', 'w') as csvfile:
fieldnames = ['Stock', 'Adj_Close_1','High_1', 'Low_1'
,'Adj_Close_2','High_2', 'Low_2','VolChg2_1','IndexChg2_1'
,'Adj_Close_3','High_3', 'Low_3','VolChg3_2','IndexChg3_2'
,'Adj_Close_4','High_4', 'Low_4','VolChg4_3','IndexChg4_3'
,'Adj_Close_5','High_5', 'Low_5','VolChg5_4','IndexChg5_4']
writer = csv.DictWriter(csvfile, lineterminator='\n', fieldnames=fieldnames)
writer.writeheader()
dow_code = 'BCB/UDJIAD1'
dji_index = []
j = 0
while (j < 10):
ticker = Share(stock_dict.get(j))
i = 0
stock_price = []
current_date = date.today()
fmt = '%Y-%m-%d'
while( i < 5):
if (ticker.get_historical(current_date.strftime(fmt), current_date.strftime(fmt)) == []):
current_date = current_date - timedelta(days=1)
else:
stock_price += ticker.get_historical(current_date.strftime(fmt), current_date.strftime(fmt))
if(j == 0):
if(i == 0 and Quandl.get(dow_code, trim_start=current_date, trim_end=current_date, authtoken="T246AaoCUiwSyz1C4Vfe").values.tolist() == []):
dji_index.append(get_latest_dji())
else:
dji_index.append(Quandl.get(dow_code, trim_start=current_date, trim_end=current_date, authtoken="T246AaoCUiwSyz1C4Vfe").values.tolist()[0][0])
current_date = current_date - timedelta(days=1)
i = i + 1
AbVolChg2_1 = int(stock_price[1].get('Volume')) - int(stock_price[0].get('Volume'))
VolChg2_1 = log(AbVolChg2_1,2) if AbVolChg2_1 > 0 else -1*log(fabs(AbVolChg2_1),2)
AbVolChg3_2 = int(stock_price[2].get('Volume')) - int(stock_price[1].get('Volume'))
VolChg3_2 = log(AbVolChg3_2,2) if AbVolChg3_2 > 0 else -1*log(fabs(AbVolChg3_2),2)
AbVolChg4_3 = int(stock_price[3].get('Volume')) - int(stock_price[2].get('Volume'))
VolChg4_3 = log(AbVolChg4_3,2) if AbVolChg4_3 > 0 else -1*log(fabs(AbVolChg4_3),2)
AbVolChg5_4 = int(stock_price[4].get('Volume')) - int(stock_price[3].get('Volume'))
VolChg5_4 = log(AbVolChg5_4,2) if AbVolChg5_4 > 0 else -1*log(fabs(AbVolChg5_4),2)
writer.writerow({'Stock': stock_dict.get(j)
,'Adj_Close_1' : stock_price[0].get('Adj_Close'),'High_1' : stock_price[0].get('High'),'Low_1' : stock_price[0].get('Low')
,'Adj_Close_2' : stock_price[1].get('Adj_Close'),'High_2' : stock_price[1].get('High'),'Low_2' : stock_price[1].get('Low')
,'VolChg2_1': VolChg2_1,'IndexChg2_1': (float(dji_index[1]) - float(dji_index[0]))
,'Adj_Close_3' : stock_price[2].get('Adj_Close'),'High_3' : stock_price[2].get('High'),'Low_3' : stock_price[2].get('Low')
,'VolChg3_2': VolChg3_2,'IndexChg3_2': (dji_index[2] - dji_index[1])
,'Adj_Close_4' : stock_price[3].get('Adj_Close'),'High_4' : stock_price[3].get('High'),'Low_4' : stock_price[3].get('Low')
,'VolChg4_3': VolChg4_3,'IndexChg4_3': (dji_index[3] - dji_index[2])
,'Adj_Close_5' : stock_price[4].get('Adj_Close'),'High_5' : stock_price[4].get('High'),'Low_5' : stock_price[4].get('Low')
,'VolChg5_4': VolChg5_4,'IndexChg5_4': (dji_index[4] - dji_index[3])
})
j = j+1
示例6: prepare_stock_graph
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [as 别名]
def prepare_stock_graph(symbol, start, end):
stock = Share(symbol)
stringprices = list(pd.DataFrame(stock.get_historical(start, end))["Adj_Close"])
stringdates = list(pd.DataFrame(stock.get_historical(start, end))["Date"])
prices = [float(p) for p in stringprices]
dates = []
for d in stringdates:
year, month, day = d.split("-")
d = datetime.date(int(year), int(month), int(day))
dates.append(d)
return prices, dates
示例7: trailing_stop
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [as 别名]
def trailing_stop(ticker, start, end, percentage=0.15):
ticker = Share(ticker)
while True:
try:
historical = sorted(ticker.get_historical(start, end), key=itemgetter("Date"))
except ValueError as e:
raise e
except YQLQueryError as e:
continue
break
if len(historical) <= 1:
return None
initial_price = float(historical[0]["Adj_Close"])
curr_price = initial_price
stop_price = initial_price * (1 - percentage)
historical = historical[1:]
while len(historical) > 0 and stop_price < curr_price:
curr_price = float(historical[0]["Adj_Close"])
if curr_price > stop_price / (1 - percentage):
stop_price = curr_price * (1 - percentage)
historical = historical[1:]
out = (curr_price - initial_price) / initial_price
return out
示例8: main
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [as 别名]
def main():
start_date = '2007-01-01'
end_date = '2015-08-31'
plotly_name = 'username'
plotly_api_key = 'api-key'
# get_historical is part of the yahoo-finance module
nflx = Share('nflx')
nflx_prices = nflx.get_historical(start_date, end_date)
# how you can just extract the dates only
nflx_dates = [x['Date'] for x in nflx_prices]
# nflx_prices is currently sorted by dates because thats how the module gave them
sorted_by_price = sorted(nflx_prices, key=lambda x: x['Adj_Close'], reverse=True)
# say you wanted multiple stock prices
ticker_symbols = ['hrl', 'tsn', 'gis', 'k']
foods = {}
if do_plot:
plot_stock(plotly_name, plotly_api_key, nflx_prices, 'nflx')
for symbol in ticker_symbols:
foods[symbol] = Share(symbol).get_historical(start_date, end_date)
foods[symbol].sort(key=lambda x: x['Date'])
dates = [x['Date'] for x in foods[symbol]]
prices = [x['Adj_Close'] for x in foods[symbol]]
if do_plot:
add_trace(dates, prices, symbol)
示例9: fetch_data
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [as 别名]
def fetch_data(dt_from, dt_to, sym):
min_dt_from = dt.datetime(2014, 1, 1)
assert(dt_from >= min_dt_from)
r = TStockHistory.find_one(
{'Symbol': sym}, projection={'Date': 1}, sort=[('Date', pymongo.DESCENDING)])
if not r:
fetch_dt_from = min_dt_from
elif r['Date'] < dt_to:
fetch_dt_from = r['Date'] + dt.timedelta(days=1)
if fetch_dt_from > dt_to:
fetch_dt_from = None
else:
fetch_dt_from = None
if fetch_dt_from:
f = '%d-%d-%d' % (
fetch_dt_from.year, fetch_dt_from.month, fetch_dt_from.day)
t = '%d-%d-%d' % (dt_to.year, dt_to.month, dt_to.day)
print('fetch %s from network...' % (sym))
share = Share(sym)
docs = share.get_historical(f, t)
if docs:
for r in docs:
for k in ['Adj_Close', 'High', 'Low', 'Close', 'Volume']:
r[k] = np.float(r[k])
r['Date'] = dateutil.parser.parse(r['Date'])
TStockHistory.insert_many(docs)
data = TStockHistory.find(
{'Symbol': sym, 'Date': {'$gte': dt_from, '$lte': dt_to}})
rs = filter(lambda x: 'placeholder' not in x, [u for u in data])
return rs
示例10: getStockData
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [as 别名]
def getStockData(theTicker):
global startDate
print("Getting Data for ... " + theTicker)
stock = Share(theTicker)
print(startDate)
data = stock.get_historical(startDate, DateNow)
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'])
# newDate = datetime.strptime(date, "%Y-%m-%d")
tmp.append(date)
tmp.append(open)
tmp.append(high)
tmp.append(low)
tmp.append(close)
tmp.append(adjclose)
tmp.append(volume)
givenStock.append(tmp)
return givenStock
示例11: stock_Prices
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [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:valeman,项目名称:Sentiment-Analysis-in-Event-Driven-Stock-Price-Movement-Prediction,代码行数:27,代码来源:crawler_stockPrices.py
示例12: generateData
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [as 别名]
def generateData(self):
global StartingDate
global DataSize
i = datetime.datetime.now()
EndingDate = '%s-%s-%s' % (i.year,i.month,i.day)
stock = Share(Stock_name)
data = stock.get_historical(StartingDate,EndingDate)
file = open('stock_data', 'w')
closes = [c['Close'] for c in data]
opens = [o['Open'] for o in data]
oArray = []
cArray = []
for c in closes:
cArray.append(c)
for o in opens:
oArray.append(o)
for x in range(len(data)-2):
# %Difference, Next Day %Difference, Money Made Holding for a Day
file.write(str((float(cArray[x])-float(oArray[x+1]))/100) + ' ' + str((float(cArray[x+1]) - float(oArray[x+2]))/100) + ' ' + str((float(oArray[x]) - float(oArray[x+1]))) + '\n')
self.dayChange.append((float(cArray[x])-float(oArray[x+1]))/100)
self.nextDayChange.append((float(cArray[x+1]) - float(oArray[x+2]))/100)
self.profit.append(float(oArray[x]) - float(oArray[x+1]))
#Makes sure the population size is
DataSize = len(self.dayChange)
file.close()
示例13: calculateValue
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [as 别名]
def calculateValue(self, date, prices):
value = 0.
date = date.strftime('%Y-%m-%d')
for sym,qty in self.holdings.items():
if sym == 'cash':
value += qty
else:
if sym not in prices:
stock = Share(sym)
# get prices until today
string_today = datetime.date.today().strftime('%Y-%m-%d')
print(string_today)
price_list = stock.get_historical(date, string_today)
# pprint.PrettyPrinter(depth = 6).pprint(price_list)
# Prices is a dictionary of dictionaries; each inner dictionary consists of (date, value) pairs for a ticker
prices[sym] = {item['Date']: float(item['Close']) for item in price_list}
# find price for the date of interest
if date in prices[sym]:
close_price = prices[sym][date]
value += close_price * qty
else:
print(date, sym)
return (None, None)
return (value, prices)
示例14: getStock
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [as 别名]
def getStock(id):
stock = Share(str(id)+'.TW')
today = datetime.date.today()
data = stock.get_historical('2017-04-20', str(today))
# data = stock.get_historical('2017-04-20', '2017-04-20')
# data = stock.get_historical(str(today), str(today))
return data
示例15: getStockData
# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_historical [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