def printStocks(sL) : # Prints the stocks
	for x in sL: # A for each loop
		lcd.clear() # Clears the LCD
		print x + " " + ystockquote.get_price(x) # Gets the price of x and prints it to console
		lcd.message(x + " " + ystockquote.get_price(x)) # Gets the price and shows it on the lcd
		print ystockquote.get_change(x) # Gets the price change and prints it to the console
		lcd.message(ystockquote.get_change(x)) # Gets the price change and shows it on the lcd
		sleep(10) # Sleeps so it user can read the info
Пример #2
0
def oil():
  # crude oil
  crude = ystockquote.get_price('CLJ14.NYM')
  print crude
  # heating oil
  heat = ystockquote.get_price('HOH14.NYM')
  print heat
  if float(crude) < 98:
    body = "Low price alert! Crude: " + crude + " Heat: " + heat
    messager(body)
    print body
  return
Пример #3
0
def printStocks(sL):  # Prints the stocks
    for x in sL:  # A for each loop
        lcd.clear()  # Clears the LCD
        print x + " " + ystockquote.get_price(
            x)  # Gets the price of x and prints it to console
        lcd.message(
            x + " " +
            ystockquote.get_price(x))  # Gets the price and shows it on the lcd
        print ystockquote.get_change(
            x)  # Gets the price change and prints it to the console
        lcd.message(ystockquote.get_change(
            x))  # Gets the price change and shows it on the lcd
        sleep(10)  # Sleeps so it user can read the info
Пример #4
0
def buy_stock_conditionals(data, portfolio, monthly, request):
    price = ystockquote.get_price(str(data))
    number_shares = math.trunc(float(monthly) / float(price))
    if portfolio:
        for items in portfolio:
            empty_stock_add_shares(data, items, number_shares)
    else:
        price = ystockquote.get_price(str(data))
        cost = float(price) * float(number_shares)
        real_cost = decimal.Decimal(cost)
        PersonalStockPortfolio.objects.create(name="primary", owner=request.user, stock_one_name=str(data),
                                              stock_one_shares=number_shares, cost=real_cost)
    data = {data: number_shares}
    return data
Пример #5
0
 def run(self):
     """
     Main loop
     """
     properties = {"app_id": self.app_id}
     while True:
         # Loop over the tickers and lookup the stock price and volume
         for ticker in self.tickers:
             measurements = []
             price = ystockquote.get_price(ticker)
             volume = ystockquote.get_volume(ticker)
             timestamp = int(time.time())
             if volume == 'N/A' or price == 'N/A':
                 sys.stderr.write(
                     'Could not find ticker \"{0}\", skipping'.format(
                         ticker))
             else:
                 print("ticker: {0}, price: {1}, volume: {2}".format(
                     ticker, price, volume))
                 measurements.append(
                     Measurement(metric='STOCK_PRICE',
                                 value=price,
                                 source=ticker,
                                 properties=properties))
                 measurements.append(
                     Measurement(metric='STOCK_VOLUME',
                                 value=volume,
                                 source=ticker,
                                 properties=properties))
                 self.send_measurements(measurements)
         time.sleep(self.interval)
Пример #6
0
 def run(self):
     """
     Main loop
     """
     properties = {"app_id": self.app_id}
     while True:
         # Loop over the tickers and lookup the stock price and volume
         for ticker in self.tickers:
             measurements = []
             price = ystockquote.get_price(ticker)
             volume = ystockquote.get_volume(ticker)
             timestamp = int(time.time())
             if volume == 'N/A' or price == 'N/A':
                 sys.stderr.write('Could not find ticker \"{0}\", skipping'.format(ticker))
             else:
                 print("ticker: {0}, price: {1}, volume: {2}".format(ticker, price, volume))
                 measurements.append(Measurement(metric='STOCK_PRICE',
                                                 value=price,
                                                 source=ticker,
                                                 properties=properties))
                 measurements.append(Measurement(metric='STOCK_VOLUME',
                                                 value=volume,
                                                 source=ticker,
                                                 properties=properties))
                 self.send_measurements(measurements)
         time.sleep(self.interval)
