예제 #1
0
class ShareObj(object):
    def __init__(self, ID):
        self.id = ID
        self.share = Share(self.id)
        self.refresh

    def getPrice(self):
        return self.share.get_price()

    def getOpenPrice(self):
        return self.share.get_open()

    def getChange(self):
        if(self.share.get_percent_change() == None):
            return 0
        else:
            percent = (self.share.get_percent_change()[:-1])
            return float(percent)

    def getChangeFormatted(self):
        self.share.get_percent_change()

    def getID(self):
        return self.id

    def refresh(self):
        self.share.refresh()

    def getHistorical(self,date1, date2):
        return self.share.get_historical(date1,date2)

    def getCalculatedChange(self, open, close):
        return ((close - open)/open)*100
예제 #2
0
파일: app.py 프로젝트: jacobj10/JumpShyp
def get_stock_info(name, abbr):
    x = Share(abbr)
    x.refresh()
    price = x.get_price()
    change = x.get_percent_change()
    print(change[0] == '-')
    if change[0] == '-':
        color = '#B22222'
    else:
        color = '#006400'
    url = "https://news.google.com/news?q={0}&output=rss".format(name)
    feed = feedparser.parse(url)

    entries = []
    i = 0
    while i < len(feed.entries) and i < 7:
        title = feed.entries[i]['title']
        index = title.index('-')
        author = title[index + 2:]
        title = title[:index - 1]
        link = feed.entries[i]['link']
        entries.append({'title': title, 'author': author, 'link': link})
        i += 1
    return {
        'price': price,
        'change': change,
        'color': color,
        'entries': entries
    }
예제 #3
0
def getPrice():
    input = json.dumps(request.json)
    data = input
    print(data)
    symbolT = request.json['symbol']
    finalResult["errMsg"] = "None"
    try:
        company = get_symbol(symbolT.upper())
        if company == "NetworkError" or company == "InvalidSymbol":
            finalResult["errMsg"] = company
        else:
            #output
            dt = datetime.datetime.now(tzlocal.get_localzone())
            finalResult["time"] = dt.strftime("%a %b %d %H:%M:%S %Z %Y")
            finalResult["company"] = company + " (" + symbolT.upper() + ") "
            stock = Share(symbolT)
            finalResult["stockInfo"] = stock.get_price(
            ) + " " + stock.get_change() + " (" + stock.get_percent_change(
            ) + ") "

    except ValueError:
        finalResult["errMsg"] = "SystemError"

    jsonResult = json.dumps(finalResult)
    return jsonResult
예제 #4
0
파일: tasks.py 프로젝트: JoshuaKw/Minvest
def set_ETF_data():
    etf_data = []

    for index, etf_symbol in enumerate(settings.ETF_MASTER_LIST):
        etf_dict = {
            'model': 'portfolio.ETF',
            'pk': index + 1,
            'fields': {},
        }

        fund = Share(etf_symbol)

        fields = {
            'name': fund.get_name(),
            'symbol': etf_symbol,
            'last_trade': fund.get_price(),
            'dividend_yield': fund.get_dividend_yield(),
            'absolute_change': fund.get_change(),
            'percentage_change': fund.get_percent_change(),
            'year high': fund.get_year_high(),
            'year low': fund.get_year_low(),
            '50 day moving average': fund.get_50day_moving_avg(),
            '200 day moving average': fund.get_200day_moving_avg(),
            'average_daily_volume': fund.get_avg_daily_volume()
        }

        etf_dict['fields'] = fields
        etf_data.append(etf_dict)
    json_data = json.dumps(etf_data)

    # print(json_data)

    output_dict = [y for y in etf_data if y['fields']['dividend_yield'] > 1]

    output_dict = [
        x for x in output_dict if x['fields']['average_daily_volume'] > 100000
    ]

    output_dict = [
        z for z in output_dict
        if z['fields']['200 day moving average'] < z['fields']['last_trade']
    ]

    sorted_list = sorted(output_dict,
                         key=lambda k: k['fields']['dividend_yield'],
                         reverse=True)

    for etf in sorted_list[:5]:
        ETF.objects.create(
            portfolio=Portfolio.objects.get(pk=1),
            name=etf['fields']['name'],
            symbol=etf['fields']['symbol'],
            investment_style=1,
            last_trade=etf['fields']['last_trade'],
            dividend_yield=etf['fields']['dividend_yield'],
            absolute_change=etf['fields']['absolute_change'],
            percentage_change=etf['fields']['percentage_change'],
            currency='USD',
            last_updated=timezone.now())
