예제 #1
0
def index():
    start_date = "2016-10-02"
    end_date = "2016-10-16"
    company = "AAPL"
    if request.method == 'POST':
        if len(request.form.get("company")) <= 4:
            topic_name = get_symbol(request.form.get("company").upper())
            company_stock_symbol = request.form.get("company").upper()
            company_stock_price = ystockquote.get_all(request.form.get("company").upper())["price"]
        else: 
        	topic_name = request.form.get("company").title()
        	company_stock_symbol = False
        	company_stock_price = False
        company = request.form.get("company")
        descriptions,articles_with_images = get_search_results(company)
        sentiments = get_sentiment_scores([x["description"] for x in descriptions])
        sentiment = sum(sentiments) / len(sentiments)

        # text_blob_sentiment = get_textblob_sentiment(descriptions)
        # print sum([x for x in text_blob_sentiment if x != 0]) / len(text_blob_sentiment)

        return render_template("index.html", company=company, topic_name=topic_name, symbol=company_stock_symbol, price=company_stock_price, sentiment=sentiment, imaged_articles=articles_with_images, startdate=start_date, enddate=end_date)
    company_stock_price = ystockquote.get_all(company)["price"]
    descriptions,articles_with_images = get_search_results(company)
    return render_template("index.html", imaged_articles=articles_with_images, price=company_stock_price, company=company, startdate=start_date, enddate=end_date)
예제 #2
0
    def get(self):
        stock_name = self.request.path[7:]
        # Checking if request is from valid user
        if 'HMAC' not in self.request.headers:
            self.request.headers['HMAC'] = None
        hmac_sign = self.request.headers['HMAC']
        if 'PKEY' not in self.request.headers:
            self.request.headers['PKEY'] = None
        public_key = self.request.headers['PKEY']
        data_dict = {'stock': stock_name}
        response = {}
        if not is_valid_user_request(hmac_sign,
                                     public_key,
                                     data_dict):
            response['status'] = False
            response['unathorized'] = True
            self.response.out.write(json.dumps(response))
            return

        response["name"] = stock_name
        try:
            if len(stock_name) < 1:
                raise Exception()
            details = ystockquote.get_all(stock_name)
            response["status"] = True
            response["details"] = details
        except:
            response["status"] = False
        self.response.out.write(json.dumps(response))
예제 #3
0
 def test_get_all_alignment(self):
     """ Compare bulk 'all_info' values to individual values.
     Currently broken due to misalignment from invalid CSV in
     fields: f6, k3, and maybe j2, a5, b6.
     """
     symbol = 'GOOG'
     all_info = ystockquote.get_all(symbol)
     self.assertIsInstance(all_info, dict)
     self.assertEquals(
         all_info['previous_close'],
         ystockquote.get_previous_close(symbol))
     self.assertEquals(
         all_info['volume'],
         ystockquote.get_volume(symbol))
     self.assertEquals(
         all_info['bid_realtime'],
         ystockquote.get_bid_realtime(symbol))
     self.assertEquals(
         all_info['ask_realtime'],
         ystockquote.get_ask_realtime(symbol))
     self.assertEquals(
         all_info['last_trade_price'],
         ystockquote.get_last_trade_price(symbol))
     self.assertEquals(
         all_info['today_open'],
         ystockquote.get_today_open(symbol))
     self.assertEquals(
         all_info['todays_high'],
         ystockquote.get_todays_high(symbol))
     self.assertEquals(
         all_info['last_trade_date'],
         ystockquote.get_last_trade_date(symbol))
예제 #4
0
    def percent_change(self):
        tick_data = []
        repull_all = raw_input("Would you like to pull ticker data? (Y/N): ")
        ask_print = raw_input("Show after pull? (Y/N): ")
        if "y" in repull_all:
            pbar = ProgressBar()
            for ticker in pbar(self.ticker_list):
                # print str(ticker_list.index(ticker) + 1) + ' / ' + str(len(ticker_list)) + '  ' + str((float(ticker_list.index(ticker) + 1) / len(ticker_list))) + '%'

                try:
                    tick_data = ysq.get_all(ticker)
                    percentage = (
                        float(tick_data["change"]) / (float(tick_data["price"]) - float(tick_data["change"]))
                    ) * 100

                    if percentage > 0:
                        self.rising.append([ticker, tick_data["price"]])
                    if percentage > 3:
                        self.rising_three.append([ticker, tick_data["price"]])
                    if percentage < 0:
                        self.dipping.append([ticker, tick_data["price"]])
                    if percentage < -3:
                        self.dipping_three.append([ticker, tick_data["price"]])

                except Exception, e:
                    # print "Data Pull Error For: " + str(ticker)
                    self.error_list.append(ticker)
                    pass
            self.write_cache()
예제 #5
0
def handle(text, mic, profile):
    """
        Responds to user-input, typically speech text, with a summary of
        the day's top news headlines, sending them to the user over email
        if desired.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """
    mic.say("Getting Stock Info")
    try:
        output = ''
        for symbol in profile['stocks']:
            print symbol
            stock_info = ys.get_all(symbol)
            print stock_info
            current_out = symbol + " Current Price is " + stock_info['price'] + \
            " with a daily change of " + stock_info['change'] + " ... "
            print current_out
            output = output + current_out
        mic.say(output)
    except:
        mic.say("Error retrieving stocks")
예제 #6
0
def compact_quote(symbol):
    a = y.get_all(symbol)
    try:
        L52 = int(round(float(a['fifty_two_week_low']), 0))
    except ValueError:
        L52 = '_'
    try:
        P = round(float(a['price']), 1)
    except ValueError:
        P = '_'
    try:
        C = a['change']
    except ValueError:
        C = '_'
    try:
        H52 = int(round(float(a['fifty_two_week_high']), 0))
    except ValueError:
        H52 = '_'
    try:
        PE = round(float(a['price_earnings_ratio']), 1)
    except ValueError:
        PE = '_'
    try:
        Cp = int(round(float(C) / float(P) * 100))
    except ValueError:
        Cp = '_'
    return '{} {} {}% [{} {}] PE {}'.format(symbol, P, Cp, L52, H52, PE)[0:31]
예제 #7
0
 def test_get_all(self):
     symbol = 'GOOG'
     all_info = ystockquote.get_all(symbol)
     self.assertIsInstance(all_info, dict)
     pc = all_info['previous_close']
     self.assertNotEqual(pc, 'N/A')
     self.assertGreater(float(pc), 0)