Пример #7
0
 def __init__(self, ticker):
     self.ticker = ticker
     params = getParams(ticker)
     self.mean = params[0][0]
     self.var = params[0][1]
     self.vol = params[1]
     self.price = get_price(self.ticker)
Пример #8
0
 def buy(self, ticker, amount):
     buy_price = y.get_price(ticker)
     buy_date = datetime.today()
     pos = Position(ticker, buy_date, buy_price, amount)
     self.open_positions.append(pos)
     buy = Decimal(buy_price.strip(' "')) * Decimal(amount)
     self.cash = int(self.cash - buy)
Пример #9
0
 def buy(self, ticker, amount):
     buy_price = y.get_price(ticker)
     buy_date = datetime.today()
     pos = Position(ticker, buy_date, buy_price, amount)
     self.open_positions.append(pos)
     buy = Decimal(buy_price.strip(' "')) * Decimal(amount)
     self.cash = int(self.cash - buy)
Пример #10
0
    def testMovingAverage(self, stock):

        if self.MA35 > self.MA350 and self.MA35 > float(
                quote.get_price(stock)):
            return 1
        else:
            return 0
Пример #11
0
def post_stock_price(symbol, apikey, devicename):
    '''
    Retrieve the stock price for the given ticker symbol ("T" for AT&T) and
    post it in the correct M2X data stream.
    '''
    client = M2XClient(key=apikey)

    # Find the correct device if it exists, if not create it.
    try:
        device = [d for d in client.devices(q=devicename) if d.name == devicename][0]
    except IndexError:
        device = client.create_device(name=devicename,
                                      description="Stockreport Example Device",
                                      visibility="private")

    # Get the stream if it exists, if not create the stream.
    try:
        stream = device.stream(symbol)
    except HTTPError:
        stream = device.create_stream(symbol)
        device.update_stream(symbol, unit={'label': 'Dollars', 'symbol': '$'})

    postime = datetime.now()
    stock_price = ystockquote.get_price(symbol).encode('utf-8')
    stream.add_value(stock_price, postime)
def get_current_price(symbol):
    """
    Get the latest price!
    :param symbol:
    :return:
    """
    return float(ystockquote.get_price(symbol))
Пример #13
0
	def buyStockIfPossible(self):
		for k,v in self.stocks.items():
			cost = float(ystockquote.get_price(k));
			if(cost < self.capital):
				count = int(self.capital / cost);
				self.stocks[k] = v + count;
				self.capital -= cost * count;
Пример #14
0
def check(symbol, position=False):
    days = 20
    quotes = prices(symbol, days)
    _raising = raising(symbol)
    _price = float(ystockquote.get_price(symbol))
    _over_mavg = over_mavg(_price, quotes)
    _min = min(quotes)
    #print "%s min %s, now %s" % (symbol, _min, _price)

    if (position):
        color = "red"
    else:
        color = "orange"

    if (_raising and _over_mavg):
        print "<div style=color:green>Raising and over mavg: BUY %s</div>" % symbol
        return

    if (not _over_mavg):
        print "<div style=color:%s>Not over mavg: SELL %s</div>" % (color,
                                                                    symbol)
        return

    if (_price <= _min):
        print "<div style=color:orange>Under 20 day min: SELL %s</div>" % (
            color, symbol)
        return

    print "<div>No matching signal for %s</div>" % symbol
Пример #15
0
def get_current_price(symbol):
    """
    Get the latest price!
    :param symbol:
    :return:
    """
    return float(ystockquote.get_price(symbol))
