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


Python Share.get_trade_datetime方法代码示例

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


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

示例1: create_files

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

示例2: get_database

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_trade_datetime [as 别名]
def get_database(stock):
    """Return stock database"""
    now = date.today()
    mystock = Share(stock)
    now_price = mystock.get_price() #ราคาปัจจุบัน
    import_time = mystock.get_trade_datetime() #เวลาที่ดึงฐานข้อมูล
    stock_db = mystock.get_historical("2015-01-01", now.isoformat()) #ฐานข้อมูลหุ้นตั้งแต่วันที่ 1 มกราคม 2558 ถึงปัจจุบัน
    return now, stock, now_price, import_time, stock_db
开发者ID:graciaz,项目名称:Stock-Chart,代码行数:10,代码来源:Project+PSIT.py

示例3: main

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

示例4: fetch

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_trade_datetime [as 别名]
def fetch():
    for share in Share.objects.all():
        try:
            sh = YahooShare(share.share)
        except:
            print('exception occurred while fetching stock...')
            continue

        sv, created = ShareValue.objects.get_or_create(share=share, price=sh.get_price(), open=sh.get_open(),
                                                       volume=sh.get_volume(),
                                                       time=datetime.strptime(sh.get_trade_datetime(),
                                                                              '%Y-%m-%d %H:%M:%S %Z%z'))
        if not created:
            print('%s market is closed' % sv.share)
开发者ID:corallus,项目名称:algotrading,代码行数:16,代码来源:utils.py

示例5: process_symbol

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_trade_datetime [as 别名]
def process_symbol(net, symbol):
 settings = load(symbol+'.set')
 if(len(settings)==0):
  return
 yahoo = Share(symbol)
 mp = 2.0*settings['maxc']
 p = float(yahoo.get_price())/mp 
 d = yahoo.get_trade_datetime()
 wd = datetime.datetime.strptime(d[:10],"%Y-%m-%d").weekday()/6.0 
 v = float(yahoo.get_volume())/(2*settings['maxv'])
 ts = UnsupervisedDataSet(3,) 
 ts.addSample((wd,p,v),)
 ret = net.activate([wd,p,v])
 print "IK, K, V ", ret
开发者ID:ZwenAusZwota,项目名称:aktien,代码行数:16,代码来源:process.py

示例6: get_trade_date_series

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_trade_datetime [as 别名]
def get_trade_date_series(country):
    # get the data of 000001 by tushare
    if country == "CN":
        # now = datetime.datetime.today()
        # before = now - datetime.timedelta(days=30)
        # start = before.strftime("%Y-%m-%d")
        # end = now.strftime("%Y-%m-%d")
        # df = ts.get_hist_data(code='sh', start=start, end=end)
        # date_cn = datetime.datetime.strptime(df.index.values[0],"%Y-%m-%d") + datetime.timedelta(hours=15, minutes=5)
        df = ts.get_realtime_quotes("sh")
        date_cn = datetime.datetime.strptime(df["date"].values[0].encode("utf8"), "%Y-%m-%d") + datetime.timedelta(hours=9, minutes=25)
        return date_cn

    elif country == "US":
        yahoo = Share('QQQ')
        time_str = yahoo.get_trade_datetime()
        date_us = datetime.datetime.strptime(time_str[:10], "%Y-%m-%d") + datetime.timedelta(hours=28, minutes=5)
        return date_us
开发者ID:frankyzhou,项目名称:easytrader,代码行数:20,代码来源:util.py

示例7: inter_minute_data_get

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_trade_datetime [as 别名]
def inter_minute_data_get(Ticker, Market, Target_File):
    start, end = get_market_times(Market)
    while True:
        prices = open(Target_File, "a")
        # concerning this "open" "close" within the loop; this means that regardless of how the program exits we still
        # write to the file (as opposed to what we were doing which was saving only temporarily
        t1 = datetime.datetime.utcnow().time()
        if not start <= t1 <= end:
            # This finds the current time and waits until the market should next open (does not account for weekends)
            p = datetime.datetime.utcnow()
            y = p.replace(hour=start.hour, minute=start.minute, second=start.second)
            delta_t = y - p
            if "-1" in str(delta_t):
                # in case of the "start" time being before the current time we shift to the next day
                y = p.replace(day=p.day + 1, hour=start.hour, minute=start.minute, second=start.second)
                delta_t = y - p
            h, m, s = str(delta_t).split(":")
            new_delta = datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds()
            time.sleep(new_delta)
        prices.write("Time: {}Ticker: {} Price: {} \n".format(Share.get_trade_datetime(x).strip("UTC+0000"), Ticker,
                                                              Share.get_price(x)))
        time.sleep(3)
        prices.close()
开发者ID:TheLateOne,项目名称:TryingGithub,代码行数:25,代码来源:first_stocks_program.py

示例8: Share

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

yahoo = Share('SPY')
print yahoo.get_open()
print yahoo.get_price()
print yahoo.get_trade_datetime()
yahoo.refresh()

