예제 #1
0
def get_current_shares():
    """Gets current shares, writes updated version back to json"""

    company_dict = get_company_dict()

    gmt = datetime.now()
    market_time = gmt.replace(hour=abs(gmt.hour - 5))

    # Ensure market is open (opening hours 9:30 - 4 EST)
    if int(str(market_time.hour) + str(market_time.minute if market_time.minute >= 10 else f'0{market_time.minute}')):
        for company in company_dict:
            try:
                stock = Pinance(company_dict[company]["symbol"])
                stock.get_quotes()

                share = stock.quotes_data["regularMarketPrice"]

                # Gets the current share price, replaces the "current"
                # and adds to the sharePriceList
                curr_day = str(company_dict[company]["day"])
                company_dict[company]["currentSharePrice"] = float(share)
                company_dict[company]["sharePriceList"][curr_day].append(("{:%d-%m-%Y %H:%M:%S}".format(datetime.now()),
                                                                          float(share)))

                # Gets the current share change
                share_change = 1.0 - (company_dict[company]["initialSharePrice"] /
                                      company_dict[company]["currentSharePrice"])
                company_dict[company]["shareChange"] = share_change

            except TypeError as error:
                # Will catch the error if share returns a value other than a float
                logging.debug(error)

    with open(MONITOR, "w") as f:
        json.dump(company_dict, f, sort_keys=True, indent=4, ensure_ascii=False)
예제 #2
0
async def stock(symbol: str):
    symbol = symbol.upper()
    if symbol == "HELP":
        await bot.say(
            'Command is written as: ",stock <Stock>". Bot only can take input of stock symbol such as AAPL or GOOGL. To get data on Apple one would type ",crypto AAPL".'
        )
    else:
        try:

            company = Pinance(symbol)
            company.get_quotes()
            stock = company.quotes_data

            price = stock['regularMarketPrice']
            percentchange = stock['regularMarketChangePercent']
            index = stock['fullExchangeName']
            lastupdate = stock['regularMarketTime']
            timeupdated = datetime.datetime.fromtimestamp(
                int(lastupdate)).strftime('%Y-%m-%d %H:%M:%S')
            await bot.say(symbol + ' is currently trading at $' + str(price) +
                          ' corresponding to a ' + str(percentchange) +
                          '% change. This was last updated at ' + timeupdated)

        except KeyError:
            await bot.say('Error: This input is not a stock symbol.')
예제 #3
0
def get_initial_company_info():
    """Gets the initial information for each company"""

    company_dict = get_company_dict()

    for company in company_dict:
        # Gets symbol for company
        if company_dict[company]["symbol"] == "unknown":
            try:
                with urllib.request.urlopen(
                      f'https://finance.yahoo.com/_finance_doubledown/'
                      f'api/resource/searchassist;searchTerm={company_dict[company]["companyName"]}') as response:

                    html = response.read().decode()
                    d = json.loads(html)

                    company_dict[company]["symbol"] = d['items'][0]['symbol']

            except urllib.error.HTTPError as error:
                logging.debug(error)
                break

        # Gets initial share price
        if company_dict[company]["initialSharePrice"] == 1:
            stock = Pinance(company_dict[company]["symbol"])
            stock.get_quotes()

            share = stock.quotes_data["regularMarketPrice"]

            company_dict[company]["initialSharePrice"] = float(share)
            company_dict[company]["currentSharePrice"] = float(share)

    with open(MONITOR, "w") as f:
        json.dump(company_dict, f, sort_keys=True, indent=4, ensure_ascii=False)
예제 #4
0
def get_quote(symbol):
    stock = Pinance(symbol)
    stock.get_quotes()
    rec_data = stock.quotes_data
    print(rec_data)
    last_tradeprice = rec_data['LastTradePrice']
    print('LTP : %s"' %last_tradeprice)
예제 #5
0
def liveDailyPercent(symbol):
    stock = Pinance(symbol)
    stock.get_quotes()
    percentChange = stock.quotes_data['regularMarketChangePercent']
    cacheQuote(symbol,{'percentChange':percentChange,
                        'lastPrice':stock.quotes_data['regularMarketPrice'],
                        'change':stock.quotes_data['regularMarketChange']})
    return percentChange
예제 #6
0
def get_forward_pe_ratio(ticker):
    """
        Stock Price / Future Earnings Per Share
    :param ticker:
    :return: forward PE Ratio
    """

    from pinance import Pinance
    pinance_data = Pinance(ticker)
    pinance_data.get_quotes()
    pinance_data.quotes_data['forwardPE']
예제 #7
0
def liveQuote(symbol, lock=None):
    stock = Pinance(symbol)
    stock.get_quotes()
    if 'postMarketPrice' in stock.quotes_data.keys():
        currValue = float(stock.quotes_data['postMarketPrice'])*STOCKS[symbol]
        dayChange = float(stock.quotes_data['regularMarketChange'] + stock.quotes_data['postMarketChange'])*STOCKS[symbol]
    else:
        currValue = float(stock.quotes_data['regularMarketPrice'])*STOCKS[symbol]                
        dayChange = stock.quotes_data['regularMarketChange']*STOCKS[symbol]
    cacheQuote(symbol,
                {'lastPrice':stock.quotes_data['regularMarketPrice'],
                'change':stock.quotes_data['regularMarketChange'],
                'percentChange':stock.quotes_data['regularMarketChangePercent']},
                lock)
    return (currValue,dayChange)