Пример #16
0
def post_stock_price(symbol, apikey, devicename):
    '''
    Retrieve the stock price for the given ticker symbol ("T" for AT&T) and
    post it in the correct M2X data stream.
    '''
    client = M2XClient(key=apikey)

    # Find the correct device if it exists, if not create it.
    try:
        device = [
            d for d in client.devices(q=devicename) if d.name == devicename
        ][0]
    except IndexError:
        device = client.create_device(name=devicename,
                                      description="Stockreport Example Device",
                                      visibility="private")

    # Get the stream if it exists, if not create the stream.
    try:
        stream = device.stream(symbol)
    except HTTPError:
        stream = device.create_stream(symbol)
        device.update_stream(symbol, unit={'label': 'Dollars', 'symbol': '$'})

    postime = datetime.now()
    stock_price = ystockquote.get_price(symbol).encode('utf-8')
    stream.add_value(stock_price, postime)
Пример #17
0
def check(symbol, position=False):
  days = 20
  quotes = prices(symbol, days) 
  _raising = raising(symbol) 
  _price = float(ystockquote.get_price(symbol))
  _over_mavg = over_mavg(_price, quotes)
  _min = min(quotes)
  #print "%s min %s, now %s" % (symbol, _min, _price)

  if(position):
    color = "red"
  else:  
    color = "orange"

  if(_raising and
     _over_mavg):
    print "<div style=color:green>Raising and over mavg: BUY %s</div>" % symbol
    return

  if(not _over_mavg):
    print "<div style=color:%s>Not over mavg: SELL %s</div>" % (color, symbol)
    return
  
  if(_price <= _min):
    print "<div style=color:orange>Under 20 day min: SELL %s</div>" % (color, symbol)
    return
  
  print "<div>No matching signal for %s</div>" % symbol
Пример #18
0
def get_stock_cost(data, number_shares, items):
    price = ystockquote.get_price(str(data))
    cost = float(price) * float(number_shares)
    real_cost = decimal.Decimal(cost)
    items.cost += real_cost
    items.save()
    return real_cost
def update_price(dict):
	'''
	Updates portfolio with new prices
	'''
	print 'Updating portfolio...'
	for key in dict:
		dict[key][4] = ystockquote.get_price(dict[key][1])
Пример #20
0
def run(stocks):
    with open(get_stockfile(), 'a') as data:
        for stock in stocks:
            current = ystockquote.get_price(stock)
            if isinstance(current, float):
                data.write(stock + ' ' + current + '\n')
            print 'Purchased', stock, 'at', current
Пример #21
0
def update_price():
    # pull today
    now = datetime.now()
    today = ("%s-%02d-%02d" % (now.year, now.month, now.day))
    quotes = ystockquote.get_historical_prices('SPY', '2015-01-15',
                                               today)  #pull data

    #writing json
    with open('www/live-data/price.json', 'w') as file:
        json.dump(quotes, file)

    #get current price
    current_price = ystockquote.get_price('SPY')
    current_date = now.strftime('%Y-%m-%d')
    current_time = now.strftime('%H:%M:%S')

    current_value = str(current_date) + "," + str(current_time) + "," + str(
        current_price)
    header = "date,time,price"

    with open('www/live-data/current.csv', 'wb') as f:
        fwriter = csv.writer(f, delimiter=" ")
        fwriter.writerow([header])
        fwriter.writerow([current_value])

    if app_config.DEPLOYMENT_TARGET:
        flat.deploy_folder('www/live-data',
                           'live-data',
                           max_age=app_config.DEFAULT_MAX_AGE)
Пример #22
0
def priceMe(tick):
	price = 0
	try:
		price = float(ystockquote.get_price(tick))
	except:
		return price
	return price
