Пример #1
0
def login_robinhood(path_to_credentials):
    from fast_arrow import Client
    credentials = open(path_to_credentials, 'r').read()
    credentials = credentials.split("\n")
    client = Client(username=credentials[0], password=credentials[1])
    print(client.authenticate())
    return client
    def __init__(self, username, password):
        """The Biggest Challenge to Using the Robinhood Data is figuring out the client
        authentication. They use Multifactor authentication, so you have to figure out a way
        to add your credentials. The way I have it set up is that I get an email, adn the code
        automatically parses my email to get the code."""

        self.client = Client(username=username, password=password)
        self.client.authenticate()  # this part can use some finagling.
Пример #3
0
class Robinhood:
    def __init__(self):
        username, password, device_token = self.setup()
        self.username = username
        self.password = password
        self.device_token = device_token

    def setup(self):
        config_path = os.path.join(os.path.dirname(__file__), '../config.local.json')
        username = ''
        password = ''
        device_token = None
        with open(config_path) as config_file:
            config = json.load(config_file)
            username = config['robinhood']['username']
            password = config['robinhood']['password']
            device_token = config['robinhood']['device-token']
        return (username, password, device_token)

    def login(self):
        self.client = Client(
            username=self.username,
            password=self.password,
            device_token=self.device_token)
        self.result = self.client.authenticate()
        self.user = User.fetch(self.client)

        print("Authenticated successfully = {}".format(self.result))
        print("Account Url = {}".format(self.client.account_url))
        print("Account Id = {}".format(self.client.account_id))

        print("Username = {}".format(self.user["username"]))
        print()

        # Set client to legacy version for further use
        auth_data = self.client.gen_credentials()
        self.client = ClientLegacy(auth_data)
        return self.client

    def get_quote(self, symbol):
        return StockMarketdata.quote_by_symbol(self.client, symbol)

    def get_option_chain(self, symbol, stock):
        stock_id = stock["instrument"].split("/")[-2]
        return OptionChain.fetch(self.client, stock_id, symbol)

    def get_next_3_exp_options(self, option_chain):
        option_chain_id = option_chain["id"]
        expiration_dates = option_chain['expiration_dates']

        next_3_expiration_dates = expiration_dates[0:3]

        ops = Option.in_chain(self.client, option_chain_id, expiration_dates=next_3_expiration_dates)
        ops = Option.mergein_marketdata_list(client, ops)
        return ops
Пример #4
0
    def login(self):
        self.client = Client(
            username=self.username,
            password=self.password,
            device_token=self.device_token)
        self.result = self.client.authenticate()
        self.user = User.fetch(self.client)

        print("Authenticated successfully = {}".format(self.result))
        print("Account Url = {}".format(self.client.account_url))
        print("Account Id = {}".format(self.client.account_id))

        print("Username = {}".format(self.user["username"]))
        print()

        # Set client to legacy version for further use
        auth_data = self.client.gen_credentials()
        self.client = ClientLegacy(auth_data)
        return self.client
Пример #5
0
import configparser
from fast_arrow import Client, OptionOrder

print("----- running {}".format(__file__))

config = configparser.ConfigParser()
config.read('config.debug.ini')

#
# initialize fast_arrow client and authenticate
#
client = Client(username=config['account']['username'],
                password=config['account']['password'])

client.authenticate()

#
# fetch option orders
#
option_orders_all = OptionOrder.all(client)

#
# in case you have lots, only use first 25
# (unroll process fetches contract data for each leg)
#
option_orders = option_orders_all[0:25]

#
# unroll option orders ... ie, break each option leg into its own row
# this is helpful when doing detailed P/L reporting
#
Пример #6
0
from datatype_tools.lib import *
from print_tools.printer import Printer
from fast_arrow import Client, OptionChain, Option, OptionPosition, OptionOrder

#: Login

p = Printer()
client = Client()
client.authenticate()

#: Get Positions

positions = OptionPosition.all(client)
positions = list(filter(lambda p: float(p["quantity"]) > 0.0, positions))

if (len(positions) > 0):
    positions = OptionPosition.mergein_marketdata_list(client, positions)
    positions = OptionPosition.mergein_instrumentdata_list(client, positions)
    positions = OptionPosition.mergein_orderdata_list(client, positions)

    #: Get Most Recent Order

    symbol = positions[0]['chain_symbol']
    strat = positions[0]['option_type']
    effect = positions[0]['type']
    buy_price = positions[0]['average_price']
    bid_price = positions[0]['bid_price']
    expiration_date = positions[0]['expiration_date']
    quantity = positions[0]['quantity']
    url = positions[0]['instrument']