예제 #8
0
def get_stock_data(
        tickers=get_sp500_tickers(), path='pinance_data/{}.pickle',
        update=False):
    for symbol in tickers:
        if update:
            print("Reading data for ticker " + symbol['ticker'])
            stock = Pinance(symbol['ticker'])
            stock.get_quotes()
            stock.get_news()

            stock_data = stock.quotes_data
            stock_news = stock.news_data

            data = {
                'ticker': symbol['ticker'],
                'data': stock_data,
                'news': stock_news
            }

            write_to_pickle(data, path.format(symbol['ticker']))

        else:
            with open(path.format(symbol['ticker']), 'rb') as handle:
                data = pickle.load(handle)

        yield data
예제 #9
0
# my_url = 'http://topforeignstocks.com/stock-lists/the-complete-list-of-biotech-stocks-trading-on-nasdaq/' # List of biotech companies (outdated source)
# uClient = requests.get(my_url) #downloads webpage
# page_html = uClient.text
# page_soup = soup(page_html, "html.parser")
# bio_tech_companies = page_soup.findAll("td",{"class":"column-2"}) # specific to name
# bio_tech_companies_symbol = page_soup.findAll("td",{"class":"column-3"}) # specific to symbol
NASDAQ_File = pd.read_csv('NASDAQ_Company_List.csv')
Industry = NASDAQ_File['Industry']
Symbol = NASDAQ_File['Symbol']
Name = NASDAQ_File['Name']
for i in range(len(Industry)):
    if 'Biotechnology' in str(Industry[i]) or 'Pharmaceuticals' in str(
            Industry[i]):
        query = str(Name[i])  # gets name of biotech company
        query_symbol = str(Symbol[i])  # gets symbol of biotech company
        stock = Pinance(query_symbol)
        stock.get_quotes()
        try:  # necessary if stock.get_quotes returns an empty or incomplete dictionary
            if stock.quotes_data['tradeable'] == True:
                stock_price = ((stock.quotes_data['regularMarketPrice']))
                if stock_price < 35.00:
                    query_params = {
                        "q":
                        "language:english site_type:news "
                        "title: {0}".format(query),
                        "sort":
                        "crawled",
                    }
                    output = webhoseio.query("filterWebContent", query_params)
                    count = 0  # used to limit number of articles printed on a certain company
                    for i in range(len(output['posts'])):
예제 #10
0
#TODO Create a `PinanceClient` class that has functions in it that call the pinance code

# TODO this needs to be a function that takes in a list of stocks and puts the quotes into a dictionay
"""
{'VZ': 
	{
		'stock': ...,
		'quote': ...,
		'market_price': ...
	},
	...
}
"""
for each_symbol in dogs_of_dow:
    stock_list = Pinance(each_symbol)
    symbol = each_symbol
    stock = Pinance(symbol)
    stock.get_quotes()

    # Gets the price of the list of stocks in djia_list.
    price_stock = stock.quotes_data['regularMarketPrice']

    # Gets the trailing annual divident of the list of stocks in djia_list.
    dividend_yield = stock.quotes_data['trailingAnnualDividendRate']

    # Prints stock tickers, prices, and dif yields of the list of stocks in djia_list.
    #print(each_symbol, price_stock, dividend_yield)

    # Calculate number of shares to buy based on stock allocation and the price of each stock in dog list.
    shares_to_buy = stock_allocation / price_stock
예제 #11
0
from pinance import Pinance

symbol = "OGEN"

stock = Pinance(symbol)

stock.get_quotes()

print((stock.quotes_data))
예제 #12
0
alldata = []
try:
    for stock in static.equitties_train:
        mydata = quandl.get_table('ZACKS/MKTV', ticker=stock)
        if len(mydata) > 0:

            mydata['date'] = pd.to_datetime(mydata['per_end_date'])
            mc = mydata.set_index('date')[['mkt_val'
                                           ]].sort_index().iloc[-1]['mkt_val']
            alldata.append((stock, round(mc)))
        else:
            alldata.append((stock, 'nan'))
except:
    print(alldata)

#this is the good one
from pinance import Pinance

alldata = []
try:
    for stock in static.equitties_train:
        share = Pinance(stock)
        try:
            share.get_quotes()
            mc = share.quotes_data['marketCap']
        except:
            alldata.append((stock, 'nan'))
            continue
        alldata.append((stock, round(mc / 1000000)))
except:
    print(alldata)
예제 #13
0
from pinance import Pinance

symbol = "VALO.BA"
valo = Pinance("VALO.BA")
edn = Pinance("EDN.BA")
agro = Pinance("AGRO.BA")

valo.get_quotes()
edn.get_quotes()
agro.get_quotes()

print("precio " + valo.quotes_data['longName'] + ": ",
      valo.quotes_data['regularMarketPrice'])
print("precio " + edn.quotes_data['longName'] + ": ",
      edn.quotes_data['regularMarketPrice'])
print("precio " + agro.quotes_data['longName'] + ": ",
      agro.quotes_data['regularMarketPrice'])
예제 #14
0
from pinance import Pinance
import pandas as pd

stock1 = 'HDFC'
stock2 = 'HDFC.NS'

first = Pinance(stock1)
second = Pinance(stock2)

first.get_quotes()
second.get_quotes()

second.get_news()

df1 = pd.DataFrame(data=first.quotes_data, index=[0])
df2 = pd.DataFrame(data=second.quotes_data, index=[0])
df1 = (df1.T)
df2 = (df2.T)
df1.to_excel("DataQuality\hdfc.xls")
df2.to_excel("DataQuality\hdfcNS.xls")

df3 = pd.DataFrame(data=second.news_data, index=[0])
df3 = (df3.T)

df3.to_excel(r"DataQuality\news.xls")