def setUp(self): """SetUp.""" self.ticker = 'AAPL' self.stock = Stock(self.ticker) self.start_date = '2016-03-01' self.end_date = '2016-03-03' self.keys = [ 'Date', 'Adj_Close', 'Close', 'High', 'Low', 'Open', 'Volume' ]
def setUp(self): """SetUp.""" self.ticker = 'AAPL' self.stock = Stock(self.ticker) self.start_date = '2016-03-01' self.end_date = '2016-03-03' self.keys = ['Date', 'Adj_Close', 'Close', 'High', 'Low', 'Open', 'Volume']
def stock_worker(sym): stock = Stock(sym) for i in range(100): try: data = stock.get_latest_price()[0] if data[u'LastTradeTime'] is None: print('Stock %s is unavailable. ' % sym) break last_time = str(data[u'LastTradeTime']) price = float(str(data[u'LastTradePriceOnly'])) news = json.dumps(getNews(sym), indent=2) #print(news) # Do not print for now... print('{:<10}'.format(last_time + ':') + '{:<30}'.format('%0.2fUSD' % price)) except: import traceback traceback.print_exc() print('%s FAILED' % sym) time.sleep(10)
def runData(stock, cursor): realtime = Stock(stock) data = getData(stock) format_str = """INSERT INTO realtime (last_price, price_time, symbol) VALUES ('{last_price}','{price_time}','{symbol}');""" sql_command = format_str.format(last_price=data[0], price_time=data[1], symbol=data[2]) print(sql_command) cursor.execute(sql_command)
class TestStockGetHistorical(unittest.TestCase): """Tests for Stock's get_historical method.""" def setUp(self): """SetUp.""" self.ticker = 'AAPL' self.stock = Stock(self.ticker) self.start_date = '2016-03-01' self.end_date = '2016-03-03' self.keys = ['Date', 'Adj_Close', 'Close', 'High', 'Low', 'Open', 'Volume'] def test_success(self): """Test get_historical success.""" response = self.stock.get_historical(self.start_date, self.end_date) # Checks for 3 dictionaries (one per day) self.assertEqual(len(response), 3) # Checks for the field on 'keys' self.assertEqual(response[0]['Date'], self.end_date) self.assertEqual(response[2]['Date'], self.start_date) self.assertEqual(len(response[0].keys()), len(self.keys)) for key in response[0].keys(): self.assertTrue(key in self.keys) def test_wrong_format(self): """Test get_historical passing a wrong date.""" with self.assertRaises(ValueError): self.stock.get_historical(self.start_date, '11111') def test_more_than_a_year(self): """Test get_historical passing a period greater than a year.""" with self.assertRaises(ValueError): self.stock.get_historical(self.start_date, '2017-03-03') def test_change_start_and_end(self): """Test get_historical misplacing start and end dates.""" with self.assertRaises(ValueError): self.stock.get_historical(self.end_date, self.start_date)
class TestStockGetHistorical(unittest.TestCase): """Tests for Stock's get_historical method.""" def setUp(self): """SetUp.""" self.ticker = 'AAPL' self.stock = Stock(self.ticker) self.start_date = '2016-03-01' self.end_date = '2016-03-03' self.keys = [ 'Date', 'Adj_Close', 'Close', 'High', 'Low', 'Open', 'Volume' ] def test_success(self): """Test get_historical success.""" response = self.stock.get_historical(self.start_date, self.end_date) # Checks for 3 dictionaries (one per day) self.assertEqual(len(response), 3) # Checks for the field on 'keys' self.assertEqual(response[0]['Date'], self.end_date) self.assertEqual(response[2]['Date'], self.start_date) self.assertEqual(len(response[0].keys()), len(self.keys)) for key in response[0].keys(): self.assertTrue(key in self.keys) def test_wrong_format(self): """Test get_historical passing a wrong date.""" with self.assertRaises(ValueError): self.stock.get_historical(self.start_date, '11111') def test_more_than_a_year(self): """Test get_historical passing a period greater than a year.""" with self.assertRaises(ValueError): self.stock.get_historical(self.start_date, '2017-03-03') def test_change_start_and_end(self): """Test get_historical misplacing start and end dates.""" with self.assertRaises(ValueError): self.stock.get_historical(self.end_date, self.start_date)
class TestFakeStock(unittest.TestCase): """Tests for fake Stock""" def setUp(self): """SetUp.""" self.ticker = 'fake_ticker' self.stock = Stock(self.ticker) def test_get_ticker(self): """Test get_ticker.""" self.assertEqual(self.stock.get_ticker(), self.ticker) def test_set_ticker(self): """Test set_ticker.""" self.stock.set_ticker('new_ticker') self.assertEqual(self.stock.get_ticker(), 'new_ticker') def test_get_latest_price(self): """Test get_latest_price error.""" response = self.stock.get_latest_price() # Checks for 'LastTradePriceOnly', 'LastTradeTime' field # Check if both fields are empty self.assertEqual(len(response[0].keys()), 2) for key in response[0].keys(): self.assertTrue(key in ['LastTradePriceOnly', 'LastTradeTime']) self.assertFalse(response[0][key]) def test_get_info(self): """Test get_info error.""" keys = [ 'Ask', 'AverageDailyVolume', 'Bid', 'BookValue', 'Change', 'Change_PercentChange', 'ChangeFromFiftydayMovingAverage', 'ChangeFromTwoHundreddayMovingAverage', 'ChangeFromYearHigh', 'ChangeFromYearLow', 'ChangeinPercent', 'Currency', 'DaysHigh', 'DaysLow', 'DaysRange', 'DividendPayDate', 'DividendShare', 'DividendYield', 'EarningsShare', 'EBITDA', 'EPSEstimateCurrentYear', 'EPSEstimateNextQuarter', 'EPSEstimateNextYear', 'ExDividendDate', 'FiftydayMovingAverage', 'LastTradeDate', 'LastTradePriceOnly', 'LastTradeTime', 'LastTradeWithTime', 'MarketCapitalization', 'Name', 'OneyrTargetPrice', 'Open', 'PEGRatio', 'PERatio', 'PercebtChangeFromYearHigh', 'PercentChange', 'PercentChangeFromFiftydayMovingAverage', 'PercentChangeFromTwoHundreddayMovingAverage', 'PercentChangeFromYearLow', 'PreviousClose', 'PriceBook', 'PriceEPSEstimateCurrentYear', 'PriceEPSEstimateNextYear', 'PriceSales', 'ShortRatio', 'StockExchange', 'Symbol', 'TwoHundreddayMovingAverage', 'Volume', 'YearHigh', 'YearLow', 'YearRange' ] response = self.stock.get_info() # Checks for 'LastTradePriceOnly', 'LastTradeTime' field self.assertEqual(len(response[0].keys()), len(keys)) for key in response[0].keys(): self.assertTrue(key in keys) # Check if all fields but Symbol are empty if key == 'Symbol': self.assertEqual(response[0][key], self.ticker) else: self.assertFalse(response[0][key]) def test_save_historical(self): """Test save_historical error.""" with self.assertRaises(error.RequestError): self.stock.save_historical('.')
# Yahoo real time data #---------------------------------------------------------------------------- #stock we want to scrap: ticker = 'ENI.MI' #when we want to finish: finish_time = datetime.datetime.now() + datetime.timedelta(hours=0.3) #time sleep (minuts) between the price queries: delta = 1 stocks_quote = Yahoo_realTime(ticker, finish_time, delta) stocks_quote.to_csv('files/StreamingData.csv') #----------------------------------------------------------------------------- # rtstock pacakage (https://pypi.org/project/realtime-stock/) from rtstock.stock import Stock stock = Stock('AAPL') stock.get_latest_price() #----------------------------------------------------------------------------- # wikipedia #----------------------------------------------------------------------------- wiki_url = 'https://it.wikipedia.org/wiki/Lisbona' wikipedia_text = ' '.join(wikipedia_scrap(wiki_url)) text_file = open("files/Wikipedia.txt", "w", encoding='utf-8') text_file.write(wikipedia_text) text_file.close() #WIKIPEDIA API: import wikipedia print(wikipedia.WikipediaPage(title='Lisbon').summary)
def getStockInfoVerbose(ticker): """Return verbose result of the ticker""" stock = Stock(ticker) # datadump=json.dumps(stock.get_info()) return stock.get_info()
def get_latest_price(name): # Returns the latest price the stock was traded at stock = Stock(name) return [str(stock.get_latest_price()[0]['LastTradePriceOnly'])]
import sys import os import json #sys.path.insert(0,os.path.join(os.path.realpath(__file__),'..')) #import my_dependencies; my_dependencies.check() from googlefinance import getNews from rtstock.stock import Stock sym = 'AAPL' stock = Stock(sym) while True: print(stock.get_latest_price()) print(json.dumps(getNews(sym), indent=2))
class TestFakeStock(unittest.TestCase): """Tests for fake Stock""" def setUp(self): """SetUp.""" self.ticker = 'fake_ticker' self.stock = Stock(self.ticker) def test_get_ticker(self): """Test get_ticker.""" self.assertEqual(self.stock.get_ticker(), self.ticker) def test_set_ticker(self): """Test set_ticker.""" self.stock.set_ticker('new_ticker') self.assertEqual(self.stock.get_ticker(), 'new_ticker') def test_get_latest_price(self): """Test get_latest_price error.""" response = self.stock.get_latest_price() # Checks for 'LastTradePriceOnly', 'LastTradeTime' field # Check if both fields are empty self.assertEqual(len(response[0].keys()), 2) for key in response[0].keys(): self.assertTrue(key in ['LastTradePriceOnly', 'LastTradeTime']) self.assertFalse(response[0][key]) def test_get_info(self): """Test get_info error.""" keys = ['Ask', 'AverageDailyVolume', 'Bid', 'BookValue', 'Change', 'Change_PercentChange', 'ChangeFromFiftydayMovingAverage', 'ChangeFromTwoHundreddayMovingAverage', 'ChangeFromYearHigh', 'ChangeFromYearLow', 'ChangeinPercent', 'Currency', 'DaysHigh', 'DaysLow', 'DaysRange', 'DividendPayDate', 'DividendShare', 'DividendYield', 'EarningsShare', 'EBITDA', 'EPSEstimateCurrentYear', 'EPSEstimateNextQuarter', 'EPSEstimateNextYear', 'ExDividendDate', 'FiftydayMovingAverage', 'LastTradeDate', 'LastTradePriceOnly', 'LastTradeTime', 'LastTradeWithTime', 'MarketCapitalization', 'Name', 'OneyrTargetPrice', 'Open', 'PEGRatio', 'PERatio', 'PercebtChangeFromYearHigh', 'PercentChange', 'PercentChangeFromFiftydayMovingAverage', 'PercentChangeFromTwoHundreddayMovingAverage', 'PercentChangeFromYearLow', 'PreviousClose', 'PriceBook', 'PriceEPSEstimateCurrentYear', 'PriceEPSEstimateNextYear', 'PriceSales', 'ShortRatio', 'StockExchange', 'Symbol', 'TwoHundreddayMovingAverage', 'Volume', 'YearHigh', 'YearLow', 'YearRange'] response = self.stock.get_info() # Checks for 'LastTradePriceOnly', 'LastTradeTime' field self.assertEqual(len(response[0].keys()), len(keys)) for key in response[0].keys(): self.assertTrue(key in keys) # Check if all fields but Symbol are empty if key == 'Symbol': self.assertEqual(response[0][key], self.ticker) else: self.assertFalse(response[0][key]) def test_save_historical(self): """Test save_historical error.""" with self.assertRaises(error.RequestError): self.stock.save_historical('.')
class TestRealStock(unittest.TestCase): """Tests for Stock.""" def setUp(self): """SetUp.""" self.ticker = 'AAPL' self.stock = Stock(self.ticker) def test_get_ticker(self): """Test get_ticker.""" self.assertEqual(self.stock.get_ticker(), self.ticker) def test_set_ticker(self): """Test set_ticker.""" self.stock.set_ticker('new_ticker') self.assertEqual(self.stock.get_ticker(), 'new_ticker') def test_get_latest_price(self): """Test get_latest_price success.""" response = self.stock.get_latest_price() # Checks for 'LastTradePriceOnly', 'LastTradeTime' field self.assertEqual(len(response[0].keys()), 2) for key in response[0].keys(): self.assertTrue(key in ['LastTradePriceOnly', 'LastTradeTime']) def test_get_info(self): """Test get_info success.""" keys = ['Ask', 'AverageDailyVolume', 'Bid', 'BookValue', 'Change', 'Change_PercentChange', 'ChangeFromFiftydayMovingAverage', 'ChangeFromTwoHundreddayMovingAverage', 'ChangeFromYearHigh', 'ChangeFromYearLow', 'ChangeinPercent', 'Currency', 'DaysHigh', 'DaysLow', 'DaysRange', 'DividendPayDate', 'DividendShare', 'DividendYield', 'EarningsShare', 'EBITDA', 'EPSEstimateCurrentYear', 'EPSEstimateNextQuarter', 'EPSEstimateNextYear', 'ExDividendDate', 'FiftydayMovingAverage', 'LastTradeDate', 'LastTradePriceOnly', 'LastTradeTime', 'LastTradeWithTime', 'MarketCapitalization', 'Name', 'OneyrTargetPrice', 'Open', 'PEGRatio', 'PERatio', 'PercebtChangeFromYearHigh', 'PercentChange', 'PercentChangeFromFiftydayMovingAverage', 'PercentChangeFromTwoHundreddayMovingAverage', 'PercentChangeFromYearLow', 'PreviousClose', 'PriceBook', 'PriceEPSEstimateCurrentYear', 'PriceEPSEstimateNextYear', 'PriceSales', 'ShortRatio', 'StockExchange', 'Symbol', 'TwoHundreddayMovingAverage', 'Volume', 'YearHigh', 'YearLow', 'YearRange'] response = self.stock.get_info() # Checks for 'LastTradePriceOnly', 'LastTradeTime' field self.assertEqual(len(response[0].keys()), len(keys)) for key in response[0].keys(): self.assertTrue(key in keys) def test_save_historical(self): """Test save_historical success.""" first_line = b'Date,Open,High,Low,Close,Volume,Adj Close\n' self.stock.save_historical('.') with open(self.ticker + '.csv', 'rb') as f: self.assertEqual(f.readline(), first_line) os.remove(self.ticker + '.csv')
def setUp(self): """SetUp.""" self.ticker = 'AAPL' self.stock = Stock(self.ticker)
class TestRealStock(unittest.TestCase): """Tests for Stock.""" def setUp(self): """SetUp.""" self.ticker = 'AAPL' self.stock = Stock(self.ticker) def test_get_ticker(self): """Test get_ticker.""" self.assertEqual(self.stock.get_ticker(), self.ticker) def test_set_ticker(self): """Test set_ticker.""" self.stock.set_ticker('new_ticker') self.assertEqual(self.stock.get_ticker(), 'new_ticker') def test_get_latest_price(self): """Test get_latest_price success.""" response = self.stock.get_latest_price() # Checks for 'LastTradePriceOnly', 'LastTradeTime' field self.assertEqual(len(response[0].keys()), 2) for key in response[0].keys(): self.assertTrue(key in ['LastTradePriceOnly', 'LastTradeTime']) def test_get_info(self): """Test get_info success.""" keys = [ 'Ask', 'AverageDailyVolume', 'Bid', 'BookValue', 'Change', 'Change_PercentChange', 'ChangeFromFiftydayMovingAverage', 'ChangeFromTwoHundreddayMovingAverage', 'ChangeFromYearHigh', 'ChangeFromYearLow', 'ChangeinPercent', 'Currency', 'DaysHigh', 'DaysLow', 'DaysRange', 'DividendPayDate', 'DividendShare', 'DividendYield', 'EarningsShare', 'EBITDA', 'EPSEstimateCurrentYear', 'EPSEstimateNextQuarter', 'EPSEstimateNextYear', 'ExDividendDate', 'FiftydayMovingAverage', 'LastTradeDate', 'LastTradePriceOnly', 'LastTradeTime', 'LastTradeWithTime', 'MarketCapitalization', 'Name', 'OneyrTargetPrice', 'Open', 'PEGRatio', 'PERatio', 'PercebtChangeFromYearHigh', 'PercentChange', 'PercentChangeFromFiftydayMovingAverage', 'PercentChangeFromTwoHundreddayMovingAverage', 'PercentChangeFromYearLow', 'PreviousClose', 'PriceBook', 'PriceEPSEstimateCurrentYear', 'PriceEPSEstimateNextYear', 'PriceSales', 'ShortRatio', 'StockExchange', 'Symbol', 'TwoHundreddayMovingAverage', 'Volume', 'YearHigh', 'YearLow', 'YearRange' ] response = self.stock.get_info() # Checks for 'LastTradePriceOnly', 'LastTradeTime' field self.assertEqual(len(response[0].keys()), len(keys)) for key in response[0].keys(): self.assertTrue(key in keys) def test_save_historical(self): """Test save_historical success.""" first_line = b'Date,Open,High,Low,Close,Volume,Adj Close\n' self.stock.save_historical('.') with open(self.ticker + '.csv', 'rb') as f: self.assertEqual(f.readline(), first_line) os.remove(self.ticker + '.csv')
def getLatestPrice(ticker): """Return latest price result of the ticker""" stock = Stock(ticker) # datadump=json.dumps(stock.get_info()) return stock.get_latest_price()
bg='white', font=('Calibri', 10)).grid(column=0, sticky='W') # Label(business_root, text = item.description.text, fg = 'dimgray', bg = 'white', font = ('Calibri',8), wraplength = 500, justify = LEFT).grid(rowspan =4, columnspan = 4, sticky = W) ############################################################### stocks_root = Frame(business_root, bg='black') stocks_root.grid(column=0) Label(business_root, text='Stock Quotes', fg='navy', bg='white', font=('Calibri', 15, 'bold')).grid(column=0, sticky=W) all_stocks = [ Stock('AAPL'), Stock('AMZN'), Stock('GOOG'), Stock('NFLX'), Stock('FB'), Stock('TSLA') ] for stock in all_stocks: stock_info = stock.get_info() Label(business_root, text=stock_info[0]['Symbol'] + ' ' + stock_info[0]['LastTradePriceOnly'] + ' ' + stock_info[0]['PercentChange'], fg='black', bg='white',
import pandas as pandas from pandas_datareader import data as web import datetime from datetime import datetime, timedelta from simpleMovingAverage import simpleMovingAverage from volume import Volume from rtstock.stock import Stock smalist=[] #SMA = SimpleMovingAverage.simpleMovingAverage(x) for x in c: print() yahoo= Stock('GOOG') yahoo.get_latest_price() print(google) #print (currentprice) #SMA = simpleMovingAverage(x) #volume = Volume(x) #if(volume>500000): #smalist.append([x,SMA,volume]) #print(SMA) #print volume #with open('SMA.txt','w') as f: #for item in smalist: #print (item, end="", file=f) #f.close()
def setUp(self): """SetUp.""" self.ticker = 'fake_ticker' self.stock = Stock(self.ticker)
from rtstock.stock import Stock stock = Stock('AAPL') print(stock.get_latest_price())
btc_high = 2800 eth_low = 225 # Ethereum eth_high = 275 etc_low = 10 # Ethereum Classic etc_high = 25 zec_low = 225 # Zcash zec_high = 275 print("Monitoring stock market and cryptocurrency rates...") while True: # Print actual timestamp print(datetime.now().strftime("%d/%m/%y %H:%M:%S")) # Get actual stock market prices TSLA = float(Stock('TSLA').get_latest_price()[0]["LastTradePriceOnly"]) # Tesla MSFT = float(Stock('MSFT').get_latest_price()[0]["LastTradePriceOnly"]) # Microsoft NVDA = float(Stock('NVDA').get_latest_price()[0]["LastTradePriceOnly"]) # NVIDIA WESAS = float(Stock('WES.AS').get_latest_price()[0]["LastTradePriceOnly"]) # WES.AS btc = get_current_price('btc', 'eur') # Bitcoin eth = get_current_price('eth', 'eur') # Ethereum etc = get_current_price('etc', 'eur') # Ethereum Classic zec = get_current_price('zec', 'eur') # Zcash # Trigger telegram's alert (if any) if TSLA < TSLA_low: telegram_alert("Tesla low price: " + str(TSLA)) if TSLA > TSLA_high: telegram_alert("Tesla high price: " + str(TSLA)) if MSFT < MSFT_low: telegram_alert("Microsoft low price: " + str(MSFT)) if MSFT > MSFT_high: telegram_alert("Microsoft high price: " + str(MSFT))
def get_price(stock_name): stock = Stock(stock_name) return stock.get_latest_price()[0]['LastTradePriceOnly']
from yahoo_finance import Share from rtstock.stock import Stock from googlefinance import getQuotes import json Stock_One = 'tsla' # Get the Data from rtstock rtstock_stock = Stock(Stock_One) rtstock_latestprice = rtstock_stock.get_latest_price() print("rtstock returns this value:", rtstock_latestprice) # Get the stock Data from yahoo_finance VERY EXTENSIVE yahooofinance_stock = Share(Stock_One) yahooofinance_latestprice = yahooofinance_stock.get_price() yahooofinance_tradetime = yahooofinance_stock.get_trade_datetime() yahooofinance_anotherfunction = yahooofinance_stock.get_last_trade_with_time() print('Yahoo finance retuns:', yahooofinance_latestprice, 'on the time:', yahooofinance_tradetime, 'AND IT RETURNS:', yahooofinance_anotherfunction) # Get the stock Data from GoogleFinance WORKS REAL TIME, THE OTHERS DONT # print('The Google Finance module returns:', json.dumps(getQuotes(Stock_One), indent=2))