def download_exchange(symbol):
    exchange = ystockquote.get_stock_exchange(symbol)
    if exchange == '"NMS"' or exchange =='"NGM"' or exchange =='"NCM"':
        exchange = "XNAS"
    elif exchange == '"NYQ"':
        exchange = "XNYS"
    elif exchange == '"ASE"':
        exchange = "XASE"
    elif exchange == '"OBB"':
        exchange = "XOTC"
    elif exchange == '"PNK"':
        exchange = "PINX"
    else:
        print exchange
        return False
    return exchange
def download_exchange(symbol):
    exchange = ystockquote.get_stock_exchange(symbol)
    if exchange == '"NMS"' or exchange == '"NGM"' or exchange == '"NCM"':
        exchange = "XNAS"
    elif exchange == '"NYQ"':
        exchange = "XNYS"
    elif exchange == '"ASE"':
        exchange = "XASE"
    elif exchange == '"OBB"':
        exchange = "XOTC"
    elif exchange == '"PNK"':
        exchange = "PINX"
    else:
        print exchange
        return False
    return exchange
Exemple #3
0
def _main():

    for s in ["NA.TO", "XBB.TO", "NOU.V", "AP-UN.TO", "BRK-A", "AAPL"]:
        print("=============================================")
        print("s: {}".format(s))

        print("get_name: {}".format(ysq.get_name(s)))
        print("get_price: {}".format(ysq.get_price(s)))
        print("get_volume: {}".format(ysq.get_volume(s)))
        print("get_stock_exchange: {}".format(ysq.get_stock_exchange(s)))
        print("get_market_cap: {}".format(ysq.get_market_cap(s)))
        print("get_dividend_yield: {}".format(ysq.get_dividend_yield(s)))
        print("get_price_earnings_ratio: {}".format(
            ysq.get_price_earnings_ratio(s)))

        print("get_52_week_low: {}".format(ysq.get_52_week_low(s)))
        print("get_52_week_high: {}".format(ysq.get_52_week_high(s)))
        print("get_currency: {}".format(ysq.get_currency(s)))
def AddStockChangeToTickerList():
    TickerFile = 'C:\Users\Makaye\Desktop\Investment\Code\yahoo_stock_symbols_4.csv'
    OutTickerFile = 'C:\Users\Makaye\Desktop\Investment\Code\TickersNamesExhanges_4.csv'
    fid = open(TickerFile,'r')
#    fidOut = open(OutTickerFile,'w')    
    TickerList = fid.readlines() 
    Data = [];
    count = 0;
    N = len(TickerList)
    for i in TickerList:
        count = count + 1
        print str(count) + ':' + str(N)
        i = i.partition('\n')[0]
        i = i.split(',')
        Exh = ys.get_stock_exchange(i[0])        
        Data.append([i[0],i[1],Exh])
    fid.close()
    return Data
    WriteToFile(OutTickerFile,Data)
Exemple #5
0
    def add_stock(self, ticker, name=None, exchange=None, sector=None, industry=None):
        """ Add a stock to the stock database

        Add the stock to the symbols table and populate quotes table with all
        available historical quotes. If any of the optional parameters are left
        out, the corresponding information will be obtained from Yahoo!
        Finance.

        :param ticker: Stock ticker symbol
        :param name: (optional) Company/security name
        :param exchange: (optional) Exchange on which the security is traded
        :param sector: (optional) Company/security sector
        :param Industry (optional) Company/security industry
        """
        ticker = ticker.lower()
        if name is None:
            name = quotes.get_name(ticker)
        if exchange is None:
            exchange = quotes.get_stock_exchange(ticker)
        if sector is None:
            sector = quotes.get_sector(ticker)
        if industry is None:
            industry = quotes.get_industry(ticker)
        stock = Symbol(ticker, name, exchange, sector, industry)
        session = self.db.Session()

        if self.check_stock_exists(ticker,session):
            print "Stock %s already exists!" % (ticker.upper())
        else:
            print "Adding %s to database" % (ticker.upper())
            session.add(stock)
            q = self._download_quotes(ticker, date(1900,01,01), date.today())
            for quote in q:
                quote.Features = Indicator(quote.Id)
            session.add_all(q)
        session.commit()
        session.close()
        self.update_quotes(ticker)
 def test_get_stock_exchange(self):
     value = ystockquote.get_stock_exchange(self.symbol)
     self.assertIsInstance(value, str)
Exemple #7
0
 def test_get_stock_exchange(self):
     value = ystockquote.get_stock_exchange(self.symbol)
     self.assertIsInstance(value, str)