예제 #5
0
 def update_ETF_value(self):
     fund = Share(self.symbol)
     self.last_trade = fund.get_price()
     self.absolute_change = fund.get_change()
     self.percentage_change = fund.get_percent_change()
     self.dividend_yield = fund.get_dividend_yield()
     self.last_updated = timezone.now()
     self.save()
예제 #6
0
def lookup2(symbol):

    try:
        share = Share(symbol)
    except:
        return None

    if share.get_name() is None:
        return None

    return {
        "name": share.get_name(),
        "symbol": symbol.upper(),
        "price": share.get_price(),
        "change": share.get_change(),
        "pc_change": share.get_percent_change(),
        "trade_time": share.get_trade_datetime()
    }
예제 #7
0
파일: mint.py 프로젝트: peterwu8/stocks
class TickerData:
    def __init__(self, ticker_symbol):
        self._name = ticker_symbol
        self._yahoo = None
        self._google = None
        self._csv_data = HistoricCsvFile(ticker_symbol)
        if self._csv_data.is_google_data():
            self._google = googlefinance.getQuotes(ticker_symbol)[0]
            #print (json.dumps(self._google, indent=2))
        else:
            self._yahoo = Share(ticker_symbol)

    def get_name(self):
        return self._name

    def get_long_name(self):
        return self._yahoo.get_name() if self._yahoo else self._name

    def get_last_price(self):
        return self._yahoo.get_price(
        ) if self._yahoo else self._google['LastTradePrice']

    def get_last_trade_datetime(self):
        return self._yahoo.get_trade_datetime(
        ) if self._yahoo else self._google['LastTradeDateTime']

    def get_price_change(self):
        return self._yahoo.get_change(
        ) if self._yahoo else self._google['ChangePercent']

    def get_price_open(self):
        return self._yahoo.get_open(
        ) if self._yahoo else self._google['PreviousClosePrice']

    def get_percent_change(self):
        return self._yahoo.get_percent_change(
        ) if self._yahoo else get_ratio_percent(self.get_last_price(),
                                                self.get_price_open())

    def get_yahoo(self):
        return self._yahoo

    def get_csv_data(self):
        return self._csv_data
예제 #8
0
def bot_action(c, symbol):
    stock = Share(symbol)                # Link stock with yahoo_finance module
    print(stock)
    if stock.get_price() == None:
        main()
    #print(stock.get_price())
    head = 'Up to date stock info for **${0}** ({1}):\n\n'.format(symbol.upper(), stock.get_name())
    price = '**Price:** ${0:.2f}\n\n'.format(float(stock.get_price()))
    price_open = '**Open:** ${0:.2f}\n\n'.format(float(stock.get_open()))
    change = '**Change:** {0:.2f} ({1})\n\n'.format(float(stock.get_change()), stock.get_percent_change())
    vol = '**Volume:** {0:,.2f}\n\n'.format(float(stock.get_volume()))
    market_cap = '**Mkt Cap:** {0}\n\n'.format(stock.get_market_cap())
    average = '**Average (50 day):** {0:.2f}\n\n'.format(float(stock.get_50day_moving_avg()))
    exchange = '**Exchange:** {0}\n\n'.format(stock.get_stock_exchange())
    divider = '-----------------------------------------------------------------------------------------\n\n'
    tail = "Don't abuse me, robots have feelings too! | [Source Code](https://github.com/Logicmn/Reddit-Stock-Bot) " \
           "| [Report Bug](https://www.reddit.com/message/compose/?to=Pick-a-Stock) " \
           "| [Suggest Feature](https://www.reddit.com/message/compose/?to=Pick-a-Stock)"
    c.reply(head + divider + price + price_open + change + vol + market_cap + average + exchange+ divider + tail)