def get_fundamental_data(stock: str) -> dict:
    """
    Gets fundamental Data from yahoo finance. Some fundamentals and a lot af real-live prices.
    Enter a starting point and an endpoint as args after entering the symbol of a stock or an index. 
    The result will look like this:

      avg_daily_volume: 17735800,
      book_value: 9.33,
      change: -0.13,
      dividend_per_share: 0.12,
      dividend_yield: 1.23,
      earnings_per_share: -0.44,
      ebitda: 2.63B,
      fifty_day_moving_avg: 10.28,
      fifty_two_week_high: 11.50,
      fifty_two_week_low: 6.14,
      market_cap: 12.35B,
      price: 9.39,
      price_book_ratio: 1.02,
      price_earnings_growth_ratio: 2.50,
      price_earnings_ratio: N/A,
      price_sales_ratio: 0.59,
      short_ratio: 8.07,
      stock_exchange: "NYQ",
      two_hundred_day_moving_avg: 9.91,
      volume: 15300774},  

    """
    try:
        return ystockquote.get_all(stock)
    except:
        print("Something went wrong!")
예제 #9
0
def fetchQuotes(sym, start=FROM_DATE, end=CURRENT_DATE):
    his = None
    data = None
    try:
        # print start, end
        data = ystockquote.get_historical_prices(sym, start, end)
    except Exception:
        print "Please check the dates. Data might not be available. 404 returned"

        # 404 due to data yet not available
    if data:
        his = DataFrame(collections.OrderedDict(sorted(data.items()))).T
        his = his.convert_objects(convert_numeric=True)
        his.index = pd.to_datetime(his.index)
        his.insert(0, 'symbol', sym, allow_duplicates=True)
        # insert the date as dataframe too
        his.insert(1, 'date', his.index)
        # his.columns = getColumns('stock_quote_historical')   # Removing as db dependency is removed
        his.columns = getColumnsNoSql('stock_quote_historical')

    daily = ystockquote.get_all(sym)
    # print daily
    # persist(his, daily, sym, end)

    return his, daily
예제 #10
0
def banner():
    d = feedparser.parse('http://weather.yahooapis.com/forecastrss?w=9807&u=c')
    temp = d['feed'][u'yweather_location']['city'] + ': ' + d['entries'][0][u'yweather_condition']['text'] + ' ' + \
           d['entries'][0][u'yweather_condition']['temp'] + 'C'
    s = ystockquote.get_all('abt.to')
    stock = ['Abt: $' + s['price'], 'Change: ' + s['change'], temp]
    return stock
예제 #11
0
파일: stock.py 프로젝트: kiddzero/williebot
def stock(bot, trigger):
  if not trigger.group(2):
    bot.reply("Please enter a stock ticker. Ex. TWTR")
  else:
    ticker = trigger.group(2).upper()
    s = ystockquote.get_all(ticker)
    bot.reply("%s %s, Price: $%s, Change: %s, Volume: %s, 52 Week High: $%s. " % (ticker, s['stock_exchange'], s['price'], s['change'], s['volume'], s['52_week_high']))
예제 #12
0
def main():
    # ticker_file = "input/tickers.txt"
    # bucket_name = "edgarsentimentbucket"

    # conn = S3Connection(argv[1], argv[2])
    # path_bucket = conn.get_bucket(bucket_name)
    # k = Key(path_bucket)
    # k.key = ticker_file
    # pathfile = k.get_contents_as_string()
    # try:
    #     lines = pathfile.split('\n')
    # except AttributeError:
    #     lines = pathfile

    
    try:
        print "started"
        # for linie in open(ticker_file, "r"):
        for linie in sys.stdin:
            try:
                print linie
                ticker_arr = linie.split('\t')
                curr_ticker = ticker_arr[1]
                curr_cik = ticker_arr[2]
                curr_date = ticker_arr[3]
                if not '-' in curr_date:
                    curr_date = curr_date[0:4] + '-' + curr_date[4:6] + '-' + curr_date[6:8]
                curr_date = curr_date.strip()
                curr_date_obj = crteDateObj(curr_date)
                yest_date_obj = curr_date_obj - timedelta(days=1)
                yest_date = crteDateStr(yest_date_obj)
                try:
                    price_dict = ystockquote.get_historical_prices(curr_ticker, yest_date, curr_date)
                    curr_close = price_dict[curr_date]['Close']
                    curr_adj_close = price_dict[curr_date]['Adj Close']
                    curr_open = price_dict[curr_date]['Open']
                    yest_close = price_dict[yest_date]['Close']
                    yest_adj_close = price_dict[yest_date]['Adj Close']
                    yest_open = price_dict[yest_date]['Close']
                except:
                    curr_close = "NA"
                    curr_adj_close = "NA"
                    curr_open = "NA"
                    yest_close = "NA"
                    yest_adj_close = "NA"
                    yest_open = "NA"

                try:
                    all_dict = ystockquote.get_all(curr_ticker)
                    curr_mkt_cap = all_dict['market_cap']
                except:
                    curr_mkt_cap = "NA"

                print curr_ticker + '\t' + curr_cik + '\t' + curr_date + '\t' + curr_open + '\t' + \
                 curr_close + '\t' + curr_adj_close + '\t' + yest_open + '\t' + yest_close + '\t' + \
                 yest_adj_close + '\t' + curr_mkt_cap
            except:
                print "bad"
    except:
        print "didn't start"
예제 #13
0
 def getStockLine (self, stocks):
     stock_list = stocks.split()
     stockLine = ""
     for stock in stock_list:
         stockData = ystockquote.get_all(stock)
         stockLine += stock + '[' + stockData['price'] + '/' + stockData['change'] + "] "
     return stockLine
예제 #14
0
 def get_quote(self):
     if self.quote is None:
         try:
             self.quote = ystockquote.get_all(self.symbol)
         except:
             self.quote = None
     return self.quote
예제 #15
0
def fetchQuotes(sym, start=FROM_DATE, end=CURRENT_DATE):
    his = None
    data = None
    try:
        # print start, end
        data = ystockquote.get_historical_prices(sym, start, end)
    except Exception:
        print "Please check the dates. Data might not be available. 404 returned"

        # 404 due to data yet not available
    if data:
        his = DataFrame(collections.OrderedDict(sorted(data.items()))).T
        his = his.convert_objects(convert_numeric=True)
        his.index = pd.to_datetime(his.index)
        his.insert(0, 'symbol', sym, allow_duplicates=True)
        # insert the date as dataframe too
        his.insert(1, 'date', his.index)
        # his.columns = getColumns('stock_quote_historical')   # Removing as db dependency is removed
        his.columns = getColumnsNoSql('stock_quote_historical')

    daily = ystockquote.get_all(sym)
    # print daily
    # persist(his, daily, sym, end)

    return his, daily
예제 #16
0
 def test_get_all(self):
     symbol = 'GOOG'
     all_info = ystockquote.get_all(symbol)
     self.assertIsInstance(all_info, dict)
     pc = all_info['previous_close']
     self.assertNotEqual(pc, 'N/A')
     self.assertGreater(float(pc), 0)