Пример #7
0
def _init_client(username, password):
    client = Client(username=username, password=password)
    client.authenticate()
    return client
Пример #8
0
 def test_init(self):
     auth_data = self.example_auth_data()
     Client(auth_data)
Пример #9
0
print("----- running {}".format(__file__))

#
# get the authentication configs
#
config_file = "config.debug.ini"
config = configparser.ConfigParser()
config.read(config_file)
username = config['account']['username']
password = config['account']['password']

#
# initialize and authenticate Client
#
client = Client(username=username, password=password)
client.authenticate()

#
# fetch spy options
#
symbol = "SPY"
stock = Stock.fetch(client, symbol)
stock = Stock.mergein_marketdata_list(client, [stock])[0]

oc = OptionChain.fetch(client, stock["id"], symbol)
ed = oc['expiration_dates'][0]
ops = Option.in_chain(client, oc["id"], expiration_dates=[ed])

#
# enrich options with market data
Пример #10
0
def gen_client():
    return Client()
class Robinhood_Data:
    """This code uses fast-arrow, a library developed by
    Weston Platter. It's excellent, and it showcases the power of
    the Robinhood API. You can find the API here...

    https://github.com/westonplatter/fast_arrow.

    While the brokerage has its limits, it's great for real time Options Market
    Analyses."""
    def __init__(self, username, password):
        """The Biggest Challenge to Using the Robinhood Data is figuring out the client
        authentication. They use Multifactor authentication, so you have to figure out a way
        to add your credentials. The way I have it set up is that I get an email, adn the code
        automatically parses my email to get the code."""

        self.client = Client(username=username, password=password)
        self.client.authenticate()  # this part can use some finagling.

    def get_spot_price(self, symbol):
        """Returns a dictionary of data about the spot price,
        which includes bid, ask, bid size, ask size, as well as some api identification"""

        stock1 = Stock.fetch(self.client, symbol)
        stock = StockMarketdata.quote_by_instrument(self.client,
                                                    _id=stock1['id'])

        return stock

    def _process_spot_price(self, spot_price_object):
        """returns mid point price"""
        return (float(spot_price_object['bid_price']) +
                float(spot_price_object['ask_price'])) / 2

    def __convert_to_float(self, x):

        try:
            return np.float(x)
        except:
            return x

    def get_options_robinhood(self, symbol, **exp):
        """Get Robinhood Options Chains for Puts and Calls.
        The code returns three objects. This code returns two pandas dataframes
        The first is Calls, the Second is Puts. The final output is the spot price.


        """

        try:
            stock = Stock.fetch(self.client, symbol)
            stock_id = stock["id"]
            option_chain = OptionChain.fetch(self.client,
                                             stock_id,
                                             symbol=symbol)
            eds = option_chain['expiration_dates']

            oc_id = option_chain["id"]

            spot = self.get_spot_price(symbol)

            spot_price = self._process_spot_price(spot)
            if exp:
                if exp['exp'] not in eds:
                    print(
                        'Expiry not a Valid Expiration,Here are the valid Expirations \n'
                    )
                    print(eds)
                    return np.nan, np.nan, np.nan

                expiry = exp['exp']
                eds = [expiry]
            else:
                print(
                    'Expiry not a Valid Expiration,Here are the valid Expirations \n'
                )
                print(eds)
                return np.nan, np.nan, np.nan

            ops = Option.in_chain(self.client, oc_id, expiration_dates=eds)
            ops = Option.mergein_marketdata_list(self.client, ops)
            df = pd.DataFrame(ops)
            df.index = np.arange(0, len(df))

            #calls = df.loc[df.type=='call']
            #calls = calls.sort_index()
            #puts = df.loc[df.type=='put']
            #puts = puts.sort_index()
            df['spot_price'] = spot_price
            #puts['spot_price'] = spot_price
            df = df.applymap(self.__convert_to_float)
            df['expiration_date'] = pd.to_datetime(
                df['expiration_date'].values)
            #puts  = puts.applymap(self.__convert_to_float)

            return df.fillna(0)

        except:
            return pd.DataFrame()

    def get_all_options_robinhood(self, symbol):
        """Here, we use a library called 'DASK' to parallelize our code to fetch the data. We can be clever
        and fetch it all at once, to HOPEFULLY, speed up data retrieval for our larger datasets,
        like SPY and AMZN, to name a couple.
        from dask import delayed"""

        df_list = []
        stock = Stock.fetch(self.client, symbol)
        stock_id = stock["id"]
        expiries = OptionChain.fetch(self.client, stock_id,
                                     symbol=symbol)['expiration_dates']

        for expiration_date in expiries:
            #print(expiration_date)
            y = delayed(self.get_options_robinhood)(symbol,
                                                    exp=expiration_date)
            df_list.append(y)

        ans = delayed(pd.concat)(df_list)
        df = ans.compute()
        return df.loc[df.type == 'call'], df.loc[df.type ==
                                                 'put'], df.spot_price.iloc[0]