Пример #23
0
 def export(self, xlsx_file, s_flag):
   wb = Workbook()
   ws = wb.create_sheet(0)
   ws.title = "Guru 13Fs"
   print "Writing {0}...".format(xlsx_file) 
   headers = ["Gurus", "Date", "Symbol", "Action", "Average", "Minimum", "Volume", "Portfolio Impact"]
   if s_flag:
     headers.append("Current Share Price")
   
   col = 0
   for header in headers:
     header_cell = ws.cell(row = 0, column = col)
     header_cell.value = header
     if header == "Gurus":
       ws.merge_cells(start_row = 0, start_column = 0, end_row = 0, end_column = 2)
       col += 2
     col += 1
     
   db = self.client.gurudb
   gurus = db.gurus
   cursor = gurus.find()
   
   share_prices = dict()
   guruRow = 1
   for guru in cursor:
     tickers = guru['tickers']
     for ticker in tickers:
       history = ticker['transactionHistory']
       transactions = history['transactions']
       symbol = ticker['ticker']
       if share_prices.get(symbol) == None and s_flag:
         share_prices[symbol] = ystockquote.get_price(symbol)
         print "Retrieved {0} at ${1} for {2}".format(symbol, share_prices[symbol], guru['name'])
       for transaction in transactions:
         guru_cell = ws.cell(row = guruRow, column = 0)
         guru_cell.value = guru['name']
         ws.merge_cells(start_row = guruRow, start_column = 0, end_row = guruRow, end_column = 2)
         symbol_cell = ws.cell(row = guruRow, column = self.SYMBOL_CELL)
         symbol_cell.value = symbol
         impact_cell = ws.cell(row = guruRow, column = self.IMPACT_START_CELL)
         impact_cell.value = "{0}%".format(ticker['percent'])
         transaction_cell = ws.cell(row = guruRow, column = self.DATE_CELL)
         transaction_cell.value = transaction['date']
         action_cell = ws.cell(row = guruRow, column = self.ACTION_CELL)
         action_cell.value = transaction['entryType']
         average_cell = ws.cell(row = guruRow, column = self.AVERAGE_CELL)
         # convert from int to decimal. stored in mongo this way for percision reasons
         average_cell.value = float(transaction['avg']) * 0.01
         minimum_cell = ws.cell(row = guruRow, column = self.MINIMUM_CELL)
         minimum_cell.value = float(transaction['min']) * 0.01
         volume_cell = ws.cell(row = guruRow, column = self.VOLUME_CELL)
         volume_cell.value = transaction['numberOfShares']
         if s_flag:
           current_share_price_cell = ws.cell(row = guruRow, column = self.CURRENT_SHARE_PRICE_START_CELL)
           current_share_price_cell.value = share_prices.get(symbol)
         guruRow += 1
   
   wb.save(xlsx_file)
   print "Wrote {0}".format(xlsx_file) 
   return
Пример #24
0
def mainIndex():
    if request.method == 'POST':
	ticker = request.form['search']
    	stockPrice = ystockquote.get_price(ticker)
    	return render_template('index.html', selectedMenu='Home', price=stockPrice, symbol=ticker, queryType='stock')
    if 'username' in session:
	return render_template('index.html', selectedMenu='Home', username=session['username'])
    return render_template('index.html', selectedMenu='Home')
Пример #25
0
def update_prices():
    """
    update stock prices calling ystockquote
    """
    from finance_game.models import Stock
    for stock in Stock.objects.all():
        stock.price = ystockquote.get_price(stock.symbol)
        stock.save()
Пример #26
0
 def __init__(self, ticker):
     self.ticker = ticker
     self.price = round(float(ystock.get_price(ticker)), 2)
     self.ma_5 = None
     self.ma_10 = None
     self.ma_20 = None
     self.ma_50 = None
     self._calculate_moving_averages()
Пример #27
0
    def post(self):
        self.write("{\"number\": \"five\"}")
		if request.headers['Content-Type'] == 'application/json':
			data = json.loads(request.data)
			ticker = data['ticker']
			price = ystockquote.get_price(ticker)
			returnStatement = "{\"price\": \""+str(price)+"\"}"
			self.write(returnStatement)
Пример #28
0
def add_stock(stock, target):
    price = ystockquote.get_price(stock)
    c.execute("INSERT INTO stocks VALUES (?,?,?)", (
        stock,
        target,
        price,
    ))
    conn.commit()  # Save (commit) the changes
    print "\nStock added to database"
Пример #29
0
def stockfinder_view(request, ticker=None):
    """
    This view displays a HTML-page where the user can search for stocks
    on the OSL stock exchange.
    """
    ticker = ticker + '.OL'
    price = get_price(ticker)
    data = {'ticker': ticker,'price': price}
    return HttpResponse((data['ticker'], data['price']))