Exemple #8
0
					symbolList.append(letter)
				
				symbol = ''.join(str(e) for e in symbolList if e.isalpha()) #turn list of letters in symbol into string
				symbol.strip()
				
				summaryPage = requests.get('http://finance.yahoo.com/q/pr?s=' + symbol, stream=False)				
				
				d = summaryPage.content
				soup1 = BeautifulSoup(d)

				getSummary = soup1.find_all('p')

				price = str(ystockquote.get_price(symbol))
				change = str(ystockquote.get_change(symbol))
				volume = str(ystockquote.get_volume(symbol))
				stockExchange = str(ystockquote.get_stock_exchange(symbol))
				marketCap = str(ystockquote.get_market_cap(symbol))
				bValue = str(ystockquote.get_book_value(symbol))
				ebitda = str(ystockquote.get_ebitda(symbol))
				mvavg = str(ystockquote.get_200day_moving_avg(symbol))
				High = str(ystockquote.get_52_week_high(symbol))
				Low = str(ystockquote.get_52_week_low(symbol))
				
				commaData = []

				data=[price, change, volume, stockExchange, mvavg, bValue, ebitda, marketCap, High, Low]		


				for individData in data:
					commaInt = humanize.intcomma(individData)
					commaData.append(commaInt)
Exemple #9
0
def view_stock(request, ticker):
    if request.user.__class__.__name__ is 'CustomUser':
        c_user = get_object_or_404(CustomUser, pk=request.user.pk)
        account = Account.objects.get(user=c_user)
    else:
        account = False
    stock = get_object_or_404(Stock, ticker=ticker)

    companyName = stock.ticker
    companyName = companyName.upper()
    stock = Stock.objects.get(ticker=companyName)
    namer = "'" + companyName + "'"
    ystock = Share(companyName)
    the_price = ystock.get_price()

    regex = 'Business Summary</span></th><th align="right">&nbsp;</th></tr></table><p>(.+?)</p>'
    pattern = re.compile(regex)

    root_url = urllib.urlopen("http://finance.yahoo.com/q/pr?s=" +
                              companyName + "+Profile")
    htmltext = root_url.read()

    decoded_str = str(re.findall(pattern, htmltext)).decode("utf8")
    encoded_str = decoded_str.encode('ascii', 'ignore')
    stock.description = encoded_str
    stock.description = stock.description[:-2]
    stock.description = stock.description[2:]
    stock.book_value = ystockquote.get_book_value(companyName)
    stock.change = ystockquote.get_change(companyName)
    #stock.dividend_per_share = ystockquote.get_dividend_per_share(companyName)
    #stock.dividend_yield = ystockquote.get_dividend_yield(companyName)
    stock.ebitda = ystockquote.get_ebitda(companyName)
    stock.fifty_two_week_high = ystockquote.get_52_week_high(companyName)
    stock.fifty_two_week_low = ystockquote.get_52_week_low(companyName)
    stock.market_cap = ystockquote.get_market_cap(companyName)
    stock.short_ratio = ystockquote.get_short_ratio(companyName)
    stock.stock_exchange = ystockquote.get_stock_exchange(companyName)
    stock.volume = ystockquote.get_volume(companyName)
    stock.price = ystock.get_price()
    #yahoo_finance
    stock.average_daily_volume = ystock.get_avg_daily_volume()
    stock.earnings_per_share = ystock.get_price_earnings_ratio()
    stock.fifty_day_moving_avg = ystock.get_50day_moving_avg()
    stock.two_hundred_day_moving_avg = ystock.get_200day_moving_avg()
    stock.price_book_ratio = ystock.get_price_book()
    stock.last_sale = ystock.get_price()
    stock.price_earnings_growth_ratio = ystock.get_price_earnings_growth_ratio(
    )
    stock.price_earnings_ratio = ystock.get_price_earnings_ratio()
    stock.price_sales_ratio = ystock.get_price_sales()
    stock.save()

    vl = []
    acl = []
    hl = []
    ll = []
    cl = []
    ol = []
    days_list = []
    d = 0
    seven_days_ago = datetime.datetime.now() + datetime.timedelta(-30)
    today = datetime.datetime.now()
    days = ystockquote.get_historical_prices(
        'GOOGL', seven_days_ago.strftime("%Y-%m-%d"),
        today.strftime("%Y-%m-%d"))
    for day in days.keys():
        d += 1
        date_label = datetime.datetime.now() + datetime.timedelta(-d)
        days_list.append(date_label.strftime("%b-%d"))
        day_info = days.get(day)
        vol = int(day_info.get('Volume'))
        vl.append(vol)
        adjcl = float(day_info.get('Adj Close'))
        acl.append(adjcl)
        highs = float(day_info.get('High'))
        hl.append(highs)
        lows = float(day_info.get('Low'))
        ll.append(lows)
        closes = float(day_info.get('Close'))
        cl.append(closes)
        opens = float(day_info.get('Open'))
        ol.append(opens)

    volume = vl
    lows = ll
    opens = ol
    highs = hl
    averages = acl
    closes = cl
    days_l = days_list[::-1]
    context = RequestContext(
        request,
        dict(account=account,
             request=request,
             stock=stock,
             volume=volume,
             lows=lows,
             highs=highs,
             opens=opens,
             closes=closes,
             averages=averages,
             days_l=days_l))
    return render_to_response('scrapyr_app/stock.html', context=context)