def getStock(ticker):
    stock = Share(ticker)
    #name = stock.get_name()
    po = str(stock.get_open())
    pn =  str(stock.get_price())
    pcl =  str(stock.get_prev_close())
    pc = str(stock.get_percent_change())
    low = str(stock.get_days_low())
    high = str(stock.get_days_high())
    h = datetime.now().strftime("%I")
    p = datetime.now().strftime("%p")
    x = ticker.upper() + "\nCurrent: " + pn +"\nClose: " + pcl + "\nChange: "+ pc + "\nLow: " + low + "\nHigh: " + high
    y = ticker.upper() + "\nCurrent: " + pn + "\nOpen: " + po + "\nChange: " + pc + "\nLow: " + low + "\nHigh: " + high
    
    if h <= "4" and p == "PM":
        return x
    elif h >= "4" and p == "PM":
        return y
    elif h <= "8" and p == "AM":
        return y
    else:
        return x
def main():
    # this adds commas to all numbers greater than one thousand
    locale.setlocale(locale.LC_ALL, 'en_US')
    # if statement that checks for args. error/help message will appear if no args
    if (len(sys.argv) == 1):
        print "\nPlease supply one or more tickers. Example: python stephan_s_stock_quote.py GOOG\n"

    else:
        for counter in range(1, len(sys.argv)):
            # this is where we fetch our stocks from
            y = Share(sys.argv[counter])
            # this is the output along with a message regarding the CSV file
            print "\nSymbol: " + str(sys.argv[counter])

            print "Company Name: " + str(y.get_name())

            print "Market Capitalization: $" + str(y.get_market_cap())

            print "Earnings Per Share: $" + str(
                locale.format(
                    "%d", float(y.get_earnings_share()), grouping=True))

            print "P/E Ratio: " + str(y.get_price_earnings_ratio())

            print "Average Volume: " + str(
                locale.format(
                    "%d", float(y.get_avg_daily_volume()), grouping=True))

            print "Today's Volume: " + str(
                locale.format("%d", float(y.get_volume()), grouping=True))

            print "Today's Closing Price: $" + str(y.get_price())

            print "Percent Change: " + str(y.get_percent_change()) + "\n"

    print "A CSV file of your selected stock tickers has been downloaded to your computer under the name 'stocks.csv'. " + "\n"

    print "The CSV file will be downloaded to the same folder that this program was stored in." + "\n"
예제 #11
0
    etf_dict = {
        'model': 'portfolio.ETF',
        'pk': index + 1,
        'fields': {},
    }

    fund = Share(ETF)

    fields = {
        'name': fund.get_name(),
        'symbol': ETF,
        'last_trade': fund.get_price(),
        'dividend_yield': fund.get_dividend_yield(),
        'absolute_change': fund.get_change(),
        'percentage_change': fund.get_percent_change(),
        'year high': fund.get_year_high(),
        'year low': fund.get_year_low(),
        '50 day moving average': fund.get_50day_moving_avg(),
        '200 day moving average': fund.get_200day_moving_avg(),
        'average_daily_volume': fund.get_avg_daily_volume()
    }

    etf_dict['fields'] = fields
    etf_data.append(etf_dict)
json_data = json.dumps(etf_data)

# print(json_data)

output_dict = [y for y in etf_data if y['fields']['dividend_yield'] > 1]
    print "The CSV file will be downloaded to the same folder that this program was stored in." + "\n"