Пример #30
0
	def getPrice(self):
		global verbose
		if self.name == 'Cash':
			return
		if verbose:
			print("PRICE GET: %s" % (self.name))
		ret = ystockquote.get_price(self.name)
		self.price = float(ret)
		if verbose:
			print("PRICE RCV: %s $%.2f" % (self.name, self.price))
Пример #31
0
def price(ticker):
    """
    For a given 'ticker' this function returns a dict containing
    {'ticker':'T', price:'P'}
    (Can lookup towards yahoo finance or even better - use live data
    from SEB )
    """
    price = get_price(ticker)
    data = {"ticker": ticker, "price": price}
    return data
Пример #32
0
def run():
    for line in open(get_stockfile(), 'r').readlines():
        purchased = line.split()
        current = ystockquote.get_price(purchased[0])
        difference = 100 * round(float(current) / float(purchased[1]) - 1, 5)

        print purchased[0] + ':',
        print 'bought at', purchased[1] + ',',
        print 'current price is', current,
        print '(' + str(difference) + '%)'
Пример #33
0
def match_stocks(data, portfolio_stocks):
    data_list = {}
    for stock, values in data[0]['stockPort'].iteritems():
        for quote in portfolio_stocks:
            if stock == quote.hidden_symbol:
                value = (float(ystockquote.get_price(stock))*values)
                data_list[quote.name] = value
            else:
                pass
    return [data_list, data[1]]
Пример #34
0
def update(stock1):
    stock1.lastprice = ystockquote.get_price(stock1)
    stock1.volume = ystockquote.get_volume(stock1)
    price_change = ystockquote.get_change(stock1)
    market_cap = ystockquote.get_market_cap(stock1)
    get_high = ystockquote.get_52_week_high(stock1)
    get_low = ystockquote.get_52_week_low(stock1)
    pb_ratio = ystockquote.get_price_book_ratio(stock1)
    ebitda = ystockquote.get_ebitda(stock1)
    dividend = ystockquote.get_dividend_yield(stock1)
    stock1.save()
Пример #35
0
def get_percent_change(symbol):
    change = ystockquote.get_change(symbol)
    price = ystockquote.get_price(symbol)
    percent_change = 100*float(change)/(float(price)-float(change))
    percent_decimal = round(Decimal(percent_change), 2)
    if percent_decimal > 0:
        return '+'+str(percent_decimal)
    elif percent_decimal==0:
        return '0'
    else:
        return '-'+str(abs(percent_decimal))
Пример #36
0
def update(stock1):
    stock1.lastprice = ystockquote.get_price(stock1)
    stock1.volume = ystockquote.get_volume(stock1)
    price_change = ystockquote.get_change(stock1)
    market_cap = ystockquote.get_market_cap(stock1)
    get_high = ystockquote.get_52_week_high(stock1)
    get_low = ystockquote.get_52_week_low(stock1)
    pb_ratio = ystockquote.get_price_book_ratio(stock1)
    ebitda = ystockquote.get_ebitda(stock1)
    dividend = ystockquote.get_dividend_yield(stock1)
    stock1.save()
def get_current_price(symbol):
    """
    Get the latest price for a symbol.

    :param symbol: (str)
    :return: (float)
    """
    quote = ystockquote.get_price(symbol)
    if quote == 'N/A':
        return None
    return float(quote)
Пример #38
0
 def __init__(self, ticker, sess):
     self.ticker = ticker
     self.sess = sess
     # Next points will be inited in _initialize_points()
     self.r2 = None
     self.r1 = None
     self.p = None
     self.s1 = None
     self.s2 = None
     self.price = round(float(ystock.get_price(ticker)), 2)
     self._initialize_points()
Пример #39
0
def updatePrices(stocks2):
	filne = "stocks.txt"
	f = open(filne, 'r+')
	lines = f.readlines()
	for i in range(1, len(lines)):
		place = i-1
		#Only update if stock is owned
		if(stocks2[5][place]==True):
			stocks2[4][place] = ystockquote.get_price(stocks2[0][place])
			
	return stocks2
