<commit_before>import json
import requests
import urllib

class Robinhood:

    session = None

    username = None

    password = None

    headers = None

    auth_token = None

    data = {        
        'account_number': None
    }

    url = None

    endpoints = {
            "login": "https://api.robinhood.com/api-token-auth/",
            "investment_profile": "https://api.robinhood.com/user/investment_profile/",
            "accounts":"https://api.robinhood.com/accounts/",
            "ach_iav_auth":"https://api.robinhood.com/ach/iav/auth/",
            "ach_relationships":"https://api.robinhood.com/ach/relationships/",
            "ach_transfers":"https://api.robinhood.com/ach/transfers/",
            "applications":"https://api.robinhood.com/applications/",
            "dividends":"https://api.robinhood.com/dividends/",
            "edocuments":"https://api.robinhood.com/documents/",
            "instruments":"https://api.robinhood.com/instruments/",
            "margin_upgrades":"https://api.robinhood.com/margin/upgrades/",
            "markets":"https://api.robinhood.com/markets/",
            "notifications":"https://api.robinhood.com/notifications/",
            "orders":"https://api.robinhood.com/orders/",
            "password_reset":"https://api.robinhood.com/password_reset/request/",
            "quotes":"https://api.robinhood.com/quotes/",
            "document_requests":"https://api.robinhood.com/upload/document_requests/",
            "user":"https://api.robinhood.com/user/",
            "watchlists":"https://api.robinhood.com/watchlists/"
    }

    ##############################
    #Logging in and initializing
    ##############################

    def __init__(self, username, password):
        self.session = requests.session()
        self.session.proxies = urllib.getproxies()
        self.username = username
        self.password = password
        self.headers = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, nl;q=0.6, it;q=0.5",
            "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
            "X-Robinhood-API-Version": "1.0.0",
            "Connection": "keep-alive",
            "User-Agent": "Robinhood/823 (iPhone; iOS 7.1.2; Scale/2.00)"
        }
        self.session.headers = self.headers
        self.login()

    def login(self):
        data = "password=%s&username=%s" % (self.password, self.username)
        res = self.session.post(self.endpoints['login'], data=data)
        res = res.json()
        self.auth_token = res['token']
        self.headers['Authorization'] = 'Token '+self.auth_token


    ##############################
    #GET DATA 
    ##############################

    def investment_profile(self):
        return self.session.get(self.endpoints['investment_profile'])

    def instruments(self, stock=None):
        res = self.session.get(self.endpoints['instruments'], params={'query':stock.upper()})
        res = res.json()
        return res['results']

    def accounts(self):
        accounts = self.session.get(self.endpoints['accounts'])
        self.url = accounts.json()['results'][0]['url']
        self.data['account_number'] = accounts.json()['results'][0]['account_number']
        self.data['buying_power'] = accounts.json()['results'][0]['buying_power']
        return accounts

    def user(self):
        return self.session.get(self.endpoints['user'])

    def portfolio(self):
        if self.url == None:
            self.accounts()
        portfolio = self.session.get(self.url+"portfolio/")
        self.data['portfolio_current_value'] = portfolio.json()['market_value']
        self.data['portfolio_previous_value'] = portfolio.json()['adjusted_equity_previous_close']
        return portfolio

    def holdings(self):
        if self.url == None:
            self.accounts()
        holdings = self.session.get(self.url+"positions/")
        return holdings

    def quote_data(self, stock=None):
        #Prompt for stock if not entered
        if stock is None:
            stock = raw_input("Symbol: ");
        url = str(self.endpoints['quotes']) + str(stock) + "/"
        #Check for validity of symbol
        try:
            res = json.loads((urllib.urlopen(url)).read());
            if len(res) > 0:
                return res;
            else:
                raise NameError("Invalid Symbol: " + stock);
        except (ValueError):
            raise NameError("Invalid Symbol: " + stock);

    def get_quote(self, stock=None):
        data = self.quote_data(stock)
        return data["symbol"]

    def print_quote(self, stock=None):
        data = self.quote_data(stock)
        print(data["symbol"] + ": $" + data["last_trade_price"]);

    def print_quotes(self, stocks):
        for i in range(len(stocks)):
            self.print_quote(stocks[i]);

    def ask_price(self, stock=None):
        return self.quote_data(stock)['ask_price'];

    def ask_size(self, stock=None):
        return self.quote_data(stock)['ask_size'];

    def bid_price(self, stock=None):
        return self.quote_data(stock)['bid_price'];

    def bid_size(self, stock=None):
        return self.quote_data(stock)['bid_size'];

    def last_trade_price(self, stock=None):
        return self.quote_data(stock)['last_trade_price'];

    def last_trade_price(self, stock=None):
        return self.quote_data(stock)['last_trade_price'];

    def previous_close(self, stock=None):
        return self.quote_data(stock)['previous_close'];

    def previous_close_date(self, stock=None):
        return self.quote_data(stock)['previous_close_date'];

    def adjusted_previous_close(self, stock=None):
        return self.quote_data(stock)['adjusted_previous_close'];

    def symbol(self, stock=None):
        return self.quote_data(stock)['symbol'];

    def last_updated_at(self, stock=None):
        return self.quote_data(stock)['updated_at'];

    def dividends(self):
        return self.session.get(self.endpoints['dividends'])


    ##############################
    #PLACE ORDER<commit_msg>Added portfolio and holdings print functions. Rearranged some function layouts<commit_after>import json