예제 #17
0
    def addRow(self, stockSym):
        self.sysmTextIn.delete(0, END)
        searchterms = [('Symbol', stockSym.upper(), '=', 'AND')]
        symbolCol = self.model.getColumnData(columnIndex=self.model.getColumnIndex(columnName="Symbol"),
                                             columnName="Symbol", filters=searchterms)
        if stockSym.upper() in symbolCol:
            return
        result = ystockquote.get_all(stockSym.upper())

        row = Rows(result, stockSym.upper())
        dictrow = row.getRow()
        colIndex = self.model.getColumnIndex(columnName="Symbol")
        stockSym = self.model.getValueAt(rowIndex=0, columnIndex=colIndex)
        if stockSym == " ":
            row0 = self.table.getSelectedRow()
            self.model.deleteRow(row0)
            self.table.setSelectedRow(row0-1)
            self.table.clearSelected()
        else:
            self.currentRow = self.currentRow + 1
        self.model.importDict({ "%s%d" % ("rec", self.currentRow) : dictrow})
        change = float(dictrow['Change'])
        if change > 0:
            self.model.setColorAt(rowIndex=self.model.getRecordIndex("%s%d" % ("rec", self.currentRow)),
                                  columnIndex=self.model.getColumnIndex(columnName="Change"),color="green", key="fg") 
            self.model.setColorAt(rowIndex=self.model.getRecordIndex("%s%d" % ("rec", self.currentRow)),
                                  columnIndex=self.model.getColumnIndex(columnName="%Change"),color="green", key="fg")
        if change < 0:
            self.model.setColorAt(rowIndex=self.model.getRecordIndex("%s%d" % ("rec", self.currentRow)),
                                  columnIndex=self.model.getColumnIndex(columnName="Change"),color="red", key="fg") 
            self.model.setColorAt(rowIndex=self.model.getRecordIndex("%s%d" % ("rec", self.currentRow)),
                                  columnIndex=self.model.getColumnIndex(columnName="%Change"),color="red", key="fg")
        self.table.redrawTable()
        self.after(5000, self.updateTableValue, "%s%d" % ("rec", self.currentRow))
예제 #18
0
 def getStockLine(self, stocks):
     stock_list = stocks.split()
     stockLine = ""
     for stock in stock_list:
         stockData = ystockquote.get_all(stock)
         stockLine += stock + '[' + stockData['price'] + '/' + stockData[
             'change'] + "] "
     return stockLine
예제 #19
0
 def test_get_all_multiple(self):
     symbols = ['GOOG', 'TSLA']
     all_info = ystockquote.get_all(symbols)
     self.assertIsInstance(all_info, list)
     for row in all_info:
         self.assertIsInstance(row, dict)
         pc = row['previous_close']
         self.assertNotEqual(pc, 'N/A')
         self.assertGreater(float(pc), 0)
예제 #20
0
def main():
  args = parse_args()
  if args.startDate and args.endDate:
    values = get_historical_prices(
        args.symbol, args.startDate, args.endDate).items()
  else:
    values = get_all(args.symbol).items()
  for val in sorted(values):
    print val
예제 #21
0
 def yahoo(symbols):
   """
      Downloads the latest quote for the given symbols
   """
   all = None
   try:
     return ystockquote.get_all(symbols)
   except Exception, e:
     logging.error('Could not download quote %s:%s', symbols, e)
     return None
예제 #22
0
def main(tickers):
	for ticker in tickers:
		allInfo = ystockquote.get_all(ticker)
		print ticker + ":Exchange=" + allInfo["stock_exchange"] \
		+ ":Cap=" + allInfo["market_cap"] \
		+ ":P-Earn=" + allInfo["price_earnings_ratio"] \
		+ ":P-Sales=" + allInfo["price_sales_ratio"] \
		+ ":Range52=" + allInfo["fifty_two_week_low"] \
		+ "-" + allInfo["fifty_two_week_high"] \
		+ ":Price=" + allInfo["price"]
예제 #23
0
def get_ticks():        
    print "%(1)s %(2)s %(3)s %(4)s %(5)s %(6)s" % {"1" : "SYMBOLS".ljust(12), "2" : "Price".rjust(8), "3" : "Change".rjust(8), "4" : "Bought".rjust(8), "5" : "Vol(%)".rjust(8), "6" : "Action".ljust(5)}
    for stock in stocks:
        data= ystockquote.get_all(stock[1])
        prices.append((stock[0], data['price']))
        thisprices = []
        for price in prices:
            if price[0] == stock[0]:
                thisprices.append(float(price[1]))

        thisprevsma = data['price']        
        for price in prevsma:
            if price[0] == stock[0]:
                thisprevsma=price[1]

        thisprevema = data['price']        
        for price in prevema:
            if price[0] == stock[0]:
                thisprevema=price[1]
        bar =len(thisprices)-1
        currentsma = running_sma(bar, thisprices, 3, float(thisprevsma))
        currentema = ema(bar, thisprices, period, float(thisprevema), smoothing=None)

        Hit = False
        for i,value in enumerate(prevsma):
            if prevsma[i] == stock[0]:
                Hit=True
                prevsma[i] = currentsma

        if Hit==False:
             prevema.append((stock[0], currentsma))

        Hit = False
        for i,value in enumerate(prevema):
            if prevema[i] == stock[0]:
                Hit=True
                prevema[i] = currentema

        if Hit==False:
             prevema.append((stock[0], currentema))
        action = ""
        if float(currentsma) > float(currentema) :
            action = "long"
        elif float(currentema) > float(currentsma) :
            action = "short"
        
        vol=0
        
        if float(data['volume']) > 0 and float(data['avg_daily_volume']) > 0:
            vol = "{0:.2f}".format((float(data['volume']) /float(data['avg_daily_volume']))*100)

        color=Color_It(data['price'], stock[2])
        print colored("%(1)s %(2)s %(3)s %(4)s %(5)s %(6)s" % {"1" : stock[0].ljust(12), "2" : data['price'].rjust(8), "3" : data['change'].rjust(8), "4" : str(stock[2]).rjust(8), "5" : str(vol).rjust(8), "6" : action.ljust(5)}, color)