Пример #40
0
	def record_stock_price(self, stock, file):

		price = ystockquote.get_price(stock)
		now = datetime.now()
		self.history[now] = price

		with open(file, "a") as f:
			f.write(str(now))
			f.write(',')
			f.write(price)
			f.write("\n")
		f.close()
Пример #41
0
def get_predicted_stock(symbol):
    symbol = "$"+symbol.upper()
    predicted_stock = {}
    predicted_change = dao.get_predicted_stock_change(symbol, db)
    current_value = get_price(symbol.strip("$"))
    # Calculate a predicted stock value based on the predicted change
    predicted_value = float(predicted_change) + float(current_value)
    predicted_stock['symbol'] = symbol
    predicted_stock['predicted_change'] = predicted_change
    predicted_stock['predicted_value'] = predicted_value
    predicted_stock['current_value'] = current_value
    return json.dumps(predicted_stock)
Пример #42
0
def get_predicted_stock(symbol):
    symbol = "$" + symbol.upper()
    predicted_stock = {}
    predicted_change = dao.get_predicted_stock_change(symbol, db)
    current_value = get_price(symbol.strip("$"))
    # Calculate a predicted stock value based on the predicted change
    predicted_value = float(predicted_change) + float(current_value)
    predicted_stock['symbol'] = symbol
    predicted_stock['predicted_change'] = predicted_change
    predicted_stock['predicted_value'] = predicted_value
    predicted_stock['current_value'] = current_value
    return json.dumps(predicted_stock)
Пример #43
0
    def record_stock_price(self, stock, file):

        price = ystockquote.get_price(stock)
        now = datetime.now()
        self.history[now] = price

        with open(file, "a") as f:
            f.write(str(now))
            f.write(',')
            f.write(price)
            f.write("\n")
        f.close()
Пример #44
0
def savequote(stockid, lastquotestamp, conn):
    c = conn.cursor()

    c.execute(
        "select symbolgoogle, symbolyahoo, type from stocks where id=:id",
        {'id': int(stockid)})

    row = c.fetchone()
    if row['type'].upper() == 'STOCK':
        symbol = str(row['symbolgoogle'])
        quote = getQuotes(symbol)  # get quote
        value = quote[0]["LastTradePrice"]
        # parse uses posix stype for timezone offsets. ISO requires inversion in sign!!
        correcteddate = quote[0]["LastTradeDateTimeLong"]
        if correcteddate.find('+'):
            correcteddate = correcteddate.replace('+', '-')
        elif correcteddate.find('-'):
            correcteddate = correcteddate.replace('-', '+')
        date = dateutil.parser.parse(correcteddate, tzinfos=tzd)
        timestamp = date.isoformat()
        if date.tzinfo is None:
            timestamp += 'Z'

    elif row['type'].upper() == 'CURRENCY':
        symbol = str(row['symbolyahoo'])
        value = float(get_price(symbol))  # get quote
        date = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
        timestamp = date.isoformat()

    if (lastquotestamp is None) or (dateutil.parser.parse(
            lastquotestamp, tzinfos=tzd) != date):
        # Date changed since last quote => save to database
        c.execute(
            """
                insert into quotes(stockid,timestamp,value)
                values(?,?,?)
                """, (int(stockid), timestamp, float(value)))

        if not (timestamp is None):
            c = conn.cursor()
            c.execute("""
                UPDATE stocks
                SET lastquotestamp = ?, lastquote = ?
                WHERE id = ?;
                """, (timestamp, float(value),
                      int(stockid)))  # update last quote timestamp

        conn.commit()

        return timestamp, float(value)
    else:
        return None, None
Пример #45
0
def calculate_ebit_ev(cur, ticker):

    ebit = float(get_last(ticker, "EBIT", cur))
    shares = float(get_last(ticker, "total common shares out", cur))
    bonds = float(get_last(ticker, "long-term debt", cur))
    #try:
    price = float(ystockquote.get_price(ticker))
    #except ValueError:
    #    return 0
    ev = price * shares + bonds
    if ev == 0:
        return
    return ebit / ev
