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)
from rtstock.stock import Stock stock = Stock('AAPL') print(stock.get_latest_price())
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'])]
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')
#---------------------------------------------------------------------------- #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) wikipedia.set_lang("it")
def get_price(stock_name): stock = Stock(stock_name) return stock.get_latest_price()[0]['LastTradePriceOnly']
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')
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 getLatestPrice(ticker): """Return latest price result of the ticker""" stock = Stock(ticker) # datadump=json.dumps(stock.get_info()) return stock.get_latest_price()
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))