# code that creates the CSV file
with open('stocks.csv', 'w') as fp:
    outputFile = csv.writer(fp)
    data1 = [[
        'Symbol', 'Company Name', 'Market Capitalization',
        'Earnings Per Share', 'P/E Ratio', 'Average Volume', 'Today\'s Volume',
        'Today\'s Closing Price', 'Percent Change'
    ]]
    outputFile.writerows(data1)
    for counter in range(1, len(sys.argv)):
        y = Share(sys.argv[counter])

        data2 = [[
            str(sys.argv[counter]),
            str(y.get_name()),
            str(y.get_market_cap()),
            str(y.get_earnings_share()),
            str(y.get_price_earnings_ratio()),
            str(y.get_avg_daily_volume()),
            str(y.get_volume()),
            str(y.get_price()),
            str(y.get_percent_change())
        ]]

        outputFile.writerows(data2)

if __name__ == '__main__':
    main()
예제 #13
0
def get_info(ticker):
    # rjson = get_json(ticker)
    info = {}

    try:
        stock = Share(ticker)

        # 0: Get name
        url = "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query={}&region=1&lang=en".format(ticker)
        print("Ticker: ", ticker)
        result = requests.get(url).json()

        for x in result['ResultSet']['Result']:
            if x['symbol'] == ticker:
                info['name'] = truncate(x['name'])

        if info['name'] == "" or info['name'] == None:
            raise ValueError('Did not obtain a real value!')


        # 1: Get price
        # info['price'] = float(rjson[0][u'l'])
        info['price'] = get_price(ticker)

        if info['price'] == 0 or info['price'] == None:
            raise ValueError('Did not obtain a real value!')

        # 2: Get datetime
        # info['datetime'] = rjson[0][u'lt']
        info['datetime'] = getdatetime(ticker)

        if info['datetime'] == "" or info['datetime'] == None:
            raise ValueError('Did not obtain a real value!')

        # 3: Get gain
        # change = rjson[0][u'c']
        # if change is None:
        #     info['gain'] = 0
        # c = change.split("+")
        # if (len(c) > 1):
        #     info['gain'] = float(c[1])
        # info['gain'] = float(change)
        change = stock.get_change()

        if change is None:
            info['gain'] = 0
        else:
            info['gain'] = float(stock.get_change())

        if info['gain'] == None:
            raise ValueError('Did not obtain a real value!')

        # 4: Get percent change
        # info['percentchange'] = float(rjson[0][u'cp'])
        try:
            percentChange = stock.get_percent_change()
            percentChange = percentChange.split("%")[0]
            if len(percentChange.split("+")) > 1:
                percentChange = percentChange.split("+")[1]
            elif len(percentChange.split("-")) > 1:
                percentChange = percentChange.split("-")[1]

            info['percentchange'] = float(percentChange)
        except:
            info['percentchange'] = stock.get_percent_change()

        if info['percentchange'] == None:
            raise ValueError('Did not obtain a real value!')

    except:
        if db.session.query(Stock).filter_by(ticker = ticker).count() > 0:
            found_stock = db.session.query(Stock).filter_by(ticker = ticker).first()
            info['name'] = found_stock.name
            info['price'] = found_stock.price
            info['datetime'] = found_stock.datetime
            info['gain'] = found_stock.change
            info['percentchange'] = found_stock.percentChange
        else:
            info['name'] = "N/A"
            info['price'] = 0.00
            info['datetime'] = "N/A"
            info['gain'] = 0.00
            info['percentchange'] = 0.00

    return info