spyprice = yahoo.get_historical('2000-01-01', '2016-04-25')
pprint(yahoo.get_historical('2014-04-25', '2014-04-29'))
开发者ID:jingriver,项目名称:testPython,代码行数:13,代码来源:testYahoo.py

示例9: Share

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_trade_datetime [as 别名]
from yahoo_finance import Share
yahoo = Share("YHOO")
print(yahoo.get_open())
print(yahoo.get_trade_datetime())
yahoo.refresh()
开发者ID:anuragdutt,项目名称:python-basics,代码行数:7,代码来源:stock-data-download.py

示例10: range

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

from yahoo_finance import Share

from Parser.models import EtfInfo, EtfData, StockInfo, StockDetail



etfResult = StockInfo.objects.values('ticker', 'name')

#for etfIdx in range(0, len(etfResult)) :
tickerStr = etfResult[0]['ticker']

share = Share(tickerStr)

dateStr = share.get_trade_datetime()[0:11].replace('-','')
ma_200Str = convert(share.get_200day_moving_avg())
ma_50Str = convert(share.get_50day_moving_avg())
book_valueStr = convert(share.get_book_value())
volume_avgStr = convert(share.get_avg_daily_volume())
ebitdaStr = convert(share.get_ebitda())
dividend_yieldStr = convert(share.get_dividend_yield())
market_capStr = convert(share.get_market_cap())
year_highStr = convert(share.get_year_high())
year_lowStr = convert(share.get_year_low())

print tickerStr, dateStr, ma_200Str, ma_50Str, book_valueStr, volume_avgStr, ebitdaStr, dividend_yieldStr, market_capStr, year_highStr, year_lowStr


# print share.get_change()
# print share.get_days_high()
开发者ID:quantosauros,项目名称:MAProject,代码行数:33,代码来源:testYahooApi.py

示例11: getHistoricalData

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

示例12: current_time_stock

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_trade_datetime [as 别名]
def current_time_stock(name):
 stock = Share('{}'.format(name))
 return stock.get_trade_datetime()
开发者ID:Kitae360,项目名称:Stock_Game,代码行数:5,代码来源:stock_info.py

示例13: Share

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_trade_datetime [as 别名]
# find the date of yesterday
now = datetime.datetime.now()

# connect the sqlite
conn = lite.connect('StockHistory.db')
cursor = conn.cursor()
# every time empty data
cursor.execute('DELETE FROM TrueTimeValue')
conn.commit()
# get the records ranging from max date in DB to yesterday
BeginTime = now.replace(hour=9, minute=0, second=0, microsecond=0)
EndTime = now.replace(hour=16, minute=0, second=0, microsecond=0)
# LocalTime = T.strftime('%Y-%m-%d ',T.localtime(T.time()))
while now > BeginTime and now < EndTime:
    StockList = ['YHOO', 'GOOG', 'AAPL', 'TWTR', 'AMZN']
    for stock in StockList:
        Symbol = stock
        Company = Share(stock)
        Price = Company.get_price()
        Time = Company.get_trade_datetime()
        Volume = Company.get_volume()
        purchases = (Symbol, Price, Time, Volume)
        cursor.execute('INSERT INTO TrueTimeValue VALUES (?,?,?,?)', purchases)
        conn.commit()
        Company.refresh()
    cursor.execute('SELECT * FROM TrueTimeValue')
    print(cursor.fetchall())
    T.sleep(60)
cursor.close()
conn.close()
开发者ID:AlexWufan,项目名称:StockPrediction,代码行数:32,代码来源:realtimestock.py

示例14: Share

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_trade_datetime [as 别名]
        TEXT,
    )
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_pwd)
        server.sendmail(FROM, TO, message)
        server.close()
        print "successfully sent the mail"
    except:
        print "failed to send mail"


"""
Function:
	main
"""
# pull info for a well known ticker to establish date of pulled stock data
seedDate = Share("SPY")
currentTradeDate = seedDate.get_trade_datetime()[:10]
currentRunDate = date.today().strftime("%Y-%m-%d")

# only run the script/code if the current date matches the current trade date from the above well known ticker (SPY).
# this allows us to ensure multiple runs of the script does not produce redundant data
if currentTradeDate == currentRunDate:
    with open("tickers.csv") as f:
        for line in f:
            ticker = line.rstrip("\n")
            calculate(ticker)
开发者ID:RoundQube,项目名称:ticker,代码行数:32,代码来源:stocks.py

示例15: yahoo_get_price

# 需要导入模块: from yahoo_finance import Share [as 别名]
# 或者: from yahoo_finance.Share import get_trade_datetime [as 别名]
def yahoo_get_price(symbol):
 yahoo = Share(symbol)
 price = yahoo.get_price()
 trade_date = yahoo.get_trade_datetime()
 dict={"p":price,"d":trade_date}
 return dict
开发者ID:ZwenAusZwota,项目名称:aktien,代码行数:8,代码来源:stock_functions.py


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