예제 #24
0
def main(argv):
    ticker_file = "input/tickers.txt"
    bucket_name = "edgarsentimentbucket"

    conn = S3Connection(argv[1], argv[2])
    path_bucket = conn.get_bucket(bucket_name)
    k = Key(path_bucket)
    k.key = ticker_file
    pathfile = k.get_contents_as_string()
    try:
        lines = pathfile.split('\n')
    except AttributeError:
        lines = pathfile

    for linie in lines:
        try:
            ticker_arr = linie.split('\t')
            curr_ticker = ticker_arr[0]
            curr_cik = ticker_arr[1]
            curr_date = ticker_arr[2]
            if not '-' in curr_date:
                curr_date = curr_date[0:4] + '-' + curr_date[
                    4:6] + '-' + curr_date[6:8]
            curr_date_obj = crteDateObj(curr_date)
            yest_date_obj = curr_date_obj - timedelta(days=1)
            yest_date = crteDateStr(yest_date_obj)
            try:
                price_dict = ystockquote.get_historical_prices(
                    curr_ticker, yest_date, curr_date)
                curr_close = price_dict[curr_date]['Close']
                curr_adj_close = price_dict[curr_date]['Adj Close']
                curr_open = price_dict[curr_date]['Open']
                yest_close = price_dict[yest_date]['Close']
                yest_adj_close = price_dict[yest_date]['Adj Close']
                yest_open = price_dict[yest_date]['Close']
            except:
                curr_close = "NA"
                curr_adj_close = "NA"
                curr_open = "NA"
                yest_close = "NA"
                yest_adj_close = "NA"
                yest_open = "NA"

            try:
                all_dict = ystockquote.get_all(curr_ticker)
                curr_mkt_cap = all_dict['market_cap']
            except:
                curr_mkt_cap = "NA"
            print curr_ticker + '\t' + curr_cik + '\t' + curr_date + '\t' + curr_open + '\t' + \
             curr_close + '\t' + curr_adj_close + '\t' + yest_open + '\t' + yest_close + '\t' + \
             yest_adj_close + '\t' + curr_mkt_cap
        except:
            pass
예제 #25
0
파일: main.py 프로젝트: beatty/marketdash
	def get_cached_quote(self, symbol):
		key = "quote_" + symbol
		valstr = memcache.get(key)

		if valstr is None:
			fullquote = None
			try:
				fullquote = ystockquote.get_all(symbol)
				valstr = "%s,%s,%s,%s,%s,%s" % (fullquote['price'], fullquote['52_week_high'], fullquote['52_week_low'], fullquote['50day_moving_avg'], fullquote['200day_moving_avg'], fullquote['change'])
				memcache.add(key, valstr, 60*10)
			except Exception, e:
				logging.error('error retrieving quote for %s (%s)', symbol, e)
예제 #26
0
def compact_quote(symbol):
    symbol = 'SYK'
    a = y.get_all(symbol)

    L52 = int(round(float(a['fifty_two_week_low']), 0))
    P = round(float(a['price']), 1)
    C = a['change']
    H52 = int(round(float(a['fifty_two_week_high']), 0))
    PE = round(float(a['price_earnings_ratio']), 1)
    Cp = int(round(float(C) / float(P) * 100))

    return '{} {} {}% [{} {}] PE {}'.format(symbol, P, Cp, L52, H52, PE)
예제 #27
0
파일: Account.py 프로젝트: kirpen/TraderNet
 def get_bid(self, symbol):
     try:
         bid = yt.get_all(symbol)['bid_realtime']
     except:
         bid = 'No data available'
     if bid == 'N/A':
         print 'THE MARKET IS CLOSED - NO SALE POSSIBLE'
         return -1
     elif bid == 'No data available':
         print bid
         return -1
     else:
         return float(bid)
예제 #28
0
파일: Account.py 프로젝트: kirpen/TraderNet
 def get_ask(self, symbol):
     try:
         ask = yt.get_all(symbol)['ask_realtime']
     except:
         ask = 'No data available'
     if ask == 'N/A':
         print 'THE MARKET IS CLOSED - NO PURCHASE POSSIBLE'
         return -1
     elif ask == 'No data available':
         print ask
         return -1
     else:
         return float(ask)
예제 #29
0
    def test_get_all(self):
        symbol = 'GOOG'
        all_info = ystockquote.get_all(symbol)
        self.assertIsInstance(all_info, dict)

        self.assertEqual(all_info['dividend_yield'],
                         ystockquote.get_dividend_yield(symbol))
        self.assertEqual(all_info['fifty_sma'],
                         ystockquote.get_50_sma(symbol))
        self.assertEqual(all_info['company_name'],
                         ystockquote.get_company_name(symbol))
        self.assertEqual(all_info['book_value'],
                         ystockquote.get_book_value(symbol))
예제 #30
0
 def get_bid(self, symbol):
     try:
         bid = yt.get_all(symbol)['bid_realtime']
     except:
         bid = 'No data available'
     if bid=='N/A':
         print 'THE MARKET IS CLOSED - NO SALE POSSIBLE'
         return -1
     elif bid == 'No data available':
         print bid
         return -1
     else:
         return float(bid)
예제 #31
0
def main(argv):
    ticker_file = "input/tickers.txt"
    bucket_name = "edgarsentimentbucket"

    conn = S3Connection(argv[1], argv[2])
    path_bucket = conn.get_bucket(bucket_name)
    k = Key(path_bucket)
    k.key = ticker_file
    pathfile = k.get_contents_as_string()
    try:
        lines = pathfile.split('\n')
    except AttributeError:
        lines = pathfile

    for linie in lines:
        try:
            ticker_arr = linie.split('\t')
            curr_ticker = ticker_arr[0]
            curr_cik = ticker_arr[1]
            curr_date = ticker_arr[2]
            if not '-' in curr_date:
                curr_date = curr_date[0:4] + '-' + curr_date[4:6] + '-' + curr_date[6:8]
            curr_date_obj = crteDateObj(curr_date)
            yest_date_obj = curr_date_obj - timedelta(days=1)
            yest_date = crteDateStr(yest_date_obj)
            try:
                price_dict = ystockquote.get_historical_prices(curr_ticker, yest_date, curr_date)
                curr_close = price_dict[curr_date]['Close']
                curr_adj_close = price_dict[curr_date]['Adj Close']
                curr_open = price_dict[curr_date]['Open']
                yest_close = price_dict[yest_date]['Close']
                yest_adj_close = price_dict[yest_date]['Adj Close']
                yest_open = price_dict[yest_date]['Close']
            except:
                curr_close = "NA"
                curr_adj_close = "NA"
                curr_open = "NA"
                yest_close = "NA"
                yest_adj_close = "NA"
                yest_open = "NA"

            try:
                all_dict = ystockquote.get_all(curr_ticker)
                curr_mkt_cap = all_dict['market_cap']
            except:
                curr_mkt_cap = "NA"
            print curr_ticker + '\t' + curr_cik + '\t' + curr_date + '\t' + curr_open + '\t' + \
             curr_close + '\t' + curr_adj_close + '\t' + yest_open + '\t' + yest_close + '\t' + \
             yest_adj_close + '\t' + curr_mkt_cap
        except:
            pass
