예제 #1
0
def eight_k():
    eight_dic = {
        'Item 1.03': 'Bankruptcy or Receivership',
        'Item 1.04': 'Mine Safety - Reporting of Shutdowns and Patterns of Violations',
        'Item 2.04': 'Triggering Events That Accelerate or Increase a Direct Financial Obligation or an Obligation under an Off-Balance Sheet Arrangement',
        'Item 2.05': 'Costs Associated with Exit or Disposal Activities',
        'Item 2.06': 'Material Impairments',
        'Item 3.01': 'Notice of Delisting or Failure to Satisfy a Continued Listing Rule or Standard; Transfer of Listing',
        'Item 4.02': 'Non-Reliance on Previously Issued Financial Statements or a Related Audit Report or Completed Interim Review',
        'Item 5.04': 'Temporary Suspension of Trading Under Registrant"s Employee Benefit Plans',
        'Item 6.04': 'Failure to Make a Required Distribution',}
    a = feedparser.parse('http://www.sec.gov/cgi-bin/browse-edgar?action=getcurrent&CIK=&type=8-k&company=&dateb=&owner=include&start=0&count=100&output=atom')
    time.sleep(2)
    today = datetime.datetime.today()
    for entry in range(0,99):
        try:
            company_name = a.entries[entry].title.lower()
            company_summary = a.entries[entry].summary
            for key in eight_dic:
                
                if key in company_summary:
                    last25 = slice(-25, None)
                    
                    if company_name[last25] not in stocks_sent:
                        day = a.entries[entry].updated
                        day = day.split('T')
                        t = day[0]
    
                        if t in str(today):
                            try:
                               cik = company_name[company_name.find("(")+1:company_name.find(")")]
                               stocks_sent.append(company_name[last25])    
                               headers = {'Ocp-Apim-Subscription-Key': 'GETYOUROWNSUBSCRIPTIONKEY',}
                               params = urllib.parse.urlencode({})
                               conn = http.client.HTTPSConnection('services.last10k.com')
                               conn.request("GET", "/v1/company/"+cik+"/ticker?%s" % params, "{body}", headers)
                               responsed = conn.getresponse()
                               with responsed as response:
                                   html_content = response.read()
                                   ticker = html_content
                               ticker = str(ticker)
                               ticker = ticker.replace("b","")                          
                               ticker = ticker.replace('"','')  
                               ticker = ticker.replace("'","")  
                               ticker = ticker.replace(" ","")
                               ticker = ticker.upper()
                               symbol = ticker
                               conn.close()
                               desc = eight_dic.get(key)
                               ticker = Stock(ticker)
                               current_price = ticker.get_price()
                               message = company_name+'\n'+symbol+'\n$'+str(current_price)+'\n\n'+key+'\n'+desc
                               confirm(text=message, title='Short Option', buttons=['OK'])
                               print(key,'\n',desc,'\n~~~~~~~~~~~~~~~~~~~~')
                            except:
                               print('research fail: ',company_name)   
                               pass
        except:
            print('da fuk? Re 8k')
            pass
예제 #2
0
def index():
    form = investmentForm()
    if request.method == 'POST' and form.validate():

        #Get form field data
        symb = form.stockSymbol.data
        stock = Stock(symb)
        openPrice = stock.get_open()
        nowPrice = stock.get_price()
        companyInfo = stock.get_company()
        companyName = companyInfo['companyName']
        symbol = companyInfo['symbol']
        calculate = openPrice - nowPrice
        calc = "{:.2f}".format(calculate)

        ct = datetimeConverstion()
        percentage = ((openPrice - nowPrice) / openPrice) * 100
        percent = "{:.2f}".format(percentage)
        new_date = ct.strftime('%A %Y-%m-%d %I:%M %p')

        return render_template('price.html',
                               symbol=symbol,
                               companyName=companyName,
                               nowPrice=nowPrice,
                               new_date=new_date,
                               calc=calc,
                               percent=percent)
    return render_template('home.html', form=form)