예제 #14
0
def getStocksFromSource(indexes=data, sortBy=SORT_BY_TOP):
    ''' '''
    stocks = []
    index = ['AGTC']
    # for stock in data["Ticker"][:100]:
    # for stock in index:
    for stock in data:
        try:
            print(stock)
            # print(type(stock))
            yf_data = yqd.load_yahoo_quote(stock, '20170301', '20170830')
            # yf_data = yqd.load_yahoo_quote('ABEO', '20170712', '20170725')
            # print(yf_data)
            share = Share(stock)

            # history part
            history = []
            for i, day in enumerate(yf_data[1:-1]):
                daily_data = day.split(',')
                history.append([
                    i,
                    str(daily_data[0]),
                    float(daily_data[1]),
                    float(daily_data[2]),
                    float(daily_data[3]),
                    float(daily_data[4]),
                    float(daily_data[6])
                ])

            # print(history)
            # comments part
            comments = []
            new_StockTwits_comments = []
            url = 'https://api.stocktwits.com/api/2/streams/symbol/{0}.json'.format(
                stock)
            print(url)
            try:
                r = requests.get(url).json()
                print(len(r['messages']))
                for message in r['messages']:
                    try:
                        new_tweet = {
                            'id':
                            message['id'],
                            'body':
                            message['body'],
                            'created_at':
                            message['created_at'],
                            'core_body':
                            nltk_service.clean_tweet(message['body']),
                            'nltk_sentiment':
                            nltk_service.get_tweet_sentiment(message['body']),
                            # 'azure_sentiment': azure_sentiment_service.GetSentiment(message['body'])
                        }
                        try:
                            new_tweet[
                                'azure_sentiment'] = azure_sentiment_service.GetSentiment(
                                    message['body'])
                        except Exception as e:
                            new_tweet['azure_sentiment'] = 0.5
                            print(e)
                        # print(new_tweet['azure_sentiment'])
                        new_StockTwits_comments.append(new_tweet)
                    except Exception as e:
                        print(e)
                        # pass
            except Exception as e:
                print('stock tweets part problem')
                print(e)
            # new_StockTwits_comments = [{'id': message['id'], 'body': message['body'], 'created_at': message['created_at']} for message in r['messages']]

            print(len(new_StockTwits_comments))
            stock = {
                'index': stock,
                'open': share.get_open(),
                'change': share.get_change(),
                'percent_change': share.get_percent_change(),
                'prev_close': share.get_prev_close(),
                'price': share.get_price(),
                'volume': share.get_volume(),
                'history': history,
                'new_StockTwits_comments': new_StockTwits_comments
            }
            # stock_json = json.dumps(stock)
            # print(type(stock_json))
            print(len(history))
            if len(history) != 0:
                # f.write(stock['index']+'/n')
                stocks.append(stock)
        except Exception as e:
            print(e)
            pass
    print(len(stocks))
    return stocks


# f.close()

# get_price()
# get_change()
# get_percent_change()
# get_volume()
# get_prev_close()
# get_open()
# get_avg_daily_volume()
# get_stock_exchange()
# get_market_cap()
# get_book_value()
# get_ebitda()
# get_dividend_share()
# get_dividend_yield()
# get_earnings_share()
# get_days_high()
# get_days_low()
# get_year_high()
# get_year_low()
# get_50day_moving_avg()
# get_200day_moving_avg()
# get_price_earnings_ratio()
# get_price_earnings_growth_ratio()
# get_price_sales()
# get_price_book()
# get_short_ratio()
# get_trade_datetime()
# get_historical(start_date, end_date)
# get_name()
# refresh()
# get_percent_change_from_year_high()
# get_percent_change_from_year_low()
# get_change_from_year_low()
# get_change_from_year_high()
# get_percent_change_from_200_day_moving_average()
# get_change_from_200_day_moving_average()
# get_percent_change_from_50_day_moving_average()
# get_change_from_50_day_moving_average()
# get_EPS_estimate_next_quarter()
# get_EPS_estimate_next_year()
# get_ex_dividend_date()
# get_EPS_estimate_current_year()
# get_price_EPS_estimate_next_year()
# get_price_EPS_estimate_current_year()
# get_one_yr_target_price()
# get_change_percent_change()
# get_dividend_pay_date()
# get_currency()
# get_last_trade_with_time()
# get_days_range()
# get_year_range()
예제 #15
0
def getPriceNChange(str):
    stock = Share(str)
    return stock.get_price() + ' ' + stock.get_change(
    ) + ' (' + stock.get_percent_change() + ')'
예제 #16
0
from yahoo_finance import Share
from config import _token
import requests
import json