예제 #32
0
 def get_ask(self, symbol):
     try:
         ask = yt.get_all(symbol)['ask_realtime']
     except:
         ask = 'No data available'
     if ask=='N/A':
         print 'THE MARKET IS CLOSED - NO PURCHASE POSSIBLE'
         return -1
     elif ask == 'No data available':
         print ask
         return -1
     else:
         return float(ask)
     return 26.78
예제 #33
0
 def run_sim(self,user_money,stock,price_new):
     allInfo = ystockquote.get_all(tickerSymbol)
     price_old = float(allInfo["price"])
     time.sleep(0.3)
     allInfo = ystockquote.get_all(tickerSymbol)
     price_new = float(allInfo["price"])
     print price_new
     if price_old > price_new:
         if user_money > (2*price_new):
             stock += 2
             user_money = user_money - (2 * price_new)
     if price_old < price_new:
         if stock > 0:
             stock -= 1
             user_money = user_money + price_new
 
     else:
         pass
     print "I'm still running!"
     self.balance = Label(self, text = ("Balance: $", user_money))
     self.stock = Label(self, text = ("Stock:", stock))
     self.price = Label(self, text = ("Price:", price_new))
     self.after(2000, self.run_sim(user_money,stock,price_new))
예제 #34
0
def prices(symbol):
    """
     Downloads and stores the latest quote for the given symbol
  """

    all = ystockquote.get_all(symbol)
    try:
        download.insert(
            symbol,
            datetime.strptime(all['date'], '"%m/%d/%Y"').strftime('%Y-%m-%d'),
            all['price'], all['high'], all['low'], all['open'])
    except IntegrityError:
        print "Quote for %s already stored" % symbol
    except ValueError:
        print "Quote for %s could not be downloaded" % symbol