예제 #3
0
def stock_return(message):
    result = interpreter.parse(message)

    global stock_re
    global setting

    if 'open' in result.get('entities')[0].get('value'):
        company = result.get('entities')[1].get('value')
        for i in setting:
            if company in i.get('name'):
                company = i.get('symbol')
        open_price = Stock(company).get_open()
        stock_re = "The open price is {}".format(open_price)

    if 'close' in result.get('entities')[0].get('value'):
        company = result.get('entities')[1].get('value')
        for i in setting:
            if company in i.get('name'):
                company = i.get('symbol')
        close_price = Stock(company).get_price()
        stock_re = "The close price is {}".format(close_price)

    if 'volume' in result.get('entities')[0].get('value'):
        company = result.get('entities')[1].get('value')
        for i in setting:
            if company in i.get('name'):
                company = i.get('symbol')
        volume = Stock(company).get_volume()
        stock_re = "The volume is {}".format(volume)
예제 #4
0
def stock_return(message):
    result = interpreter.parse(message)

    global stock_re
    global remember

    company = ''

    if 'open' in result.get('entities')[0].get('value'):
        if remember != '':
            company = remember
        else:
            company = result.get('entities')[1].get('value')
        open_price = Stock(company).get_open()
        stock_re = "The open price is {}".format(open_price)

    if 'close' in result.get('entities')[0].get('value'):
        if remember != '':
            company = remember
        else:
            company = result.get('entities')[1].get('value')
        close_price = Stock(company).get_price()
        stock_re = "The close price is {}".format(close_price)

    if 'volume' in result.get('entities')[0].get('value'):
        if remember != '':
            company = remember
        else:
            company = result.get('entities')[1].get('value')
        volume = Stock(company).get_volume()
        stock_re = "The volume is {}".format(volume)

    if result.get('entities')[0].get('entity') == 'company':
        stock_re = "Do you wanna look at open price, close price or volume?"
        remember = result.get('entities')[0].get('value')
예제 #5
0
def update_header(submit, input_value):

    b = Stock(input_value)
    name = pd.DataFrame([b.get_company()])
    description = name['description']

    return description
예제 #6
0
def getStock(name):
    # get data from API - use the Python requests library
    # process input to pull out the right values needed
    # calculate the sharpe ratio 
    # return the sharpe ratio
    stock = Stock(name)  
    return str(stock.get_price())
예제 #7
0
def data(tickers, sector):
    slist = []
    print(tickers)
    stocks_object = Stock(tickers)
    stocks = stocks_object.get_price()
    now = datetime.now()
    last_year = datetime.now() - timedelta(days=365)
    date = datetime.today().strftime('%Y-%m-%d')
    for company in stocks:
        # Create one-year graph trend for company
        df = web.DataReader(company, 'robinhood', datetime(last_year.year, last_year.month, last_year.day), datetime(now.year, now.month, now.day)).reset_index()
        data = [go.Scatter(x=df.begins_at, y=df.close_price)]
        layout = go.Layout(title=company, xaxis={'title': 'Date'}, yaxis={'title':'Close Price'})
        figure = go.Figure(data=data, layout=layout)
        link = py.plot(figure, filename=company)

        # Get closing price of company
        price = stocks[company]

        # Link to company graph
        company_graph = "[{}]({})".format(company, link)

        # Output company info
        slist.append([date, company_graph, price])
    output(slist)
예제 #8
0
def price(ticker):
    try:
        ticker = Stock(ticker.ticker)
        price = ticker.get_price()
    except:
        return "---"
    else:
        return price
예제 #9
0
 def setup_class(self):
     self.cshare = Stock("aapl")
     self.cshare2 = Stock("aapl", output_format='pandas')
     self.cshare3 = Stock("svxy")
     self.cshare4 = Stock("aapl",
                          json_parse_int=Decimal,
                          json_parse_float=Decimal)
     self.cshare5 = Stock("gig^")
예제 #10
0
def update_header(submit, input_value):

    b = Stock(input_value)
    name = pd.DataFrame([b.get_company()])
    name = name['companyName'].values[0]
    f = str(b.get_price())
    title = name + ' $' + f
    return title
예제 #11
0
 def test_wrong_iex_input_type(self):
     with pytest.raises(ValueError):
         Stock(34)
     with pytest.raises(ValueError):
         Stock("")
     with pytest.raises(ValueError):
         ls = []
         Stock(ls)
예제 #12
0
    def test_wrong_option_values(self):
        with pytest.raises(ValueError):
            Stock("aapl", last=555)

        with pytest.raises(TypeError):
            Stock("aapl", displayPercent=4)

        with pytest.raises(ValueError):
            Stock("aapl", _range='1yy')