Пример #46
0
def index(request):
    stocks = Stock.objects.all()
    for stock1 in stocks:
        stock1.lastprice = ystockquote.get_price(stock1)
        # YYYY-MM-DD
        historical_price = ystockquote.get_historical_prices(
            stock1, '2016-05-24', '2016-05-26')
        hprice = []
        for values in historical_price:
            hprice.append(historical_price[values]['Close'])

    template = loader.get_template('stocktracker/index.html')
    context = {'stocks': stocks}
    return render(request, 'stocktracker/index.html', context)
Пример #47
0
def strategytwo():
    bought_mode = False
    global server

    logging.info(
        "Strategy TWO:SPX MAKES A NEW 50 DAY HIGH. THE % of NYSE issues making new highs falls by at least 2%. SHORT SPX on CLOSE. BUY 5 DAYS LATER"
    )
    logging.info("Current price of SPX")
    logging.info(ystockquote.get_price("SPY"))
    #chance of working is 95%
    logging.info('\n')
    todays_date = time.strftime("%Y-%m-%d")
    logging.info("todays date is " + todays_date)
    logging.info('\n')

    date_N_days_ago = datetime.now() - timedelta(days=50)
    f = str(date_N_days_ago)
    date_fifty_days_ago = f.split(' ')[0]
    logging.info("the date 50 days ago is")
    logging.info(date_fifty_days_ago)
    logging.info('\n')

    historical_price = ystockquote.get_historical_prices(
        "SPY", date_fifty_days_ago, todays_date)
    histpricelist = historical_price.items()
    histpricelist.sort()

    try:
        logging.info("the close from fifty days ago is " +
                     historical_price[date_fifty_days_ago]['Close'])
        fiftydaysagoclose = float(
            historical_price[date_fifty_days_ago]['Close'])
        logging.info('\n')
    except Exception:
        logging.info(
            "looks like the fifty days ago close was a non trading day fixing the problem"
        )
        logging.info("the close from fifty days ago is " +
                     str(histpricelist[0][1]['Close']))
        fiftydaysagoclose = float(histpricelist[0][1]['Close'])
        logging.info('\n')

    #getpercentofnysesissues making new highs

    def mainpartofthisstrategy():
        #get the price every 10 minutes and see if it matches the strategy
        current_price = float(ystockquote.get_price("SPY"))

    threading.Timer(84600, strategytwo).start()
Пример #48
0
 def run(self):
     try:
         try:
             rate = float(ystockquote.get_price(self.code))
         except Exception, err:
             print err
             return
         share = stock.objects.get(code=self.code)
         if share.price != rate:
             share.update = share.update + 1
         share.price = rate * 65
         if rate > share.max_price_of_day:
             share.max_price_of_day = rate
         share.save()
         connection.close()
         print "sucess"
Пример #49
0
	def run(self):
		"""Plugin main loop"""
		self.loadParameters()
		self.sendEvent("Plugin started","Starting ticker plugin","info",int(time.time()))
		while True:
			# Loop over the items and lookup the stock price and volume
			for i in self.items:
				ticker = str(i["ticker"]).upper()
				price = ystockquote.get_price(ticker)
				volume = ystockquote.get_volume(ticker)
				timestamp = int(time.time())
				if volume == 'N/A' or price == 'N/A':
					self.sendEvent('Ticker Not Found','Could not find ticker \"{0}\", skipping'.format(ticker),"error",timestamp)
				else:
					self.sendMeasurement('BOUNDARY_STOCK_PRICE',price,ticker,timestamp)
					self.sendMeasurement('BOUNDARY_STOCK_VOLUME',volume,ticker,timestamp)
			time.sleep(self.pollInterval)