sp = Share('^GSPC')
sp_price, sp_percent_change, sp.change = sp.get_price(), sp.get_percent_change(), sp.get_change()

nasdaq = Share('^IXIC')
nasdaq_price, nasdaq_percent_change, nasdaq_change = nasdaq.get_price(), nasdaq.get_percent_change(), nasdaq.get_change()


def get_dow():
	base = "http://globalindiceshistorical.xignite.com/xglobalindiceshistorical.json/GetLastClosingIndexValue"
	params = dict(
		IdentifierType="Symbol",
		Identifier="DJI2MN.IND_DJI",
		_fields=["Value.Close",
		"Value.PercentChangeFromPreviousClose"],
		_token=_token
		)
	response = requests.get(base, params)
	return response.json()

dow = get_dow()
dow_price = dow['Value']['Close']
final_dow = round(dow_price, 2)
dow_change = dow['Value']['PercentChangeFromPreviousClose']
final_dow_change = round(dow_change, 2)
float_dow = float(final_dow_change)
예제 #17
0
symbol = input('Please enter A stock symbol: ')

#mydata = quandl.get("WIKI/AAPL", rows=5)
stock = Share(symbol)

while stock.get_name() == None:
    print "you enter an invalid symbol or no network "
    symbol = input('Please enter A stock symbol: ')
    stock = Share(symbol)

now = datetime.datetime.now()

# cur_price = float(stock.get_price())
# open_price = float(stock.get_open())
# price_change = ""
# percentage_change = ""

# if cur_price > open_price:
#   price_change = cur_price - open_price
#   percentage_change = "(+{:.2%})".format(price_change/cur_price)
#   price_change = "+" + str(price_change)
# else:
#   price_change = open_price - cur_price
#   percentage_change = "(-{:.2%})".format(price_change/cur_price)
#   price_change = "-" + str(price_change)

print now
print stock.get_name(), "(" + symbol + ")"
#print cur_price, price_change, percentage_change
print stock.get_price(), stock.get_change(), stock.get_percent_change()
예제 #18
0
class Market:
    __PULL_INTERVAL_IN_MIN = 5
            
    def __init__ (self, s):
        self.share_string       = s
        self.share              = Share(s)
        
        self.current_price      = self.share.get_price()
        self.price              = self.current_price
        self.market_cap         = self.share.get_market_cap()
        self.open_price         = self.share.get_open()
        self.prev_close_price   = self.share.get_prev_close()
        self.percent_change     = self.share.get_percent_change()
        
        self.price_array = []
        self.time_array = []
    
    
    def pullPrices(self):
        file_string = "share_" + self.share_string + ".dat"
        dataFile = open(file_string, "w+")
        start_time = int(time.strftime("%-S"))
        last_time = start_time
        
        while (1 == 1):
            current_time = int(time.strftime("%-S"))
            if (current_time >= 60):
                current_time = 0
            
            if (current_time - last_time < 0):
                last_time = -60 - (current_time - last_time)
                
            if (int(time.strftime("%-S")) - last_time >= self.__PULL_INTERVAL_IN_MIN):
                dataFile.write (time.strftime('%l:%M%p, %b %d, %Y') + "\t")
                dataFile.write (self.share.get_price())
                dataFile.write ("\n")
                dataFile.flush ()
                last_time = int(time.strftime("%-S"))
    
    
    
    def __storeData(self, filename):
        dataFile = open(filename, "r")
        lineList = dataFile.readLines()
        
        for i in range(len(lineList)):
            index1 = lineList[i].index('\t')
            price = float(lineList[i][index1:])
            price_array.append(price)
        
        dataFile.close() 
    
    
    def getSlope(self, filename):
        __storeData(filename)
        
        length = len(self.price_array)
        current_slope = (self.price_array[length] - self.price_array[length-1])/(self.time_array[length] - self.time_array[length-1])
        return current_slope
        
        
    def getSecondDegreeSlope(self, filename):
        __storeData(filename)
        
        length = len(price_array)
        current_slope = (self.price_array[length] - self.price_array[length-1])/(self.time_array[length] - self.time_array[length-1])
        last_slope = (self.price_array[length-1] - self.price_array[length-2])/(self.time_array[length-1] - self.time_array[length-2])
        
        current_secondDegreeSlope = (current_slope - last_slope)/(self.time_array[length] - self.time_array[length-1])
        
        return current_secondDegreeSlope