Пример #12
0
from fast_arrow import (Client, StockMarketdata)

#
# initialize. Don't need to authenticate for stock data.
#
client = Client()

#
# fetch price quote data
#
symbol = "SQ"
stock = StockMarketdata.quote_by_symbol(client, symbol)

print("{} ask_price = {}".format(stock['symbol'], stock['ask_price']))
print("{} bid_price = {}".format(stock['symbol'], stock['bid_price']))
Пример #13
0
 def test_current_auth_data(self):
     auth_data = self.example_auth_data()
     client = Client(auth_data)
     ad = client.current_auth_data()
     for key in auth_data.keys():
         assert (auth_data[key] == ad[key])
Пример #14
0
 def test_init_validates_auth_data(self):
     auth_data = self.example_auth_data()
     del auth_data['account_id']
     with self.assertRaises(AuthDataError):
         Client(auth_data)
import configparser
from fast_arrow import Client
from fast_arrow import Portfolio

#
# get the authentication configs
#
config_file = "config.debug.ini"
config = configparser.ConfigParser()
config.read(config_file)
username = config['account']['username']
password = config['account']['password']
account = config['account']['account']

client = Client(username=username, password=password)
result = client.authenticate()

span = "year"
bounds = "regular"
portfolio_historicals = Portfolio.historical(client, account, span, bounds)

ehs = portfolio_historicals["equity_historicals"]
begins_at = ehs[-1]["begins_at"]
ends_at = ehs[0]["begins_at"]

print(ehs[0].keys())

print("Fetched portfolio data between {} and {}".format(begins_at, ends_at))
Пример #16
0
import configparser
from fast_arrow import Client
from fast_arrow.resources.user import User

print("----- running {}".format(__file__))

#
# get the authentication configs
#
config_file = "config.debug.ini"
config = configparser.ConfigParser()
config.read(config_file)
username = config['account']['username']
password = config['account']['password']

client = Client(username=username, password=password)
result = client.authenticate()

print("Authenticated successfully = {}".format(result))

print("Account Url = {}".format(client.account_url))
print("Account Id = {}".format(client.account_id))

user = User.fetch(client)
print("Username = {}".format(user["username"]))

result = client.relogin_oauth2()
print("Re-Authenticated with refresh_token successfully = {}".format(result))

result = client.logout_oauth2()
print("Logged out successfully = {}".format(result))
 def initialize(self) -> None:
     '''
     Initializes the client by authenticating against the Robinhood exchange.
     '''
     if self.client is None:
         self.client = Client(self.__gen_credentials())
Пример #18
0
def gen_client():
    auth_data = gen_auth_data()
    client = Client(auth_data)
    return client
Пример #19
0
    Option,
)

print("----- running {}".format(__file__))

#
# get auth_data (see https://github.com/westonplatter/fast_arrow_auth)
#
with open("fast_arrow_auth.json") as f:
    auth_data = json.loads(f.read())


#
# initialize client with auth_data
#
client = Client(auth_data)


#
# fetch the stock info for TLT
#
symbol = "TLT"
md = StockMarketdata.quote_by_symbol(client, symbol)


#
# get the TLT option chain info
#
stock_id = md["instrument"].split("/")[-2]
option_chain = OptionChain.fetch(client, stock_id, symbol)
option_chain_id = option_chain["id"]
Пример #20
0
import json

from fast_arrow import Client
from fast_arrow.resources.user import User

print("----- running {}".format(__file__))

#
# get auth_data (see https://github.com/westonplatter/fast_arrow_auth)
#
with open("fast_arrow_auth.json") as f:
    auth_data = json.loads(f.read())

#
# initialize client with auth_data
#
client = Client(auth_data)

print("Account Id = {}".format(client.account_id))

user = User.fetch(client)
print("Username = {}".format(user["username"]))

result = client.relogin_oauth2()
print("Re-Authenticated with refresh_token successfully = {}".format(result))

refreshed_auth_data = client.current_auth_data()
filename = "fast_arrow_auth.json"
with open(filename, "w") as f:
    f.write(json.dumps(refreshed_auth_data, indent=4))