Пример #50
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)))
Пример #51
0
def fetchcurrentprice():
    content1 = urllib.urlopen("https://www.google.com/finance?q=SPY").read()
    m = re.search('(?:<span class=nwp>\n)(.*)', content1)
    print(m.group(1))
    while not 'Close' in m.group(1):
        content1 = urllib.urlopen(
            "https://www.google.com/finance?q=SPY").read()
        m = re.search('(?:<span class=nwp>\n)(.*)', content1)
        current_price = float(ystockquote.get_price("SPY"))
        print(current_price)
        current_price_array.append(current_price)
        print(current_price_array)
        if len(current_price_array) > 5760:
            print("len of current price array was greater than 5760")
            del current_price_array[0]
        np.savetxt("spy.csv", current_price_array, fmt='%10.2f', delimiter=",")
    time.sleep(15)
    threading.Timer(30, fetchcurrentprice).start()
Пример #52
0
def run(stocks):
    overall = 0
    owned = []
    for line in open(get_stockfile(), 'r').readlines():
        if any(line.startswith(stock) for stock in stocks):
            purchased = line.split()
            current = ystockquote.get_price(purchased[0])
            profit = round(float(current) - float(purchased[1]), 3)
            overall += profit

            print 'Sold', purchased[0], 'at', current + '.',
            print 'Return was',
            print_money(profit)
        else:
            owned.append(line)

    with open(get_stockfile(), 'w') as data:
        for stock in owned:
            data.write(stock)

    print 'Overall return:',
    print_money(overall)
Пример #53
0
csvfile = open('nasdaqlist.csv', 'rb')
reader = csv.reader(csvfile)

rownum = 0
stocksymbols = []
stockDetails =[]
for row in reader:
    # Save header row.
    if rownum == 0:
        header = row
    else:
        #print row
        stocksymbols.append(row[0])
        stockDetails.append(row)
             
    rownum += 1
 
csvfile.close()

results = []
for stockDetail in stockDetails:
    symbol = stockDetail[0]
    price = float(ystockquote.get_price(symbol))
    bookvalue = float(ystockquote.get_book_value(symbol))
    halfBook = bookvalue * 0.5
    if (price <= halfBook):
        print ', '.join(stockDetail)
        results.append(symbol)

print len(results)
Пример #54
0
 def priceBought(self, stock):
     self.price = float(quote.get_price(stock))
     return self.price
Пример #55
0
    return (sum - 48 * numchars)


#* you can send the text on the next line using Serial Monitor to set the clock to noon Jan 1 2010 and LLTC to $29.45
#T12623472002945
#T13246667523036

#rawtime = str(int(time()-28800))
#rawtime = str(int((time()-28800)) - 120 + 0 - 9 + 97 + 3600)
rawtime = str(int((time() - 28800)) - 120 + 0 - 9 + 97)

print "Raw Time: " + rawtime

print "Converted Time: " + strftime("%a, %d %b %Y %H:%M:%S +0000", localtime())

rawstock = str(ystockquote.get_price('LLTC'))

print "LLTC Stock Price is " + rawstock

rawstock = ''.join(i for i in rawstock if i.isdigit())
rawstock = rawstock[0:4]

print "Strip the decimal, trim to two " + rawstock

#yahoo_result = pywapi.get_weather_from_yahoo('95035', '')

#print "Yahoo says: It is " + string.lower(yahoo_result['condition']['text']) + " and " + yahoo_result['condition']['temp'] + "F now in Milpitas.\n\n"

#clockstring = "aaaaT" + rawtime + rawstock + "bbbb"
clockstring = "T" + rawtime + rawstock
clockstring = clockstring.encode('utf-8')
Пример #56
0
def validate_stock(stock):
    return ystockquote.get_price(stock) != "0.00"
Пример #57
0
 def test_get_price(self):
     value = ystockquote.get_price(self.symbol)
     self.assertIsInstance(value, str)
def getPriceOfStock(symbol):
	return float(ystockquote.get_price(symbol))
Пример #59
0
def get_price_time(symbol):
	price = ystockquote.get_price(symbol)
	current_time = datetime.datetime.now()
	return [symbol, price, str(current_time)]
Пример #60
-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()