예제 #35
0
def get_keystats():
    import ystockquote
    fi = open('keystats.csv','w')
    for sym in get_sp500()[:]:
        sym = correctYahoo(sym)
        stats = ystockquote.get_all(sym)

        for k,v in stats.items():
            s = ';'.join([sym,k,v])
            print s
            fi.write(s + '\n')
        
    fi.close()

    '''
예제 #36
0
def get_morning_data():
    """Retrieve all data available from ystockquote for each known symbol. This
    data is classified by pickers and added to past data once evening prices
    are obtained.  This method should be run in the morning to allow pickers
    to make their picks."""
    current_data = {}
    for symbol in symbol_list:
        print(symbol)
        while True:
            try:
                current_data[symbol] = ys.get_all(symbol)
                break
            except:
                sleep(1)
    return current_data
예제 #37
0
def print_portfolios(args):
    header = []
    for h in ["SYM","PRICE","QTY", "VALUE", "COST PRICE", "COST", "CHANGE",
              "TOTAL_CHG","RETURN","% GAIN"]:
        header.append(colored(h,'magenta'))

    def colorize(val,comparator=lambda x:'red' if x<0 else 'green'):
        return colored(str(val),comparator(val))

    for name,portfolio in portfolios.items():
        myscrips = [
            header,]
        portfolio_mkt_val = 0
        portfolio_pur_val = 0
        portfolio_commision_cost = 0
        transaction_fee = 29
        print colored(name,'cyan')
        print "="*80
        for scrip in portfolio:
            script_details = yq.get_all(scrip['sym'])
            scrip_price = float(script_details['price'])
            portfolio_mkt_val+=scrip_price*scrip['qty']
            portfolio_pur_val+=scrip['value']*scrip['qty']
            portfolio_commision_cost += scrip['brokerage']
            cost = scrip['value']*scrip['qty']
            price = scrip_price*scrip['qty']
            total_change = (price)-(cost)
            returns = ((scrip_price*scrip['qty'])-(cost))-(scrip['brokerage']*2) 
            percentage_gain = (float(price-cost)/float(cost))*100.0
            myscrips.append([
                    colored(str(scrip['sym']),'white'),
                    colored(str(scrip_price),'white'),
                    colored(scrip['qty'],'white'),
                    colored(str(scrip_price*scrip['qty']),'white'),
                    colored(str(scrip['value']),'white'),
                    colored(cost,'white'),
                    colorize(scrip_price-scrip['value']),
                    colorize(total_change),
                    colorize(returns),
                    colorize('%.2f%%' %percentage_gain,lambda x:'red' if x.startswith('-') else 'green')
                    ]
                            )

        pprint_table(myscrips)
        print "Portfolio: %s (value) %s (cost)" % (portfolio_mkt_val+portfolio_commision_cost,portfolio_pur_val+portfolio_commision_cost)
        print "Mkt Gains: %s " % colorize(portfolio_mkt_val-portfolio_pur_val)
        print "Act Gains: %s " % colorize(portfolio_mkt_val-(portfolio_pur_val+portfolio_commision_cost))
        print "Total Commission:%s" % portfolio_commision_cost
예제 #38
0
 def fetch_stock_data(self):
  times = 1

  while times == 1:
   for ticker in self.stocks:
    data = ystockquote.get_all(ticker)
    data['ticker'] = ticker
    data['time_stamp'] = datetime.datetime.now()   
    self.save_stock_data(data)
	
    if data['volume'].isdigit() and data['price'].isdigit():    
     self.ts_volume.onSample(ticker, int( data['volume']))
     self.ts_price.onSample(ticker,float(data['price']))
    print('.'),
   print ''
   time.sleep(60)
예제 #39
0
def prices(symbol):
  """
     Downloads and stores the latest quote for the given symbol
  """
 
  all = ystockquote.get_all(symbol)
  try:
    download.insert(symbol, 
      datetime.strptime(all['date'], '"%m/%d/%Y"').strftime('%Y-%m-%d'),
      all['price'], 
      all['high'], 
      all['low'], 
      all['open'])
  except IntegrityError:
    print "Quote for %s already stored" % symbol
  except ValueError:
    print "Quote for %s could not be downloaded" % symbol
예제 #40
0
	def run(self):
		while not self.done:
			hour = str(datetime.datetime.now().time())[0:2]
			weekday = datetime.datetime.today().weekday()
			if hour == '16' and weekday in (0,1,2,3,4):
				self.account.getNetWorth()
			elif hour == '09' and weekday == 0:
				for stock in self.stockList:
					dataDict = ys.get_all(stock)
					if self.checkData(dataDict):
						sum = self.innerProd(dataDict)
						if sum > 103910000:
							self.buy(stock)
						if sum < 10391:
							self.sell(stock)
				time.sleep(3600)
			else:
				time.sleep(3600)
예제 #41
0
def show_news():
	display_date = time.strftime("%A %B %d")
	URL = 'https://www.google.com/finance/category_news?catid=TRBC%3A54&ei=khXDVOnREfCBsgfA7IHACw'
	response = requests.get(URL)
	soup = BeautifulSoup(response.content)
	story = {'title': None, 'link': None, 'ticker': None,'price':None,
         'market_cap':None,'avg_daily_vol':None,'eps':None,
         'fiftytwo_low':None,'fiftytwo_high':None,'exchange':None,
        'pe_ratio':None,'pe_growth_ratio':None,'short_ratio':None}
	stories = []
	for listing in soup.find_all('div',{'class':'g-section news sfe-break-bottom-16'}):
		headline = listing.find('span',{'class':'name'})
		clean = unicodedata.normalize('NFKD', headline.text).encode('ascii','ignore')
		stripped= clean.strip('\n')
		story['title'] = stripped
		story['link'] =headline.a['href']
		match = re.compile( "\((.*)\)" ).search(stripped)
		if match is not None:
			ticker = match.group(1)
			story['ticker'] = ticker
			if len(ticker)<6:
				ydata = ystockquote.get_all(ticker)
				story['price'] = ydata['price']
				story['exchange'] = ydata['stock_exchange']
				story['market_cap'] = ydata['market_cap']
				story['avg_daily_vol'] = ydata['avg_daily_volume']
				story['eps'] = ydata['earnings_per_share']
				story['fiftytwo_low'] = ydata['fifty_two_week_low']
				story['fiftytwo_high'] = ydata['fifty_two_week_high']
				story['pe_ratio'] = ydata['price_earnings_ratio']
				story['pe_growth_ratio'] = ydata['price_earnings_growth_ratio']
				story['short_ratio'] = ydata['short_ratio']
			else:
				story['ticker'] = None
		stories.append(story.copy())

	return render_template('index.html', estimates=stories, date = display_date)
예제 #42
0
    s.quit()


"""
Fetch data (from yahoo) and determine if this is a reversal indicator
"""
# yesterday's date
end = current_datetime - datetime.timedelta(days=1)
# 30 days ago from today
start = current_datetime - datetime.timedelta(days=30)

# fetch the historical data from yahoo
data = ystockquote.get_historical_prices('^' + SYMBOL,
                                         start.strftime("%Y-%m-%d"),
                                         end.strftime("%Y-%m-%d"))
all_data = ystockquote.get_all('^' + SYMBOL)

# validate that we have enough historical data to continue
if len(data) < days_back:
    print 'Not enough historical data available to continue (need at least 15 days of market data)'
    sys.exit(1)

current = ystockquote.get_last_trade_price('^' + SYMBOL)
open = float(all_data['today_open'])
high = float(all_data['todays_high'])
low = all_data['todays_low']

# if the current price is higher than the open and today is a new 15-day low,
# then this is a SELL indicator
if (isCurrentHigherThanOpen(current, open) & isNewLow(low, data)):
    #print 'today is a 15-day low (' + str(low) + ') & the current price (' + str(current) + ') is higher than the open (' + str(open) + ')'
예제 #43
0
def convert(x, from_symbol, to_symbol):
    from_symbol = from_symbol.upper()
    to_symbol = to_symbol.upper()
    
    from_type = identify_symbol(from_symbol)
    to_type = identify_symbol(to_symbol)
    
    y = None
    if from_symbol == to_symbol:
        return x
    
    if from_type is None:
        warn('converter: did not recognise from_symbol "%s", returning NaN!' % 
             from_symbol)
        return np.nan
    elif from_type == 'ISIN' or to_type == 'ISIN':
        warn('converter: cannot currently convert assets to or from ISIN, '
             'returning NaN!')
        return np.nan
    elif from_type == 'altcoin' or to_type == 'altcoin':
        warn('converter: cannot currently convert assets to or from altcoins, '
             'returning NaN!')
        return np.nan
    elif to_type is None:
        warn('converter: did not recognise to_symbol "%s", returning NaN!' % 
             to_symbol)
        return np.nan
    else:
        try:
            # from bitcoin to something
            if from_type == 'bitcoin':
                bconv = fx.bitcoin.BtcConverter()
                if to_type != 'currency':
                    x = bconv.convert_btc_to_cur(x, 'EUR')
                    y = convert(x, 'EUR', to_symbol)
                else:
                    y = bconv.convert_btc_to_cur(x, to_symbol)
                
            # from something to bitcoin
            elif to_type == 'bitcoin':
                if from_type != 'currency':
                    x = convert(x, from_symbol, 'EUR')
                    from_symbol = 'EUR'
                    
                bconv = fx.bitcoin.BtcConverter()
                y = bconv.convert_to_btc(x, from_symbol)
            
            # from stock/fund to something
            elif from_type == 'yahoo':
                from_groups = symbol_re.match(from_symbol).groups()
                stock_info = ystockquote.get_all(from_symbol)
                price = convert(float(stock_info['price']), 
                                currency_map[from_groups[1]], to_symbol)
                y = x * price
                
            # from something to stock/fund
            elif to_type == 'yahoo':
                to_groups = symbol_re.match(to_symbol).groups()
                stock_info = ystockquote.get_all(to_symbol)
                price = convert(float(stock_info['price']), 
                                currency_map[to_groups[1]], from_symbol)
                y = x / price
            
            # from currency to currency
            elif from_type == 'currency' and to_type == 'currency':
                cconv = fx.converter.CurrencyRates()
                y = cconv.convert(from_symbol, to_symbol, x)
                
        except Exception as err:
            warn('converter: unexpected error ({}) during conversion, '
                 'returning NaN!'.format(err))
            return np.nan
            
    if y is None:
        y = np.nan
        warn('converter: did not recognise one of the symbols, returning NaN!')
        
    return y
예제 #44
0
            #print colored(elem + ": " + price + " " + change, 'green')
    except Exception:
        print("Debug: Post Quote exception")
        pass
    # Quote on first line + price info on second line
    lcd.message(empty_space + quote + '\n' + empty_space + price + ' ' +
                change)

    for i in range(lcd_columns):
        time.sleep(0.35)
        lcd.move_left()

    return 0


##############################################################################

# Run in a loop
while 1:
    with open('/home/pi/StockQuote/quotelist') as f:
        tickerSymbol = f.read().splitlines()

    # parse the ticker symbol list for individual symbols and print out current price and change since previous days close.
    for elem in tickerSymbol:
        try:
            allInfo = ystockquote.get_all(elem)
        except Exception:
            print("Debug: Hit Exception...ignore")
            pass
        post_quote(elem, allInfo["price"], allInfo["change"])
예제 #45
0
 def test_get_all(self):
     all_info = ystockquote.get_all(self.symbol)
     self.assertIsInstance(all_info, dict)
     p = all_info['price']
     self.assertIsInstance(p, str)
     self.assertGreater(float(p), 0.0)
예제 #46
0
 def test_get_all(self):
     all_info = ystockquote.get_all(self.symbol)
     self.assertIsInstance(all_info, dict)
     p = all_info['dividend_yield']
     self.assertIsInstance(p, str)
예제 #47
0
def main():
    # ticker_file = "input/tickers.txt"
    # bucket_name = "edgarsentimentbucket"

    # conn = S3Connection(argv[1], argv[2])
    # path_bucket = conn.get_bucket(bucket_name)
    # k = Key(path_bucket)
    # k.key = ticker_file
    # pathfile = k.get_contents_as_string()
    # try:
    #     lines = pathfile.split('\n')
    # except AttributeError:
    #     lines = pathfile

    try:
        print "started"
        # for linie in open(ticker_file, "r"):
        for linie in sys.stdin:
            try:
                print linie
                ticker_arr = linie.split('\t')
                curr_ticker = ticker_arr[1]
                curr_cik = ticker_arr[2]
                curr_date = ticker_arr[3]
                if not '-' in curr_date:
                    curr_date = curr_date[0:4] + '-' + curr_date[
                        4:6] + '-' + curr_date[6:8]
                curr_date = curr_date.strip()
                curr_date_obj = crteDateObj(curr_date)
                yest_date_obj = curr_date_obj - timedelta(days=1)
                yest_date = crteDateStr(yest_date_obj)
                try:
                    price_dict = ystockquote.get_historical_prices(
                        curr_ticker, yest_date, curr_date)
                    curr_close = price_dict[curr_date]['Close']
                    curr_adj_close = price_dict[curr_date]['Adj Close']
                    curr_open = price_dict[curr_date]['Open']
                    yest_close = price_dict[yest_date]['Close']
                    yest_adj_close = price_dict[yest_date]['Adj Close']
                    yest_open = price_dict[yest_date]['Close']
                except:
                    curr_close = "NA"
                    curr_adj_close = "NA"
                    curr_open = "NA"
                    yest_close = "NA"
                    yest_adj_close = "NA"
                    yest_open = "NA"

                try:
                    all_dict = ystockquote.get_all(curr_ticker)
                    curr_mkt_cap = all_dict['market_cap']
                except:
                    curr_mkt_cap = "NA"

                print curr_ticker + '\t' + curr_cik + '\t' + curr_date + '\t' + curr_open + '\t' + \
                 curr_close + '\t' + curr_adj_close + '\t' + yest_open + '\t' + yest_close + '\t' + \
                 yest_adj_close + '\t' + curr_mkt_cap
            except:
                print "bad"
    except:
        print "didn't start"
def lightsOut():
	# Turn off all the LEDs.
	if debug == 1:
		print ('Turning off all LEDs.')

	sense.clear()

def marketClosed():
	print "Stock Market Closed.", now
	lightsOut()
	time.sleep(60)

atexit.register(lightsOut)

if debug == 1:
	allInfo = ystockquote.get_all(tickerSymbol)
	print allInfo
# 	quote = ystockquote.get_change(tickerSymbol)
# 	print quote

# print tickerSymbol + " Price = " + allInfo["price"]
# print tickerSymbol + " Change = " + allInfo["change"]
# print allInfo["change"]

# print allInfo

getcontext().prec = 8

def getQuote(change):
	if debug == 1:
		print "Function getQuote"
예제 #49
0
        self.counter = counter
        self.target_value = target_value

    def run(self):
        print "Starting Polling"
        stock_polling(self.name, self.target_value)
        print "exiting polling"


def stock_polling(stock_name,target_value):
    while float(ystockquote.get_price(stock_name)) <= float(target_value):
        print "stock value not reached" + ystockquote.get_price(stock_name)
        time.sleep(60)
    print "yay - stock value at " + ystockquote.get_price(stock_name)



stock_name = raw_input('Enter the stock name: ')
stock_target = raw_input ('Enter the stock target price: ')
#email = raw_input('Enter your email address')

#stock_name = "AAPL"
#stock_target = "25"
print stock_name, stock_target

pprint.pprint(ystockquote.get_all(stock_name))
thread1 = StockPollingThread(1,stock_name,stock_target,1)
thread1.start()

sys.exit()
예제 #50
0
파일: test.py 프로젝트: lanlanzky/blog
#!/usr/bin/python
#coding=utf8

import ystockquote

#获取该股票所有信息
print ystockquote.get_all('GOOG')

#获取当前股价
print ystockquote.get_ask_realtime('GOOG')

#获取2012.11.22到2013.10.1历史报价
print ystockquote.get_historical_prices("GOOG", '2012.11.22', '2013.10.1')
예제 #51
0
 def getStockPrice(self):
     allInfo = ystockquote.get_all(self.name)
     return float(allInfo["price"])
예제 #52
0
#print("\nReading Dropbox account access token from external file...")
#access_token = open(access_token, "r")
#print("Done.")

# Link script to my Dropbox account
#dbx = dropbox.Dropbox('access_token')
#print("\nSuccessfully linked to Dropbox account.")

# Open file with data
data_file = open(data_file, "w")

# Dictionary for pure stock data
pure_stock_data = {}

# Save stock data to dictionary keys
pure_stock_data['ORCL'] = ystockquote.get_all('ORCL')
pure_stock_data['GOOG'] = ystockquote.get_all('GOOG')
pure_stock_data['FB'] = ystockquote.get_all('FB')
pure_stock_data['YHOO'] = ystockquote.get_all('YHOO')
pure_stock_data['MSFT'] = ystockquote.get_all('MSFT')
pure_stock_data['AAPL'] = ystockquote.get_all('AAPL')
pure_stock_data['BIDU'] = ystockquote.get_all('BIDU')
pure_stock_data['ATVI'] = ystockquote.get_all('ATVI')
pure_stock_data['ADBE'] = ystockquote.get_all('ADBE')

# Write data with ticker symbol label to file
data_file.write("ORCL:\n")
data_file.write(str(pure_stock_data.get('ORCL', "!")))

data_file.write("\n\nGOOG:\n")
data_file.write(str(pure_stock_data.get('GOOG', "!")))
예제 #53
0
def get_ticks():
    print "%(1)s %(2)s %(3)s %(4)s %(5)s %(6)s" % {
        "1": "SYMBOLS".ljust(12),
        "2": "Price".rjust(8),
        "3": "Change".rjust(8),
        "4": "Bought".rjust(8),
        "5": "Vol(%)".rjust(8),
        "6": "Action".ljust(5)
    }
    for stock in stocks:
        data = ystockquote.get_all(stock[1])
        prices.append((stock[0], data['price']))
        thisprices = []
        for price in prices:
            if price[0] == stock[0]:
                thisprices.append(float(price[1]))

        thisprevsma = data['price']
        for price in prevsma:
            if price[0] == stock[0]:
                thisprevsma = price[1]

        thisprevema = data['price']
        for price in prevema:
            if price[0] == stock[0]:
                thisprevema = price[1]
        bar = len(thisprices) - 1
        currentsma = running_sma(bar, thisprices, 3, float(thisprevsma))
        currentema = ema(bar,
                         thisprices,
                         period,
                         float(thisprevema),
                         smoothing=None)

        Hit = False
        for i, value in enumerate(prevsma):
            if prevsma[i] == stock[0]:
                Hit = True
                prevsma[i] = currentsma

        if Hit == False:
            prevema.append((stock[0], currentsma))

        Hit = False
        for i, value in enumerate(prevema):
            if prevema[i] == stock[0]:
                Hit = True
                prevema[i] = currentema

        if Hit == False:
            prevema.append((stock[0], currentema))
        action = ""
        if float(currentsma) > float(currentema):
            action = "long"
        elif float(currentema) > float(currentsma):
            action = "short"

        vol = 0

        if float(data['volume']) > 0 and float(data['avg_daily_volume']) > 0:
            vol = "{0:.2f}".format(
                (float(data['volume']) / float(data['avg_daily_volume'])) *
                100)

        color = Color_It(data['price'], stock[2])
        print colored(
            "%(1)s %(2)s %(3)s %(4)s %(5)s %(6)s" % {
                "1": stock[0].ljust(12),
                "2": data['price'].rjust(8),
                "3": data['change'].rjust(8),
                "4": str(stock[2]).rjust(8),
                "5": str(vol).rjust(8),
                "6": action.ljust(5)
            }, color)
예제 #54
0
#exemplo de utilizacao da biblioteca ystockquote

import ystockquote

print "Google share price: " + ystockquote.get_price('GOOG')
print "OGX share price: " + ystockquote.get_price('OGXP3.SA')
print "Petrobras share price: " + ystockquote.get_price('PETR4.SA')
print
print "Petrobras details"
print ystockquote.get_all('PETR4.SA')
예제 #55
0
# -*- coding: utf8 -*-
import ystockquote
# print(ystockquote.get_price_book("PETR4"))
# print(ystockquote.get_bid_realtime('GOOGL'))
print("Ola --- ooo989898")
v = ystockquote.get_all("RAPT4.sa")
p = v['price']
c = v['change']
print("Valor:")
print v
print("Preço: %s") % (str(p))
print("Oscilação: %s") % (str(c))
d = p + (c * -1)
print("Preço Fechamento: %s") % (str(d))
예제 #56
0
파일: stock.py 프로젝트: gaodaxing/python
def plot_price(name):
    f, axs = plt.subplots(4, 1, figsize=(8, 10))
    url = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + name + '/chartdata;type=quote;range=1d/csv'
    req = ystockquote.Request(url)
    resp = ystockquote.urlopen(url)
    content = resp.read().split('\n')[:-1]
    for n in range(len(content)):
        if content[n].find('previous_close') == 0:
            previous_close = float(content[n].replace('previous_close:', ''))
        if content[n].find(':') == -1:
            break
    content = content[n:]
    timestamp, close, high, low, open1, volume = array(
        [tmp.split(',') for tmp in content], dtype=float).T

    url = 'http://finance.yahoo.com/d/quotes.csv?s=' + name + '&f=aba5b6'
    req = ystockquote.Request(url)
    resp = ystockquote.urlopen(url)
    content = resp.read().split('\n')[0].split(',')
    ask, bid, askSize, bidSize = content

    # 1 day
    datime = [datetime.datetime.fromtimestamp(tmp) for tmp in timestamp]
    axs[0].plot(datime, open1)
    axs[0].plot([datime[0], datime[0] + datetime.timedelta(0, 23400)],
                previous_close * ones(2), ':')

    axs[0].grid('on')
    axs[0].set_xlim(datime[0], datime[0] + datetime.timedelta(0, 23400))

    # duo days
    for n, N in enumerate([30, 365, 1826]):
        datime = [
            datetime.datetime.now() + datetime.timedelta(days=i)
            for i in range(-N, 1)
        ]

        quote = ystockquote.get_historical_prices(
            name, datime[0].strftime('%Y-%m-%d'),
            datime[-1].strftime('%Y-%m-%d'))

        datime = sorted([
            datetime.datetime.strptime(tmp, '%Y-%m-%d')
            for tmp in quote.keys()
        ])
        quote = [quote[tmp]['Adj Close'] for tmp in sorted(quote)]
        axs[n + 1].plot(datime, quote)
        axs[n + 1].grid('on')
    for ax in axs:
        plt.setp(ax.xaxis.get_majorticklabels(), rotation=12)

    plt.subplots_adjust(left=0.06,
                        bottom=0.05,
                        right=0.95,
                        top=0.98,
                        wspace=0.05,
                        hspace=0.3)

    f.canvas.set_window_title(name)

    # bid
    axs[0].text(0.95,
                0.95,
                'bid: ' + bid + 'x' + bidSize + '   ' + 'ask: ' + ask + 'x' +
                askSize,
                verticalalignment='top',
                horizontalalignment='right',
                transform=axs[0].transAxes,
                fontsize=15)

    axs[0].text(0.70,
                0.80,
                str(close[-1]),
                verticalalignment='top',
                horizontalalignment='right',
                color='b',
                transform=axs[0].transAxes,
                fontsize=15)
    color = 'r' * int(close[-1] < previous_close) + 'g' * int(
        close[-1] > previous_close) + '0.5' * int(close[-1] == previous_close)

    axs[0].text(
        0.95,
        0.80,
        '%+-.2f' % (close[-1] - previous_close) + '  %+-.2f' %
        (float(close[-1] - previous_close) / float(previous_close) * 100) +
        '%',
        verticalalignment='top',
        horizontalalignment='right',
        color=color,
        transform=axs[0].transAxes,
        fontsize=15)

    # stuff
    all1 = ystockquote.get_all(name)
    print bcolors.Bold + name + ' ' + bcolors.Blue + str(
        close[-1]) + bcolors.ENDC
    if float(all1['change']) > 0:
        print bcolors.Green + all1['change'] + ' +' + '%.2f' % (
            float(close[-1] - previous_close) / float(all1['price']) *
            100) + '%' + bcolors.ENDC
    else:
        print bcolors.Red + all1['change'] + ' ' + '%.2f' % (
            float(close[-1] - previous_close) / float(all1['price']) *
            100) + '%' + bcolors.ENDC
    print '---------------------'
    #    pprint(all1)
    return close[-1]
예제 #57
0
 def __init__(self, symbol="TSLA"):
     self.symbol = symbol
     self.all_info = ystockquote.get_all(self.symbol)
예제 #58
0
 def collect_firmo(self):
     return ystockquote.get_all(self.symbol)