예제 #19
0
def stock_quote_get():
    print(request.args.get('symbol'))
    symbol = str(request.args.get('symbol'))

    # get all the relevant data from the Yahoo Finance API
    stock = Share(symbol)

    stock_name = stock.get_name()
    stock_symbol = stock.symbol
    stock_price = stock.get_price()
    stock_change = stock.get_change()
    stock_change_pct = stock.get_percent_change()

    prev_close = stock.get_prev_close()
    open = stock.get_open()
    day_range = stock.get_days_range()
    year_range = stock.get_year_range()
    volume = stock.get_volume()
    avg_volume = stock.get_avg_daily_volume()
    market_cap = stock.get_market_cap()
    pe_ratio = stock.get_price_earnings_ratio()
    eps = stock.get_earnings_share()
    dividend = stock.get_dividend_share()
    dividend_yld = stock.get_dividend_yield()
    dividend_ex_date = stock.get_ex_dividend_date()
    yr_target = stock.get_one_yr_target_price()

    historical = stock.get_historical('2017-01-01',
                                      date.isoformat(date.today()))

    # put the data into the DynamoDB database
    table = dynamodb.Table('Stocks')
    response = table.put_item(
        Item={
            'symbol': symbol,
            'date': date.isoformat(date.today()),
            'prev_close': prev_close,
            'open': open,
            'day_range': day_range,
            'year_range': year_range,
            'volume': volume,
            'avg_volume': avg_volume,
            'market_cap': market_cap,
            'pe_ratio': pe_ratio,
            'eps': eps,
            'dividend': dividend,
            'dividend_yld': dividend_yld,
            'dividend_ex_date': dividend_ex_date,
            'yr_target': yr_target,
        })

    close_history = []

    for point in historical:
        close_date = point['Date']
        close_date = int(
            time.mktime(datetime.strptime(close_date, "%Y-%m-%d").timetuple()))
        close_price = point['Adj_Close']
        close_price = float(close_price)
        close_history.append([close_date, close_price])

    return render_template("stock/stock_detail.html",
                           stock_name=stock_name,
                           stock_symbol=stock_symbol,
                           stock_price=stock_price,
                           stock_change=stock_change,
                           stock_change_pct=stock_change_pct,
                           prev_close=prev_close,
                           open=open,
                           day_range=day_range,
                           year_range=year_range,
                           volume=volume,
                           avg_volume=avg_volume,
                           market_cap=market_cap,
                           pe_ratio=pe_ratio,
                           eps=eps,
                           dividend=dividend,
                           dividend_yld=dividend_yld,
                           dividend_ex_date=dividend_ex_date,
                           yr_target=yr_target,
                           close_history=close_history)
예제 #20
0
    return "None"


#accept input
while True:
    try:
        print("Input : ")
        symbolT = input("Please enter a symbol : ")
        company = get_symbol(symbolT.upper())
        while company.lower() in ("none", "networkerror"):
            if company == "NetworkError":
                exit()
            symbolT = input("Invalid Symbol. Please enter a valid symbol : ")
            company = get_symbol(symbolT.upper())
        #display output
        print("\nOutput : ")
        dt = datetime.datetime.now(tzlocal.get_localzone())
        print(dt.strftime("%a %b %d %H:%M:%S %Z %Y"))
        print(company + " (" + symbolT.upper() + ") ")
        stock = Share(symbolT)
        print(stock.get_price() + " " + stock.get_change() + " (" +
              stock.get_percent_change() + ") ")
        print("---------------------------------------------")
        cont = input("Do you want to continue? (Y/N) : ")
        if cont == 'Y' or cont == "y":
            continue
        else:
            break
    except ValueError:
        print("\nWrong Input! Please try again.")