Exemple #10
0
					symbolList.append(letter)
				
				symbol = ''.join(str(e) for e in symbolList if e.isalpha()) #turn list of letters in symbol into string
				symbol.strip()
				
				summaryPage = requests.get('http://finance.yahoo.com/q/pr?s=' + symbol, stream=False)				
				
				d = summaryPage.content
				soup1 = BeautifulSoup(d)

				getSummary = soup1.find_all('p')

				price = str(ystockquote.get_price(symbol))
				change = str(ystockquote.get_change(symbol))
				volume = str(ystockquote.get_volume(symbol))
				stockExchange = str(ystockquote.get_stock_exchange(symbol))
				marketCap = str(ystockquote.get_market_cap(symbol))
				bValue = str(ystockquote.get_book_value(symbol))
				ebitda = str(ystockquote.get_ebitda(symbol))
				mvavg = str(ystockquote.get_200day_moving_avg(symbol))
				High = str(ystockquote.get_52_week_high(symbol))
				Low = str(ystockquote.get_52_week_low(symbol))
				
				commaData = []

				data=[price, change, volume, stockExchange, mvavg, bValue, ebitda, marketCap, High, Low]		


				for individData in data:
					commaInt = humanize.intcomma(individData)
					commaData.append(commaInt)
Exemple #11
0
def view_stock(request, ticker):
    if request.user.__class__.__name__ is "CustomUser":
        c_user = get_object_or_404(CustomUser, pk=request.user.pk)
        account = Account.objects.get(user=c_user)
    else:
        account = False
    stock = get_object_or_404(Stock, ticker=ticker)

    companyName = stock.ticker
    companyName = companyName.upper()
    stock = Stock.objects.get(ticker=companyName)
    namer = "'" + companyName + "'"
    ystock = Share(companyName)
    the_price = ystock.get_price()

    regex = 'Business Summary</span></th><th align="right">&nbsp;</th></tr></table><p>(.+?)</p>'
    pattern = re.compile(regex)

    root_url = urllib.urlopen("http://finance.yahoo.com/q/pr?s=" + companyName + "+Profile")
    htmltext = root_url.read()

    decoded_str = str(re.findall(pattern, htmltext)).decode("utf8")
    encoded_str = decoded_str.encode("ascii", "ignore")
    stock.description = encoded_str
    stock.description = stock.description[:-2]
    stock.description = stock.description[2:]
    stock.book_value = ystockquote.get_book_value(companyName)
    stock.change = ystockquote.get_change(companyName)
    # stock.dividend_per_share = ystockquote.get_dividend_per_share(companyName)
    # stock.dividend_yield = ystockquote.get_dividend_yield(companyName)
    stock.ebitda = ystockquote.get_ebitda(companyName)
    stock.fifty_two_week_high = ystockquote.get_52_week_high(companyName)
    stock.fifty_two_week_low = ystockquote.get_52_week_low(companyName)
    stock.market_cap = ystockquote.get_market_cap(companyName)
    stock.short_ratio = ystockquote.get_short_ratio(companyName)
    stock.stock_exchange = ystockquote.get_stock_exchange(companyName)
    stock.volume = ystockquote.get_volume(companyName)
    stock.price = ystock.get_price()
    # yahoo_finance
    stock.average_daily_volume = ystock.get_avg_daily_volume()
    stock.earnings_per_share = ystock.get_price_earnings_ratio()
    stock.fifty_day_moving_avg = ystock.get_50day_moving_avg()
    stock.two_hundred_day_moving_avg = ystock.get_200day_moving_avg()
    stock.price_book_ratio = ystock.get_price_book()
    stock.last_sale = ystock.get_price()
    stock.price_earnings_growth_ratio = ystock.get_price_earnings_growth_ratio()
    stock.price_earnings_ratio = ystock.get_price_earnings_ratio()
    stock.price_sales_ratio = ystock.get_price_sales()
    stock.save()

    vl = []
    acl = []
    hl = []
    ll = []
    cl = []
    ol = []
    days_list = []
    d = 0
    seven_days_ago = datetime.datetime.now() + datetime.timedelta(-30)
    today = datetime.datetime.now()
    days = ystockquote.get_historical_prices("GOOGL", seven_days_ago.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d"))
    for day in days.keys():
        d += 1
        date_label = datetime.datetime.now() + datetime.timedelta(-d)
        days_list.append(date_label.strftime("%b-%d"))
        day_info = days.get(day)
        vol = int(day_info.get("Volume"))
        vl.append(vol)
        adjcl = float(day_info.get("Adj Close"))
        acl.append(adjcl)
        highs = float(day_info.get("High"))
        hl.append(highs)
        lows = float(day_info.get("Low"))
        ll.append(lows)
        closes = float(day_info.get("Close"))
        cl.append(closes)
        opens = float(day_info.get("Open"))
        ol.append(opens)

    volume = vl
    lows = ll
    opens = ol
    highs = hl
    averages = acl
    closes = cl
    days_l = days_list[::-1]
    context = RequestContext(
        request,
        dict(
            account=account,
            request=request,
            stock=stock,
            volume=volume,
            lows=lows,
            highs=highs,
            opens=opens,
            closes=closes,
            averages=averages,
            days_l=days_l,
        ),
    )
    return render_to_response("scrapyr_app/stock.html", context=context)
@author: Makaye
"""
import os
import ystockquote
StockNameList = 'C:\Users\Makaye\Desktop\Investment\Code\yahoo_stock_symbols_4.csv'
StockNameWithExchange = 'C:\Users\Makaye\Desktop\Investment\Code\TickersNamesExhanges_4.csv'
fid = open(StockNameList,'r')


Data = fid.readlines()
StockTicker = [day.split(',')[0] for day in Data]
StockName = [day.split(',')[1].split('\n')[0] for day in Data]
fid.close()

StockExh = [ystockquote.get_stock_exchange(tick) for tick in StockTicker]

fid = open(StockNameWithExchange,'w')

for i in range(0,len(StockTicker)):
    temp = StockTicker[i]+','+StockName[i]+','+StockExh[i]+'\n'
    fid.write(temp)
fid.close()
# Create the directories if needed
BaseDir =  'C:\Users\Makaye\Desktop\Investment\Stocks'   
start_date = '20100101'
end_date = '201101023'
for i in range(0,len(StockTicker)):
    CurExh = StockExh[i]   
    CurTick = StockTicker[i]
    CurDir= os.path.join(BaseDir,CurExh)
def test_ysq_get_stock_exchange(s):
    assert len(ysq.get_stock_exchange(s)) > 2
Exemple #14
-1
def data_type():
	print "From the list above, enter the data type you'd like to see"
	data = raw_input("> ")
	print "What stock would you like to see data on?"
	stock = raw_input("> ")
	if data == 'price' or data == 'Price':
		print ystockquote.get_price(stock)
	elif data == 'change' or data == 'Change':
		print ystockquote.get_change(stock)
	elif data == 'Volume' or data == 'volume':
		print ystockquote.get_avg_daily_vol(stock)
	elif data == 'exchange' or data == 'Exchange':
		print ystockquote.get_stock_exchange(stock)
	elif data == 'market cap' or data == 'Market cap' or data == 'Market Cap':
		print ystockquote.get_market_cap(stock)
	elif data == 'book value' or data == 'Book value' or data == 'Book Value':
		print ystockquote.get_book_value(stock)
	elif data == 'eps' or data == 'EPS':
		print ystockquote.get_earnings_per_share(stock)
	elif data == 'short ratio' or data == 'Short Ratio':
		print ystockquote.get_short_ratio(stock)
	elif data == 'dividend yield' or data == 'Dividend Yield' or data == 'div yield':
		print ystockquote.get_dividend_yield(stock)
	elif data == 'ebitda' or data == 'EBITDA':
		print ystockquote.get_ebitda(stock)
	else:
		print 'Sorry, we don\'t have that data type'
		quit()