def process_stock_data(date_1, date_2, stock_name): nasdaq = Share('^IXIC') yahoo = Share(stock_name) nasdaq.refresh() yahoo.refresh() index_data = nasdaq.get_historical(date_1, date_2) data = yahoo.get_historical(date_1, date_2) # 0 Volume # 1 Symbol # 2 Adj Close # 3 High # 4 Low # 5 Date # 6 Close # 7 Open close_prices = [] #Set up as two dimensional data for day in data: close_price = [] close_price.append(float(day.values()[7])) close_prices.insert(0, close_price) return close_prices
class ShareObj(object): def __init__(self, ID): self.id = ID self.share = Share(self.id) self.refresh def getPrice(self): return self.share.get_price() def getOpenPrice(self): return self.share.get_open() def getChange(self): if(self.share.get_percent_change() == None): return 0 else: percent = (self.share.get_percent_change()[:-1]) return float(percent) def getChangeFormatted(self): self.share.get_percent_change() def getID(self): return self.id def refresh(self): self.share.refresh() def getHistorical(self,date1, date2): return self.share.get_historical(date1,date2) def getCalculatedChange(self, open, close): return ((close - open)/open)*100
def stock_data(start, end,companies): ''' Function: Parameters: start date, end date, and a list of companies names ''' raw_data = { 'High': [], 'Low': [], 'Open': [], 'Close': [], 'Volume': [], 'Date': [] } for key,value in companies.items(): company = Share(key) company.refresh() data = company.get_historical(start,end) for item in data: raw_data['High'].append(float(item['High'])) raw_data['Low'].append(float(item['Low'])) raw_data['Open'].append(float(item['Open'])) raw_data['Close'].append(float(item['Close'])) raw_data['Volume'].append(int(item['Volume'])) raw_data['Date'].append(item['Date']) return raw_data
class stocktw(object): CaptialCashYear = 3 def __init__(self, stockNum): self.stockNum = str(stockNum) self.share = Share(self.stockNum + ".tw") self.share.refresh() def getPrice(self): price = 0 try: price = self.share.get_price() except: print("get price error:" + self.stockNum) return price def isIncrease(self, x, key=lambda x: x): return all([key(x[i]) <= key(x[i + 1]) for i in self.CaptialCashYear]) def isCaptialCashDecrease(self): url = str('http://easyfun.concords.com.tw/z/zc/zcb/zcb_%s.djhtm' % self.stockNum) soup = BeautifulSoup(requests.get(url).text, 'lxml') table = pd.read_html(str(soup.find_all('table')[0])) df = table[2] df = df.ix[1:, :2] df.columns = df.iloc[0] df = df[1:] ds = df["比重"].str[:-1].apply(pd.to_numeric) decreasing = lambda L: all(x <= y for x, y in zip(L, L[1:])) check = decreasing(ds[:self.CaptialCashYear]) return check
def get_stock_info(name, abbr): x = Share(abbr) x.refresh() price = x.get_price() change = x.get_percent_change() print(change[0] == '-') if change[0] == '-': color = '#B22222' else: color = '#006400' url = "https://news.google.com/news?q={0}&output=rss".format(name) feed = feedparser.parse(url) entries = [] i = 0 while i < len(feed.entries) and i < 7: title = feed.entries[i]['title'] index = title.index('-') author = title[index + 2:] title = title[:index - 1] link = feed.entries[i]['link'] entries.append({'title': title, 'author': author, 'link': link}) i += 1 return { 'price': price, 'change': change, 'color': color, 'entries': entries }
def loadKeyStatistics (cls, companyID = 'A'): ''' dataset df= pd.DataFrame(columns=['marketCapital','bookValue','ebitda','dividentShare','DividentYield','earningShare', 'BookPrice','SalesPrice','earningsGrowth','earningsRatio', 'symbol', 'date']) ''' yahoo = Share(companyID) yahoo.refresh() try: a = re.search('[a-zA-Z]+', yahoo.get_market_cap()) b = re.search('[a-zA-Z]+', yahoo.get_ebitda()) if a.group(0) is not None: p = re.split('[a-zA-Z]+', yahoo.get_market_cap()) if a.group(0) in 'B': marketCap = float(p[0]) * 10 ** 9 elif a.group(0) in 'M': marketCap = float(p[0]) * 10 ** 6 else: marketCap = -1 print ('Market cap: ' + yahoo.get_market_cap()) else: marketCap = yahoo.get_market_cap() if b.group(0) is not None: p = re.split('[a-zA-Z]+', yahoo.get_ebitda()) if b.group(0) in 'B': ebitda = float(p[0]) * 10 ** 9 elif b.group(0) in 'M': ebitda = float(p[0]) * 10 ** 6 else: ebitda = -1 print ('Ebitda: ' +yahoo.get_ebitda()) else: ebitda = yahoo.get_ebitda() except (TypeError, AttributeError): print ('Missing :' + companyID) e = sys.exc_info()[0] print( "<p>Error: %s</p>" % e ) ebitda = -1.0 marketCap = -1.0 try: company = LoadYahooFinance(symbol = companyID, marketCap = marketCap, bookValue = float(yahoo.get_book_value()), ebitda = ebitda, dividentShare = float(yahoo.get_dividend_share()), dividentYield = float(yahoo.get_dividend_yield()), earningShare = float(yahoo.get_earnings_share()), bookPrice = float(yahoo.get_price_book()), salesPrice = float(yahoo.get_price_sales()), earningsGrowth = float(yahoo.get_price_earnings_growth_ratio()), earningRatio = float(yahoo.get_price_earnings_ratio())) return company except TypeError: print ('Missing :' + companyID) e = sys.exc_info()[0] print( "<p>Error: %s</p>" % e )
def main(): ticker = str(raw_input("Stock Ticker: ")) company = Share(ticker) company.refresh() print company.get_name() print "Current Price: ", company.get_price()
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--------------------------------------")
def stock(message): ticker = Share(message) ticker.refresh() quote = ticker.get_price() if quote is None: resp = str(message) + " is not a valid ticker symbol" else: change = ticker.get_change() resp = message + ": " + quote + " " + change __send_response(resp, icon_money) quote = ""
def getAllStockData(ticker): '''Get a few random tickers.''' stock = Share(ticker) stock.refresh() data = { 'name': stock.get_name(), 'price': stock.get_price(), 'change': stock.get_change(), 'volume': stock.get_volume(), 'prev_close': stock.get_prev_close(), 'open': stock.get_open(), 'avg_daily_volume': stock.get_avg_daily_volume(), 'stock_exchange': stock.get_stock_exchange, 'market_cap': stock.get_market_cap(), 'book_value': stock.get_book_value(), 'ebitda': stock.get_ebitda(), 'dividend_share': stock.get_dividend_share(), 'dividend_yield': stock.get_dividend_yield(), 'earnings_share': stock.get_earnings_share(), 'days_high': stock.get_days_high(), 'days_low': stock.get_days_low(), 'year_high': stock.get_year_high(), 'year_low': stock.get_year_low(), '50day_moving_avg': stock.get_50day_moving_avg(), '200day_moving_avg': stock.get_200day_moving_avg(), 'price_earnings_ratio': stock.get_price_earnings_ratio(), 'price_earnings_growth_ratio': stock.get_price_earnings_growth_ratio(), 'get_price_sales': stock.get_price_sales(), 'get_price_book': stock.get_price_book(), 'get_short_ratio': stock.get_short_ratio(), 'trade_datetime': stock.get_trade_datetime(), 'percent_change_from_year_high': stock.get_percent_change_from_year_high(), 'percent_change_from_year_low': stock.get_percent_change_from_year_low(), 'change_from_year_low': stock.get_change_from_year_low(), 'change_from_year_high': stock.get_change_from_year_high(), 'percent_change_from_200_day_moving_average': stock.get_percent_change_from_200_day_moving_average(), 'change_from_200_day_moving_average': stock.get_change_from_200_day_moving_average(), 'percent_change_from_50_day_moving_average': stock.get_percent_change_from_50_day_moving_average(), 'change_from_50_day_moving_average': stock.get_change_from_50_day_moving_average(), 'EPS_estimate_next_quarter': stock.get_EPS_estimate_next_quarter(), 'EPS_estimate_next_year': stock.get_EPS_estimate_next_year(), 'ex_dividend_date': stock.get_ex_dividend_date(), 'EPS_estimate_current_year': stock.get_EPS_estimate_current_year(), 'price_EPS_estimate_next_year': stock.get_price_EPS_estimate_next_year(), 'price_EPS_estimate_current_year': stock.get_price_EPS_estimate_current_year(), 'one_yr_target_price': stock.get_one_yr_target_price(), 'change_percent_change': stock.get_change_percent_change(), 'divended_pay_date': stock.get_dividend_pay_date(), 'currency': stock.get_currency(), 'last_trade_with_time': stock.get_last_trade_with_time(), 'days_range': stock.get_days_range(), 'years_range': stock.get_year_range() } return data
def get(self, ticker): quote = Share(ticker.upper()) quote.refresh() result = { 'quote': [{ 'ticker': ticker.upper(), 'price': quote.get_price(), 'trade_dt': quote.get_trade_datetime() }] } return jsonify(result)
def scraping_data(self): print('Scraping data...') yahoo = Share(self.ticker) yahoo.refresh() print(yahoo.get_name()) self.total_data = yahoo.get_historical('2017-07-11', '2017-07-12') for data in self.total_data: row = [data['Date'], data['Adj_Close']] self.writer.writerow(row) self.csv_file.close() print('\nAll done successfully!!!')
def getCurrent(ticker): """ Return the most recent stock data through yahoo_finance. """ stock = Share(ticker) stock.refresh() #refresh the query open_ = stock.get_open() volume = stock.get_volume() high = stock.get_days_high() price = stock.get_price() time = stock.get_trade_datetime() low = stock.get_days_low() return (open_, high, volume, price, time, low)
def sell(symbol,number_to_sell): global bankroll global stocks_owned stock = Share(symbol) for key, value in stocks_owned.items(): if(key == symbol): if(stocks_owned[symbol]>number_to_sell): stocks_owned[key] -= number_to_sell stock.refresh() #If it runs like crap its this line stock_value = float(stock.get_price())*float(number_to_sell) bankroll = bankroll+stock_value break else: print("You don't own enough of "+symbol+" to sell")
def get_price_YAHOO(ticker): #for ticker in list_of_symbols: try: from yahoo_finance import Share yahoo = Share(ticker) yahoo.refresh() price_finance = yahoo.get_price() print("IN->", ticker) print("Open -> ", yahoo.get_open()) print("Current Price -> ", yahoo.get_price()) print("Ave Volume -> ", yahoo.get_avg_daily_volume()) print("Volume -> ", yahoo.get_volume()) print("Time -> ", yahoo.get_trade_datetime()) return float(price_finance) except: get_price_YAHOO(ticker)
def get_close_price(start,end,companies): ''' Function: Given the parameters, the closing and date price is stored in a dictionary and returned Parameters: start date, end date, and a list of companies ''' close_price = {'Close': [], 'Date': []} for symbol in companies.keys(): company = Share(symbol) company.refresh() data = company.get_historical(start,end) for item in data: close_price['Close'].append(float(item['Close'])) close_price['Date'].append(item['Date']) return close_price
def logPrice(self): prices = {} try: price = Share(name) type = "sh" except: price = Currency(name) type = "cu" outfile = open(str(name + '_pricelog.json'), 'a') starttime = time() if (type == 'sh'): price.refresh() dumps({name: {int(time() - starttime): price.get_price()}}) if (type == 'cu'): price.refresh() dumps({name: {int(time() - starttime): price.get_price()}})
def stalk(stock): bad = True share = Share(stock["symbol"]) price = float(share.get_price()) while bad: # check if in range if price > stock["price"] - stock["range"] and price < stock["price"] + stock["range"]: # send a yo data = {"username": stock["username"], "api_token": os.environ.get("API_TOKEN")} res = requests.post("http://api.justyo.co/yo/", params=data) print res bad = False else: share.refresh()
def get_current_shares(self): """Gets current shares, compares it to initial, finds difference. Returns for output to handle""" company_dict = tf.open_json() for company in company_dict: try: yahoo = Share(company_dict[company]["Symbol"]) yahoo.refresh() share = yahoo.get_price() company_dict[company]["Current-share-price"] = float(share) company_dict[company]["Share-price-list"].append(float(share)) except Exception: pass tf.write_to_json(company_dict)
def get_one_stock(thread_id, tickers, good): #print(thread_id, len(tickers)) for ticker in tickers: try: stock = Share(ticker) stock.refresh() my_data = stock.data_set #for x in my_data.keys(): # print(x) #print(ticker, my_data) tmp = {} tmp[ticker]=my_data if is_good(my_data): #print('!!!!!!', thread_id, tmp) good.append(tmp) except Exception as e: #pass print("Exception in get_one_stock:" +str(e))
def get_current_shares(): """Gets current shares, compares it to initial, finds difference. Returns for output to handle""" company_dict = utils.open_json(MONITOR) for company in company_dict: try: yahoo = Share(company_dict[company]["Symbol"]) yahoo.refresh() share = yahoo.get_price() company_dict[company]["Current-share-price"] = float(share) company_dict[company]["Share-price-list"].append(float(share)) except ValueError: # yahoo.get_price() will return None if an error occurs print("Could not add to the Current share/Share price list") utils.write_to_json(MONITOR, company_dict)
class YahooFinanceData: """Get data from Yahoo Finance.""" def __init__(self, symbol): """Initialize the data object.""" from yahoo_finance import Share self._symbol = symbol self.state = None self.price_change = None self.price_open = None self.prev_close = None self.stock = Share(self._symbol) def update(self): """Get the latest data and updates the states.""" self.stock.refresh() self.state = self.stock.get_price() self.price_change = self.stock.get_change() self.price_open = self.stock.get_open() self.prev_close = self.stock.get_prev_close()
def buy(symbol,number_to_buy): global bankroll global stocks_owned already_owned = False stock = Share(symbol) stock.refresh() #If it runs like crap its this line stock_value = float(stock.get_price())*float(number_to_buy) if(stock_value<bankroll): #can buy stocks if you have $ bankroll = bankroll-stock_value for key, value in stocks_owned.items(): if(key == symbol): stocks_owned[key] += number_to_buy already_owned = True if(already_owned != True): stocks_owned[symbol] = number_to_buy else: print("You don't have the dough to buy a "+str(number_to_buy)+ " of "+symbol)
class YahooFinanceData(object): """Get data from Yahoo Finance.""" def __init__(self, name, symbol): """Initialize the data object.""" from yahoo_finance import Share self._name = name self._symbol = symbol self.state = None self.price_change = None self.price_open = None self.prev_close = None self.stock = Share(symbol) @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data and updates the states.""" self.stock.refresh() self.state = self.stock.get_price() self.price_change = self.stock.get_change() self.price_open = self.stock.get_open() self.prev_close = self.stock.get_prev_close()
from yahoo_finance import Share f = open('portfolio.txt', 'r') lines = [e[:-1].split() for e in f.readlines()] purchase_date = lines[0][0] shares = dict() for [ticker, amt] in lines[1:]: shares[ticker] = int(amt) purchase_prices = dict() current_prices = dict() for e in shares: eobj = Share(e) eobj.refresh() ehist = eobj.get_historical(purchase_date, purchase_date) purchase_prices[e] = (float)(ehist[0]['Open']) current_prices[e] = (float)(eobj.get_price()) print 'AT PURCHASE (%s):' % purchase_date total_value_at_purchase = 0.0 for e in shares: #purchase price per share ppps = purchase_prices[e] value_at_purchase = shares[e] * ppps total_value_at_purchase += value_at_purchase print '%4s: %d @ $%.3f = $%.4f' % (e, shares[e], ppps, value_at_purchase) print 'Total stock value: $%.4f' % total_value_at_purchase today_date = Share('YHOO').get_trade_datetime() print '\nAT PRESENT (%s):' % (today_date) total_stock_value = 0.0
yahoo_prices = [] google_prices = [] ibm_prices = [] microsoft_prices = [] oracle_prices = [] yahoo = Share('YHOO') google = Share('GOOGL') ibm = Share('IBM') microsoft = Share('MSFT') oracle = Share('ORCL') for i in range(0,30): yahoo.refresh() google.refresh() ibm.refresh() microsoft.refresh() oracle.refresh() yahoo_prices.append(yahoo.get_price()) google_prices.append(google.get_price()) ibm_prices.append(ibm.get_price()) microsoft_prices.append(microsoft.get_price()) oracle_prices.append(oracle.get_price()) time.sleep(60) print 'yahoo', for x in yahoo_prices: print ' ', print x,
def Ian(): #function that loops (like a main function) run = True #runnning parameter, failsafe if i missed a break somewhere for i in range(50): #clean things up a bit print '' print row stc = raw_input('Stock Abrieviation (ex= YHOO): ') #which stock to examine print row for i in range(50): #clean things up a bit print '' print row o = raw_input('Daily, Weekly, Monthly or Yearly (D, W, M, Y): ') #chosing timescale print row for i in range(50): print '' print row stdate = raw_input('Start date (YYYY-MM-DD) : ') #start date of data set, using yahoo_finance module syntax print row for i in range(50): print '' print row endate = raw_input('End date (YYYY-MM-DD) : ') #end date of data set, using yahoo_finance module syntax print row for i in range(50): print '' print row stock = Share(stc) #declaring the stock "Share" is imported from yahoo_finance stock.refresh() print 'Gathering data, (about a second per month of data)' print 'Building Data Structure' List = stock.get_historical(stdate, endate) #actual data gathering val = times[o] l = len(List)/val v = [0]*l for i in range(l): #reformats the data into a list called v v[i] = float(List[i*val]['Open']) v = v[::-1] while run == True: #main while loop tdate = raw_input('Algorithm value for what day?: ') #chosen date to examine momentum on if tdate == 'end': #allows user to break code, useful for diagnostics run = False break """ HELP ME: i cant find a better way to measure the number of days the stock martket is open between start date and chosen date, without making a whole new list and measuring it """ print 'Finding number of market days' xList = stock.get_historical(stdate, tdate) x = len(xList)/val print '' for i in range(50): print '' print tdate print 'ALGORITHM OUTPUT:' oval = SQT(x, v, l, val) #actual algorith usage print oval if Monte != 'y' or 'Y' or 'Yes' or 'yes': #for some reason this needed to be here pass elif Monte == 'y' or 'Y' or 'Yes' or 'yes': #runnng the monte carlo measurements newV = v oList = [] for i in range(n): #compares output against outputs of the same data set, but in a random order newV = shuffle(v) shuffle(newV) oList.append(SQT(l-1, newV, l, val)) std = np.std(oList) mu = np.average(oList) zscore = (oval - mu)/std tot = 0 for i in range(l): if oval>oList[i]: tot += 1 sampleP = float(tot)/l print 'Sample percent lower than original output' #You wan this to be low for a negative output, or high for a positive output print sampleP #uses sample (of 30) data see globaly defined 'n' to change this number, defined at top of page, 30 is generally safe print 'Population percent lower than original based on 1-sample z-test' if m == 'z': print norm.cdf(zscore) #some statistics stuff, you probly dont care, unless you wanna chack my stats work if m == 't': print t.cdf(zscore,n+1) #if you chose t distributions this one happens, t is probly the right choice given the circumstances print'' print 'enter "end" on the next prompt to quit, and try a new share' print row
def RealTime(stocks, count): cnx = mysql.connector.connect(user='******', password='******', host='127.0.0.1', database='DBtest') cursor = cnx.cursor() waitsec = 60 waitmessage = "Wait 1 minute for the next real-time values..." #The following lines avoid running the program multiple times if the market it's closed now = datetime.datetime.utcnow() # Check the current time today14 = now.replace(hour=14, minute=25, second=0, microsecond=0) today21 = now.replace(hour=21, minute=5, second=0, microsecond=0) if (now >= today21 or today14 >= now): count = 1 waitsec = 1 waitmessage = "" print( "The market opens at 14:30 UTC and closses at 21:00 UTC, \n***Data will be retrieved only once." ) print("Current datetime " + str(now)) while 0 < count: for i in stocks: print("Stock of " + i) stock = Share(i) stock.refresh() price = stock.get_price() stime = stock.get_trade_datetime() # Needed to fix the format the date is retrieved from Yahoo Finance timefixed = stime[:-8] volume = stock.get_volume() print("Price: " + price + " Time: " + timefixed + " Volume: " + volume) # Don't forget to use the config file to avoid writing the password on the source add_realtime = ("INSERT INTO realtime " "(tricker, price, time, volume) " "VALUES (%s, %s, %s, %s)") data_realtime = (i, price, timefixed, volume) try: cursor.execute(add_realtime, data_realtime) cnx.commit() # Make sure data is committed to the database except mysql.connector.IntegrityError as err: #print(err) # Ussually a Duplicate value error pass print("Database sucessfuly udpated. " + waitmessage) time.sleep(waitsec) count -= 1 cursor.close() cnx.close()
#print(stocks) row_title = "\nticker price price% volume volume% open day_low day_high year_low year_high market_cap P/E avg_50" +\ " avg_200" i = 0 for ticker in stocks: sys.exit() try: if (i % 10) == 0: print(row_title) ticker = ticker.rstrip() 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)+ \
#print(stocks) row_title = "\nticker price price% volume volume% open day_low day_high year_low year_high market_cap P/E avg_50" +\ " avg_200" i=0 for ticker in stocks: sys.exit() try: if (i%10) == 0: print(row_title) ticker = ticker.rstrip() 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)
def print_menu(menuid, errorid): global selected_Ticker namesTicker = ["Stocks", "Exchanges", "Catagory", "Number Selection"] if selected_Ticker is not None: print("Selected:\t"+selected_Ticker.name) print("Type:\t\t"+namesTicker[selected_Ticker.typeof]) if selected_Ticker.typeof == 0: stock = Share(selected_Ticker.name) stock.refresh() print(stock.get_info()) print(stock.get_price()) print(stock.get_change()) print(stock.get_volume()) print("\n\n") if menuid == 0: print("------Menu------") print(" (e) exit") print(" (l) list") print(" (s) stats") error(errorid) elif menuid == 1: print("------Stats Menu------") print(" (a) all") print(" (u) uniques") print(" (b) back") if selected_Ticker is not None: print(" (r) run data collector") print(" (c) clear") error(errorid) elif menuid == 2: print("------All Data Menu------") print(" (e) exchanges") print(" (c) catagories") print(" (n) catagory Number") print(" (b) back") error(errorid) elif menuid == 3: print("------Unique Menu------") print(" (s) stock") print(" (e) exchange") print(" (c) catagories") print(" (n) catagory Number") print(" (b) back") error(errorid) elif menuid == 4: print("------Stock Tickers Selection------") exchanges_display(0) error(errorid) elif menuid == 5: print("------Exchanges Selection------") exchanges_display(1) error(errorid) elif menuid == 6: print("------Catagory Selection------") exchanges_display(2) error(errorid) elif menuid == 7: print("------Number Catagory Selection------") exchanges_display(3) error(errorid)
j = 2 for i in Stocks: p = get_price_RT(i) add_to_csv_RT(documents=i + '_rtdata.csv', df=p) if j == 2 and i == Stocks[0]: p.to_sql(name='realtimedata', con=engine, if_exists='replace', index=False) else: p.to_sql(name='realtimedata', con=engine, if_exists='append', index=False) time.sleep(60) google.refresh() nvidia.refresh() yahoo.refresh() amazon.refresh() apple.refresh() microsoft.refresh() BoA.refresh() nike.refresh() netflix.refresh() FB.refresh() except KeyboardInterrupt: print('User Asked to Quit') raise SystemExit() finally: cnx.close() # close the connector
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'))
j = 1 else: if j == 1: j = 2 for i in Stocks: p = get_price_RT(i) add_to_csv_RT(documents=i + '_rtdata.csv', df=p) if j == 2 and i == Stocks[0]: p.to_sql(name='realtimedata', con=engine, if_exists='replace', index=False) else: p.to_sql(name='realtimedata', con=engine, if_exists='append', index=False) time.sleep(60) google.refresh() nvidia.refresh() yahoo.refresh() amazon.refresh() apple.refresh() except KeyboardInterrupt: print('User Asked to Quit') raise SystemExit() finally: cnx.close() # close the connector
def Ian(): #function that loops (like a main function) run = True #runnning parameter, failsafe if i missed a break somewhere for i in range(50): #clean things up a bit print '' print row stc = raw_input( 'Stock Abrieviation (ex= YHOO): ') #which stock to examine print row for i in range(50): #clean things up a bit print '' print row o = raw_input('Daily, Weekly, Monthly or Yearly (D, W, M, Y): ' ) #chosing timescale print row for i in range(50): print '' print row stdate = raw_input( 'Start date (YYYY-MM-DD) : ' ) #start date of data set, using yahoo_finance module syntax print row for i in range(50): print '' print row endate = raw_input( 'End date (YYYY-MM-DD) : ' ) #end date of data set, using yahoo_finance module syntax print row for i in range(50): print '' print row stock = Share( stc) #declaring the stock "Share" is imported from yahoo_finance stock.refresh() print 'Gathering data, (about a second per month of data)' print 'Building Data Structure' List = stock.get_historical(stdate, endate) #actual data gathering val = times[o] l = len(List) / val v = [0] * l for i in range(l): #reformats the data into a list called v v[i] = float(List[i * val]['Open']) v = v[::-1] while run == True: #main while loop tdate = raw_input('Algorithm value for what day?: ' ) #chosen date to examine momentum on if tdate == 'end': #allows user to break code, useful for diagnostics run = False break """ HELP ME: i cant find a better way to measure the number of days the stock martket is open between start date and chosen date, without making a whole new list and measuring it """ print 'Finding number of market days' xList = stock.get_historical(stdate, tdate) x = len(xList) / val print '' for i in range(50): print '' print tdate print 'ALGORITHM OUTPUT:' oval = SQT(x, v, l, val) #actual algorith usage print oval if Monte != 'y' or 'Y' or 'Yes' or 'yes': #for some reason this needed to be here pass elif Monte == 'y' or 'Y' or 'Yes' or 'yes': #runnng the monte carlo measurements newV = v oList = [] for i in range( n ): #compares output against outputs of the same data set, but in a random order newV = shuffle(v) shuffle(newV) oList.append(SQT(l - 1, newV, l, val)) std = np.std(oList) mu = np.average(oList) zscore = (oval - mu) / std tot = 0 for i in range(l): if oval > oList[i]: tot += 1 sampleP = float(tot) / l print 'Sample percent lower than original output' #You wan this to be low for a negative output, or high for a positive output print sampleP #uses sample (of 30) data see globaly defined 'n' to change this number, defined at top of page, 30 is generally safe print 'Population percent lower than original based on 1-sample z-test' if m == 'z': print norm.cdf( zscore ) #some statistics stuff, you probly dont care, unless you wanna chack my stats work if m == 't': print t.cdf( zscore, n + 1 ) #if you chose t distributions this one happens, t is probly the right choice given the circumstances print '' print 'enter "end" on the next prompt to quit, and try a new share' print row
# 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()
from yahoo_finance import Share inp = open('input.txt', 'r') out = open('output.txt', 'w') for line in inp: temp = Share(line) temp.refresh() out.write(line.rstrip("\n") + "," + temp.get_price() + "," + temp.get_change() + "\n") #FORMAT: Symbol, last closing price, last change temp = Share('FUSVX') print(temp.get_stock_exchange())
import sqlite3 from yahoo_finance import Share f = open('tick.txt','r') con=sqlite3.connect('stocks.db') c = con.cursor() ##historical data using yahoo # sh = ['FB', 'INTC'] sh = f.readlines() for tick in sh: print(tick) equity = Share(tick) equity.refresh() lst = equity.get_historical('2000-04-25', '2015-09-29') for x in lst: print(type(x)) close = x.get('Adj_Close') date = x.get('Date') hi = x.get('High') lo = x.get('Low') tck = x.get('Symbol') vol = x.get('Vol') opn = x.get('Open') c.execute("INSERT INTO price VALUES (?,?,?,?,?,?);",(tck,date,opn,hi,lo,close)) con.commit() con.close() ##real time data using google
tweetCount += len(new_tweets) print("Downloaded {0} tweets".format(tweetCount)) max_id = new_tweets[-1].id except tweepy.TweepError as e: # Just exit if any error print("some error : " + str(e)) break print ("Downloaded {0} tweets, Saved to {1}".format(tweetCount, fName)) tweetArr[x] = tweetCount from yahoo_finance import Share Twitter = Share('TSLA') print Twitter.get_price() Twitter.refresh() print Twitter.get_price() print Twitter.get_days_range() from pprint import pprint pprint(Twitter.get_historical('2017-03-15', '2017-03-22')) Closes = [li['Close'] for li in Twitter.get_historical('2016-09-20', '2016-09-27')] print Closes years = [2012, 2013, 2014, 2015, 2016,2017] plt.figure(1) plt.title('Daily Closing Stock Price') plt.xlabel('Day') plt.ylabel('Closing Price ($)')
import time from yahoo_finance import Share import sys # Collect 30 mins of Finance data on 5 companies, one value per minute share = Share(sys.argv[1]) for i in range(30): share.refresh(); print share.get_price() time.sleep(60) # RUN SCRIPT IN PYTHON # python yahoo.py LNKD> linkedin.txt # python yahoo.py FB> facebook.txt # python yahoo.py IBM> ibm.txt # python yahoo.py YHOO> yahoo.txt # python yahoo.py NYT> nyt.txt
# finance.py ## From Google Finance from googlefinance import getQuotes import json print json.dumps(getQuotes('AAPL'), indent=2) print json.dumps(getQuotes(['AAPL', 'GOOG']), indent=4) ## From Yahoo Finance from yahoo_finance import Share yahoo = Share('YHOO') print yahoo.get_open() print yahoo.get_price() print yahoo.get_trade_datetime() yahoo.refresh() print yahoo.get_price() print yahoo.get_trade_datetime() print yahoo.get_historical('2014-04-25', '2014-04-29') from pprint import pprint pprint(yahoo.get_historical('2014-04-25', '2014-04-29')) pprint(yahoo.get_info()) # get_price() # get_change() # get_volume() # get_prev_close() # get_open() # get_avg_daily_volume()
filename3 = "microsoft.txt" filename4 = "apple.txt" filename5 = "amazon.txt" while True: with open(filename1,"a") as f: f.write(yahoo.get_price()) f.write(" ") with open(filename2,"a") as f: f.write(google.get_price()) f.write(" ") with open(filename3,"a") as f: f.write(microsoft.get_price()) f.write(" ") with open(filename4,"a") as f: f.write(apple.get_price()) f.write(" ") with open(filename5,"a") as f: f.write(amazon.get_price()) f.write(" ") yahoo.refresh() google.refresh() microsoft.refresh() apple.refresh() amazon.refresh() time.sleep(30) c+=1 if c > 60: break