예제 #13
0
def update_graph(submit, input_value):
    b = Stock(input_value)
    d = b.get_news()
    df = pd.DataFrame(d)
    df = df[['headline', 'url']]
    e = pd.DataFrame([b.get_key_stats()])
    e = e[['EBITDA', 'beta', 'latestEPS', 'marketcap']]

    return e.to_dict('records')
예제 #14
0
def fetch_market_data(tickers):
    prices = {}
    for i in range(0, len(tickers), 99):
        # print('{}/{}'.format(i, len(tickers)))
        stock = Stock(tickers[i:i + 99])
        batch_prices = {ticker: (datetime.now(), value) for ticker, value in stock.get_price().items()}
        prices.update(batch_prices)
    batch_prices = {ticker: (datetime.now(), value) for ticker, value in Stock(tickers[-(len(tickers) % 99):]).get_price().items()}
    prices.update(batch_prices)
    return prices
예제 #15
0
def buy_portfolio(equity_values):
    '''
    Buys our portfolio.
    Sells everything that we want to reduce the weight of first, then
    buys everything we want to increase weight of.

    If an order doesn't fill all the way, it expires at end of day.

    We calculate number of shares to buy by dividing equity value we
    got by the current price.
    '''
    time.sleep(10)
    buy_dict = {}
    sell_dict = {}

    portfolio = []
    for position in api.list_positions():
        portfolio.append(position.symbol)

    bought_so_far = 0
    for symbol in equity_values:
        equity=equity_values[symbol]
        quantity = int(equity // Stock(symbol).get_price())
        if symbol in portfolio:
            quantity -= int(api.get_position(symbol).qty)
        if quantity > 0:
            buy_dict[symbol] = quantity
        elif quantity < 0:
            sell_dict[symbol] = quantity

    for symbol in sell_dict:
        quantity = sell_dict[symbol]
        time.sleep(10)
        quantity = abs(quantity)
        print('submit(sell): ' + str(quantity) + ' shares of ' + symbol)
        print(str(quantity * Stock(symbol).get_price()) + ' sold')
        try:
            util.sell(symbol, quantity)
        except:
            print("Not sold due to an error.")

    for symbol in buy_dict:
        quantity = buy_dict[symbol]
        time.sleep(10)
        print('submit(buy): ' + str(quantity) + ' shares of ' + symbol)
        new_bought = quantity * Stock(symbol).get_price()
        bought_so_far += new_bought
        print(str(new_bought) + " of " + symbol + " bought ")
        print("new portfolio value bought so far: $" + str(bought_so_far))
        try:
            util.buy(symbol, quantity)
        except:
            print("Not bought due to an error.")
        
    return None
예제 #16
0
파일: price.py 프로젝트: 0x9924/hlp
def main(argv):
    print("name\tprice\topen\tvariation")
    for n in argv:
        try:
            s = Stock(n)
            price = s.get_price()
            open = s.get_open()
            variation = 100 * (price - open) / open
            print("{}\t{}\t{}\t{:.3f} %".format(n, price, open, variation))
        except:
            sys.stderr.write("error fetching data for '{}'\n".format(n))
예제 #17
0
def get_close(sym):
    start = time.time()
    try:
        symbol = Stock(sym)
        symclose = symbol.get_close()

    except:
        symclose = alternative_close(sym)
    
    end = time.time()
    #print(f'{sym} close generation took {end-start} seconds')
    return symclose
예제 #18
0
 def chat(msg):
     global dictionary,pending,pending_action,state,my_friend
     print(msg)              
     usermessage=txt_recog(msg)         
     if usermessage=='quit':
         my_friend.send(get_chatbotanswer('See you.'))
         sys.exit()
     intent=interprete(interpreter,usermessage)['intent']['name']
     entities=extract_entities(nlp,usermessage)
     Org=Check_Org(entities)
     intent_=(check_intents(intent))       
     dictionary,pending,pending_action,state=bot_reply(intent_,state,pending,Org,pending_action,dictionary)  
     if state==END:
         my_friend.send(get_chatbotanswer('See you.'))
         sys.exit()        
     action=pending_actions()       
     if pending is not 0:
         my_friend.send(get_chatbotanswer(action[pending_action])) 
     if state is not 0 and state is not 3 and state is not 5:
         my_friend.send(get_chatbotanswer(state_change_action(state)))
     if (dictionary['function'] is not None) and (dictionary['company']is not None):
         CPN=Stock(get_ticker_symbol(dictionary['company']))
         if dictionary['function']=='b':               
             if error_check1(CPN)==1:      
                 p_CPN=CPN.get_price()
                 state=FOUND
                 my_friend.send(get_chatbotanswer('Ok,I have found it! The price of {0} is {1}$'.format(dictionary['company'],p_CPN) ))
             else:     
                 my_friend.send(get_chatbotanswer('Information of company not found'))
                 state=NOTFOUND
         if dictionary['function']=='c':
             if error_check2(CPN)==1:                
                 mv_CPN=CPN.get_volume()
                 my_friend.send(get_chatbotanswer('Ok,I have found it!'))
                 state=FOUND
                 my_friend.send(get_chatbotanswer('The volume of {0} is {1}'.format(dictionary['company'],mv_CPN) ))
             else: 
                 
                 my_friend.send(get_chatbotanswer('Information of company not found'))
                 state=NOTFOUND            
         if dictionary['function']=='d':
             if error_check3(CPN)==1:                
                 mc_CPN=CPN.get_market_cap()
                 my_friend.send(get_chatbotanswer('Ok,I have found it!'))
                 state=FOUND
                 my_friend.send(get_chatbotanswer('The market value of {0} is {1}$'.format(dictionary['company'],mc_CPN)))  
             else:                    
                 my_friend.send(get_chatbotanswer('Information not found'))
                 state=NOTFOUND
     if state == FOUND or state==NOTFOUND :
         my_friend.send(get_chatbotanswer('Do you have other questions? Say "quit" to quit'))
         state=INIT
예제 #19
0
파일: models.py 프로젝트: 0x1A1-1/Stockify
    def get_list_price(self, code_list):

        # check if there is only one code in list
        if len(code_list) == 1:
            return self.get_price(code_list[0])

        # use list to directly query
        user_stocks = IEXStock(code_list)

        try:
            return user_stocks.get_price()
        except:
            return ("No saved stock in record")
예제 #20
0
def gap_up(ticker_list):

    for ticker in ticker_list:
        current_ticker = Stock(ticker)
        prev_high = current_ticker.get_previous()['high']
        print('prev high: ' + str(prev_high))
        current_open = current_ticker.get_ohlc()['open']['price']
        print('cur open: ' + str(current_open))

        if current_open - prev_high >= 4.0:
            gapUpList.append(ticker)

    print(gapUpList)
예제 #21
0
def gap_down(ticker_list):

    for ticker in ticker_list:
        current_ticker = Stock(ticker)
        prev_low = current_ticker.get_previous()['low']
        print('prev high: ' + str(prev_low))
        current_open = current_ticker.get_ohlc()['open']['price']
        print('cur open: ' + str(current_open))

        if prev_low - current_open <= 4.0:
            gapDownList.append(ticker)

    print(gapDownList)
예제 #22
0
def stock_pending(message):
    result = interpreter.parse(message)

    global stock_re
    global remember
    global flag
    global setting

    company = ''

    if 'open' in result.get('entities')[0].get('value'):
        if remember != '':
            company = remember
        else:
            company = result.get('entities')[1].get('value')
        for i in setting:
            if company in i.get('name'):
                company = i.get('symbol')
        open_price = Stock(company).get_open()
        stock_re = "The open price is {}".format(open_price)

    if 'close' in result.get('entities')[0].get('value'):
        if remember != '':
            company = remember
        else:
            company = result.get('entities')[1].get('value')
        for i in setting:
            if company in i.get('name'):
                company = i.get('symbol')
        close_price = Stock(company).get_price()
        stock_re = "The close price is {}".format(close_price)

    if 'volume' in result.get('entities')[0].get('value'):
        if remember != '':
            company = remember
        else:
            company = result.get('entities')[1].get('value')
        for i in setting:
            if company in i.get('name'):
                company = i.get('symbol')
        volume = Stock(company).get_volume()
        stock_re = "The volume is {}".format(volume)

    if result.get('entities')[0].get('entity') == 'company':
        stock_re = "Do you wanna look at open price, close price or volume?"
        remember = result.get('entities')[0].get('value')
        for i in setting:
            if remember in i.get('name'):
                remember = i.get('symbol')

    flag = True
예제 #23
0
def get_prices_in_range():
    with open('NDQTickers.csv') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            #print(row[0])
            if len(row[0]) > 4:
                continue
            else:
                ticker = Stock(row[0])
                price = ticker.get_price()
                if 10 < price < 250:
                    tickersInRange.append(row[0])
                    #print(row[0] + " " + str(ticker.get_price()))
    return tickersInRange
예제 #24
0
 def setup_class(self):
     self.share = Stock("AAPL")
     self.share2 = Stock("AAPL", output_format='pandas')
     self.share4 = Stock("AAPL",
                         json_parse_int=Decimal,
                         json_parse_float=Decimal)
     self.share5 = Stock("TSLA")
예제 #25
0
def CurrentData(ticker):
    try:
        equity = Stock('%s' % (ticker), output_format='pandas')
        df1 = equity.get_company(
        )  # gives basic company info like CEO, location, industry, etc.
        df2 = equity.get_earnings(
        )  # earnings per share (net income / shares outstanding) for past 4Q
        df3 = equity.get_financials(
        )  # basic financial metrics like revenue, gross profit, etc.
        df1.to_csv('company_info.csv')
        df2.to_csv('earnings.csv')
        df3.to_csv('financial_statements.csv')
    except ValueError:
        print('That ticker is not valid, choose another one!')
예제 #26
0
    def run(self, dispatcher, tracker, domain):

        company_x = tracker.get_slot('company')

        symbols = get_available_symbols()
        for i in range(len(symbols)):
            if company_x.lower() in symbols[i]["name"].lower():
                company = symbols[i]["symbol"]

        companyobj = Stock(company)
        price = companyobj.get_price()

        response = """{} shares is {} currently.""".format(company, price)
        dispatcher.utter_message(response)
        return [SlotSet('company', company)]
예제 #27
0
def pStock(symbol):
    priceCriteria = 5.00
    data = Stock(symbol)
    quote = data.get_quote()
    pe = quote['peRatio']
    close = quote['close']
    sts = data.get_key_stats()
    cName = sts['companyName']

    # apply criteria
    if close > priceCriteria:
        return

    # print the results for what is left
    print('%s,%s,%s,%s' % (symbol, cName, close, pe))
예제 #28
0
def get_ma(ticker):
	stock = Stock(ticker)
	start = now - timedelta(days=25)
	try:
		keyStats = stock.get_key_stats()
		if (stock.get_price() < 5):
			return -1,-1,-1
		
		df_hist = get_historical_data(ticker, start=start, end=now, output_format='pandas')
		dma50 = keyStats['day50MovingAvg']
		dma10 = df_hist.tail(10)['close'].mean()
		dma20 = df_hist.tail(20)['close'].mean()
	except:
		return -1,-1,-1
	
	return dma10, dma20, dma50
예제 #29
0
def get_stock(company_code):
	if not isinstance(company_code, str):
		raise TypeError('company_code should be a str.')
		return False
	
	stock_reader = Stock(company_code, output_format='json', session=cache_session)
	return stock_reader
예제 #30
0
def display_stocks():
    stocks = []
    userAmount = request.form['Amount']
    print(userAmount)
    strategiesPicked = request.form.getlist("strategies")
    print(strategiesPicked)
    s = Stock(userAmount, strategiesPicked)

    for s in strategiesPicked:
        stocks.append(data[s])

    stocks_list = [item for sublist in stocks for item in sublist]
    print(stocks_list)

    # Find the change percent for all the stocks
    stock_dict = {}

    for stock in stocks_list:
        ticker_symbol = data[stock]
        now = datetime.datetime.now()
        current_datetime = str(now.month) + " " + str(now.day) + " " + str(
            now.hour) + ":" + str(now.minute) + ":" + str(
                now.second) + " " + str(now.year)
        stock_info = requests.get('https://api.iextrading.com/1.0/stock/' +
                                  ticker_symbol + '/quote')

        if stock_info.status_code == 200:
            json_data = stock_info.json()
            changePercent = json_data['changePercent']
            stock_dict[stock] = changePercent

        else:
            print("Error: API not reachable!!")

    print(stock_dict)
예제 #31
0
def respond(message, params):
    entities = interpreter.parse(message)['entities']
    for ent in entities:
        params[ent["entity"]] = str(ent["value"])
    stock = Stock(params['symbol'])
    response, entity = intent(params, stock)
    return response, params, entity
예제 #32
0
class IEXSecurity:
    def __init__(self, ticker):
        self.ticker = ticker
        self.security = Stock(ticker)
        
    def get_price(self):
        return self.security.get_price()
예제 #33
0
 def setUp(self):
     stock = Stock(["GOOG", "TSLA"])
     self.company = stock.get_price()