import requests
import urllib

class Robinhood:

    session = None

    username = None

    password = None

    headers = None

    auth_token = None

    data = {        
        'account_number': None
    }

    url = None

    endpoints = {
            "login": "https://api.robinhood.com/api-token-auth/",
            "investment_profile": "https://api.robinhood.com/user/investment_profile/",
            "accounts":"https://api.robinhood.com/accounts/",
            "ach_iav_auth":"https://api.robinhood.com/ach/iav/auth/",
            "ach_relationships":"https://api.robinhood.com/ach/relationships/",
            "ach_transfers":"https://api.robinhood.com/ach/transfers/",
            "applications":"https://api.robinhood.com/applications/",
            "dividends":"https://api.robinhood.com/dividends/",
            "edocuments":"https://api.robinhood.com/documents/",
            "instruments":"https://api.robinhood.com/instruments/",
            "margin_upgrades":"https://api.robinhood.com/margin/upgrades/",
            "markets":"https://api.robinhood.com/markets/",
            "notifications":"https://api.robinhood.com/notifications/",
            "orders":"https://api.robinhood.com/orders/",
            "password_reset":"https://api.robinhood.com/password_reset/request/",
            "quotes":"https://api.robinhood.com/quotes/",
            "document_requests":"https://api.robinhood.com/upload/document_requests/",
            "user":"https://api.robinhood.com/user/",
            "watchlists":"https://api.robinhood.com/watchlists/"
    }

    ##############################
    #Logging in and initializing
    ##############################

    def __init__(self, username, password):
        self.session = requests.session()
        self.session.proxies = urllib.getproxies()
        self.username = username
        self.password = password
        self.headers = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, nl;q=0.6, it;q=0.5",
            "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
            "X-Robinhood-API-Version": "1.0.0",
            "Connection": "keep-alive",
            "User-Agent": "Robinhood/823 (iPhone; iOS 7.1.2; Scale/2.00)"
        }
        self.session.headers = self.headers
        self.login()
        self.accounts()
        self.portfolio()
        self.holdings()

    def login(self):
        data = "password=%s&username=%s" % (self.password, self.username)
        res = self.session.post(self.endpoints['login'], data=data)
        res = res.json()
        self.auth_token = res['token']
        self.headers['Authorization'] = 'Token '+self.auth_token


    ##############################
    # USER DATA 
    ##############################

    def accounts(self):
        accounts = self.session.get(self.endpoints['accounts'])
        self.url = accounts.json()['results'][0]['url']
        self.data['account_number'] = accounts.json()['results'][0]['account_number']
        self.data['buying_power'] = accounts.json()['results'][0]['buying_power']
        return accounts

    def user(self):
        return self.session.get(self.endpoints['user'])

    ##############################
    # PORTFOLIO DATA 
    ##############################

    def investment_profile(self):
        return self.session.get(self.endpoints['investment_profile'])   

    def portfolio(self):
        portfolio = self.session.get(self.url+"portfolio/")
        self.data['portfolio_current_value'] = portfolio.json()['market_value']
        return portfolio

    def holdings(self):
        holdings = self.session.get(self.url+"positions/")
        self.data['holdings'] = []
        
        for holding in holdings.json()['results']:
            instrument = self.session.get(holding['instrument']).json()
            newHolding = {
                'symbol': instrument['symbol'],
                'name': instrument['name'],
                'current_price': holding['average_buy_price'],
                #'purchase_price': holding['price'],
                'shares': holding['quantity']
            }
            self.data['holdings'].append(newHolding)

        return holdings

    def dividends(self):
        return self.session.get(self.endpoints['dividends'])

    def print_porfolio_header(self):
        print '*** Porfolio ***'
        print 'Current Value: ' + self.data['portfolio_current_value'] + ' Buying Power: ' + self.data['buying_power']

    def print_holdings(self):
        print "*** Holdings ***"
        for holding in self.data['holdings']:
            print holding['name'] + ' (' + holding['symbol'] + ')' + ' Shares: ' + holding['shares'] + ' Current Price: ' + holding['current_price']


    ##############################
    # STOCK DATA 
    ##############################

    def instruments(self, stock=None):
        res = self.session.get(self.endpoints['instruments'], params={'query':stock.upper()})
        res = res.json()
        return res['results'] 

    def quote_data(self, stock=None):
        #Prompt for stock if not entered
        if stock is None:
            stock = raw_input("Symbol: ");
        url = str(self.endpoints['quotes']) + str(stock) + "/"
        #Check for validity of symbol
        try:
            res = json.loads((urllib.urlopen(url)).read());
            if len(res) > 0:
                return res;
            else:
                raise NameError("Invalid Symbol: " + stock);
        except (ValueError):
            raise NameError("Invalid Symbol: " + stock);

    def get_quote(self, stock=None):
        data = self.quote_data(stock)
        return data["symbol"]

    def print_quote(self, stock=None):
        data = self.quote_data(stock)
        print(data["symbol"] + ": $" + data["last_trade_price"]);

    def print_quotes(self, stocks):
        for i in range(len(stocks)):
            self.print_quote(stocks[i]);

    def ask_price(self, stock=None):
        return self.quote_data(stock)['ask_price'];

    def ask_size(self, stock=None):
        return self.quote_data(stock)['ask_size'];

    def bid_price(self, stock=None):
        return self.quote_data(stock)['bid_price'];

    def bid_size(self, stock=None):
        return self.quote_data(stock)['bid_size'];

    def last_trade_price(self, stock=None):
        return self.quote_data(stock)['last_trade_price'];

    def last_trade_price(self, stock=None):
        return self.quote_data(stock)['last_trade_price'];

    def previous_close(self, stock=None):
        return self.quote_data(stock)['previous_close'];

    def previous_close_date(self, stock=None):
        return self.quote_data(stock)['previous_close_date'];

    def adjusted_previous_close(self, stock=None):
        return self.quote_data(stock)['adjusted_previous_close'];

    def symbol(self, stock=None):
        return self.quote_data(stock)['symbol'];

    def last_updated_at(self, stock=None):
        return self.quote_data(stock)['updated_at'];


    ##############################
    #PLACE ORDER
{'fraction_non_alphanumeric': 0.1792361163016668, 'fraction_numerical': 0.004185664100455938, 'mean_word_length': 2.6617405582922826, 'pattern_counts': {'":': 54, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 38, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3769968', 'n_tokens_mistral': 4110, 'n_tokens_neox': 3951, 'n_words': 623}