예제 #21
0
def getPercentChange(Sym):
	ticker = Share(Sym)
	return ticker.get_percent_change()
예제 #22
0
class Market:
    __PULL_INTERVAL_IN_MIN = 5

    def __init__(self, s):
        self.share_string = s
        self.share = Share(s)

        self.current_price = self.share.get_price()
        self.price = self.current_price
        self.market_cap = self.share.get_market_cap()
        self.open_price = self.share.get_open()
        self.prev_close_price = self.share.get_prev_close()
        self.percent_change = self.share.get_percent_change()

        self.price_array = []
        self.time_array = []

    def pullPrices(self):
        file_string = "share_" + self.share_string + ".dat"
        dataFile = open(file_string, "w+")
        start_time = int(time.strftime("%-S"))
        last_time = start_time

        while (1 == 1):
            current_time = int(time.strftime("%-S"))
            if (current_time >= 60):
                current_time = 0

            if (current_time - last_time < 0):
                last_time = -60 - (current_time - last_time)

            if (int(time.strftime("%-S")) - last_time >=
                    self.__PULL_INTERVAL_IN_MIN):
                dataFile.write(time.strftime('%l:%M%p, %b %d, %Y') + "\t")
                dataFile.write(self.share.get_price())
                dataFile.write("\n")
                dataFile.flush()
                last_time = int(time.strftime("%-S"))

    def __storeData(self, filename):
        dataFile = open(filename, "r")
        lineList = dataFile.readLines()

        for i in range(len(lineList)):
            index1 = lineList[i].index('\t')
            price = float(lineList[i][index1:])
            price_array.append(price)

        dataFile.close()

    def getSlope(self, filename):
        __storeData(filename)

        length = len(self.price_array)
        current_slope = (
            self.price_array[length] - self.price_array[length - 1]) / (
                self.time_array[length] - self.time_array[length - 1])
        return current_slope

    def getSecondDegreeSlope(self, filename):
        __storeData(filename)

        length = len(price_array)
        current_slope = (
            self.price_array[length] - self.price_array[length - 1]) / (
                self.time_array[length] - self.time_array[length - 1])
        last_slope = (
            self.price_array[length - 1] - self.price_array[length - 2]) / (
                self.time_array[length - 1] - self.time_array[length - 2])

        current_secondDegreeSlope = (current_slope - last_slope) / (
            self.time_array[length] - self.time_array[length - 1])

        return current_secondDegreeSlope
예제 #23
0
    sys.stdout.write(stock['symbol'])
    try:
        if stock['symbol'] not in google_bad_list and '.' in stock['symbol']:
            equity_parsed = getQuotes(stock['symbol'])[0]
            sp900_all[stock['symbol']] = float(equity_parsed['ChangePercent'])
            sys.stdout.write(" {}\n".format(
                float(equity_parsed['ChangePercent'])))
            if DEBUG:
                sys.stdout.write("{}\t{}\t{}\t{}%".format(
                    stock['symbol'], stock['company'],
                    equity_parsed['LastTradePrice'],
                    equity_parsed['ChangePercent']))
        else:
            equity = Share(stock['symbol'])
            sp900_all[stock['symbol']] = float(
                equity.get_percent_change().strip('%')) / 100
            sys.stdout.write(" {}\n".format(
                float(equity.get_percent_change().strip('%')) / 100))
            if DEBUG:
                sys.stdout.write("{}\t{}\t{}\t{}".format(
                    stock['symbol'], equity.get_name(), equity.get_price(),
                    equity.get_percent_change()))
    except:
        pass

for ticker in sp900_all:
    if sp900_all[ticker] > 0.03 or sp900_all[ticker] < -0.03:
        sp900_chg[ticker] = sp900_all[ticker]

with open('result/SP900_{}.txt'.format(time.strftime("%Y%m%d%H%M%S")),
          'w') as fd: