Beispiel #1
0
    def setUp(self) -> None:
        """Set up the Stock Frame."""

        # Grab configuration values.
        config = ConfigParser()
        config.read('configs/config.ini')

        CLIENT_ID = config.get('main', 'CLIENT_ID')
        REDIRECT_URI = config.get('main', 'REDIRECT_URI')
        CREDENTIALS_PATH = config.get('main', 'JSON_PATH')

        # Create a robot.
        self.robot = PyRobot(client_id=CLIENT_ID,
                             redirect_uri=REDIRECT_URI,
                             credentials_path=CREDENTIALS_PATH)

        # Grab historical prices, first define the start date and end date.
        start_date = datetime.today()
        end_date = start_date - timedelta(days=30)

        # Grab the historical prices.
        historical_prices = self.robot.grab_historical_prices(
            start=end_date,
            end=start_date,
            bar_size=1,
            bar_type='minute',
            symbols=['AAPL', 'MSFT'])

        # Convert data to a Data Frame.
        self.stock_frame = self.robot.create_stock_frame(
            data=historical_prices['aggregated'])
Beispiel #2
0
def set_historical_prices(trading_robot: PyRobot):
	"""
		Set the historical prices for the robot

		:param trading_robot {PyRobot} -- The trading robot class
	"""

	end_date = datetime.today()
	start_date = end_date - timedelta(days=20)

	# Get historical data
	historical_prices = trading_robot.grab_historical_prices(
		start=start_date,
		end=end_date,
		bar_size=1,
		bar_type='minute'
	)

	# Convert data to a stock frame
	stock_frame = trading_robot.create_stock_frame(
		data=historical_prices['aggregated']
	)

	# Add the stock frame to the portfolio
	trading_robot.portfolio.stock_frame = stock_frame
	trading_robot.portfolio.historical_prices = historical_prices
Beispiel #3
0
def set_trade(trading_robot: PyRobot, trading_symbol: str,
              current_price: int,
              available_funds,
              max_percent: float = None) -> dict:
	"""
	Create order legs and set the qty based on how much of my portfolio
	  I want to trade at one time
	:param trading_robot: the robot
	:param trading_symbol: the ticker symbol for the trades
	:param max_percent: max percentage of my portfolio I want for a single trade
	:param current_price: current candle open price
	:param available_funds: current amount I can trade with
	:return: trade dictionary
	"""

	qty = round((available_funds * max_percent) / current_price) if max_percent else 1

	new_enter_trade = trading_robot.create_trade(
		trade_id='long_enter',
		enter_or_exit='enter',
		long_or_short='long',
		order_type='mkt'
	)

	# Add an Order Leg
	new_enter_trade.instrument(
		symbol=trading_symbol,
		quantity=qty,
		asset_type='EQUITY'
	)

	# Create a new Trade Object for Exiting position
	new_exit_trade = trading_robot.create_trade(
		trade_id='long_exit',
		enter_or_exit='exit',
		long_or_short='long',
		order_type='mkt'
	)

	# Add an Order Leg
	new_exit_trade.instrument(
		symbol=trading_symbol,
		quantity=qty,
		asset_type='EQUITY'
	)

	return {
		trading_symbol: {
			'buy': {
				'trade_func': trading_robot.trades['long_enter'],
				'trade_id': trading_robot.trades['long_enter'].trade_id
			},
			'sell': {
				'trade_func': trading_robot.trades['long_exit'],
				'trade_id': trading_robot.trades['long_exit'].trade_id
			},
		}
	}
    def setUp(self) -> None:
        """Set up the Robot."""

        # Grab configuration values.
        config = ConfigParser()
        config.read('configs/config.ini')

        CLIENT_ID = config.get('main', 'CLIENT_ID')
        REDIRECT_URI = config.get('main', 'REDIRECT_URI')
        CREDENTIALS_PATH = config.get('main', 'JSON_PATH')
        self.ACCOUNT_NUMBER = config.get('main', 'ACCOUNT_NUMBER')

        self.robot = PyRobot(client_id=CLIENT_ID,
                             redirect_uri=REDIRECT_URI,
                             credentials_path=CREDENTIALS_PATH)
Beispiel #5
0
def sell_out_trade_to_execute(trading_symbol: str, trading_robot: PyRobot):
	# Set the cancel time to 1 day out
	gtc_date = datetime.now() - timedelta(days=1)
	# Create a new Trade Object for Exiting position
	new_exit_trade = trading_robot.create_trade(
		trade_id='sell_out_exit',
		enter_or_exit='exit',
		long_or_short='long',
		order_type='mkt'
	)
	# Make the trade good till cancel
	new_exit_trade.good_till_cancel(gtc_date)

	# todo set the quantity to be the currently held quantity
	# Add an Order Leg
	new_exit_trade.instrument(
		symbol=trading_symbol,
		quantity=1,
		asset_type='EQUITY'
	)

	return {
		trading_symbol: {
			'buy': {},
			'sell': {
				'trade_func': trading_robot.trades['sell_out_exit'],
				'trade_id': trading_robot.trades['sell_out_exit'].trade_id
			},
		}
	}
Beispiel #6
0
class PyRobotIndicatorTest(TestCase):
    """Will perform a unit test for the Indicator Object."""
    def setUp(self) -> None:
        """Set up the Indicator Client."""

        # Grab configuration values.
        config = ConfigParser()
        config.read('configs/config.ini')

        CLIENT_ID = config.get('main', 'CLIENT_ID')
        REDIRECT_URI = config.get('main', 'REDIRECT_URI')
        CREDENTIALS_PATH = config.get('main', 'JSON_PATH')

        # Create a robot.
        self.robot = PyRobot(client_id=CLIENT_ID,
                             redirect_uri=REDIRECT_URI,
                             credentials_path=CREDENTIALS_PATH)

        # Grab historical prices, first define the start date and end date.
        start_date = datetime.today()
        end_date = start_date - timedelta(days=30)

        # Grab the historical prices.
        historical_prices = self.robot.grab_historical_prices(
            start=end_date,
            end=start_date,
            bar_size=1,
            bar_type='minute',
            symbols=['AAPL', 'MSFT'])

        # Convert data to a Data Frame.
        self.stock_frame = self.robot.create_stock_frame(
            data=historical_prices['aggregated'])

    def test_creates_instance_of_session(self):
        """Create an instance and make sure it's a StockFrame."""

        self.assertIsInstance(self.stock_frame, StockFrame)
Beispiel #7
0
 def __init__(self,
              client_id: str,
              redirect_uri: str,
              paper_trading: bool = True,
              credentials_path: str = None,
              trading_account: str = None):
     super().__init__(client_id, redirect_uri, paper_trading,
                      credentials_path, trading_account)
     """*** Properties*** """
     self.py_robot = PyRobot(client_id, redirect_uri, paper_trading,
                             credentials_path, trading_account)
     self.tickers = ['PLTR']
     self.db_connection = None
     # todo uhhh idk if I need to store all data in one table or each ticker in its own table...
     # self.db_table_names = ['rawData', 'processedData', 'models']
     self._agent: Agent = None
     self._indicator_client: Indicators = None
     self._signals = dict
     # Actions
     """*** Actions (order matters) ***"""
     self.initialize_db()
     self.create_portfolio()
Beispiel #8
0
class PyRobotStockFrameTest(TestCase):
    """Will perform a unit test for the StockFrame Object."""
    def setUp(self) -> None:
        """Set up the Stock Frame."""

        # Grab configuration values.
        config = ConfigParser()
        config.read('configs/config.ini')

        CLIENT_ID = config.get('main', 'CLIENT_ID')
        REDIRECT_URI = config.get('main', 'REDIRECT_URI')
        CREDENTIALS_PATH = config.get('main', 'JSON_PATH')

        # Create a robot.
        self.robot = PyRobot(client_id=CLIENT_ID,
                             redirect_uri=REDIRECT_URI,
                             credentials_path=CREDENTIALS_PATH)

        # Grab historical prices, first define the start date and end date.
        start_date = datetime.today()
        end_date = start_date - timedelta(days=30)

        # Grab the historical prices.
        historical_prices = self.robot.grab_historical_prices(
            start=end_date,
            end=start_date,
            bar_size=1,
            bar_type='minute',
            symbols=['AAPL', 'MSFT'])

        # Convert data to a Data Frame.
        self.stock_frame = self.robot.create_stock_frame(
            data=historical_prices['aggregated'])

    def test_creates_instance_of_session(self):
        """Create an instance and make sure it's a StockFrame."""

        self.assertIsInstance(self.stock_frame, StockFrame)

    def test_frame_property(self):
        """Test that the `frame` property returns a Pandas DataFrame object."""

        self.assertIsInstance(self.stock_frame.frame, pd.DataFrame)
        self.assertIsInstance(self.stock_frame.frame.index, pd.MultiIndex)

    def test_frame_symbols(self):
        """Test that the `frame.index` property contains the specified symbols."""

        self.assertIn('AAPL', self.stock_frame.frame.index)
        self.assertIn('MSFT', self.stock_frame.frame.index)

    def test_symbol_groups_property(self):
        """Test that the `symbol_groups` property returns a Pandas DataFrameGroupBy object."""

        self.assertIsInstance(self.stock_frame.symbol_groups,
                              pd.core.groupby.DataFrameGroupBy)

    def test_symbol_rolling_groups_property(self):
        """Test that the `symbol_rolling_groups` property returns a Pandas RollingGroupBy object."""

        self.assertIsInstance(self.stock_frame.symbol_rolling_groups(size=15),
                              pd.core.window.RollingGroupby)

    def test_add_row(self):
        """Test adding a new row to our data frame."""

        # Define a new row.
        new_row_dict = {
            'AAPL': {
                'openPrice': 100.00,
                'closePrice': 100.00,
                'highPrice': 100.00,
                'lowPrice': 100.00,
                'askSize': 100,
                'bidSize': 100,
                'quoteTimeInLong': 1586390399572
            }
        }

        # Add the row.
        self.stock_frame.add_rows(data=new_row_dict)

        # Create a timestamp.
        time_stamp_parsed = pd.to_datetime(1586390399572,
                                           unit='ms',
                                           origin='unix')
        index_tuple = ('AAPL', time_stamp_parsed)

        # Check to see if the Tuple is in the Index.
        self.assertIn(index_tuple, self.stock_frame.frame.index)

    def tearDown(self) -> None:
        """Teardown the StockFrame."""

        self.stock_frame = None
class PyRobotTest(TestCase):
    """Will perform a unit test for the PyRobot Object."""
    def setUp(self) -> None:
        """Set up the Robot."""

        # Grab configuration values.
        config = ConfigParser()
        config.read('configs/config.ini')

        CLIENT_ID = config.get('main', 'CLIENT_ID')
        REDIRECT_URI = config.get('main', 'REDIRECT_URI')
        CREDENTIALS_PATH = config.get('main', 'JSON_PATH')
        self.ACCOUNT_NUMBER = config.get('main', 'ACCOUNT_NUMBER')

        self.robot = PyRobot(client_id=CLIENT_ID,
                             redirect_uri=REDIRECT_URI,
                             credentials_path=CREDENTIALS_PATH)

    def test_creates_instance_of_session(self):
        """Create an instance and make sure it's a robot."""

        self.assertIsInstance(self.robot, PyRobot)

    def test_create_portofolio(self):
        """Call `create_portfolio` and make sure it's a Portfolio."""

        new_portfolio = self.robot.create_portfolio()

        self.assertIsInstance(new_portfolio, Portfolio)

    def test_regular_market_open(self):
        """Tests whether Market is Open"""

        right_now = datetime.now().replace(tzinfo=timezone.utc).timestamp()
        regular_market_start_time = datetime.now().replace(
            hour=14, minute=30, second=00, tzinfo=timezone.utc).timestamp()
        regular_market_end_time = datetime.now().replace(
            hour=21, minute=00, second=00, tzinfo=timezone.utc).timestamp()

        if regular_market_end_time >= right_now >= regular_market_start_time:
            open = True
        else:
            open = False

        self.assertEqual(open, self.robot.regular_market_open)
        """
        Pre
        09:00
        14:30

        Regular
        14:30
        21:00

        Post
        21:00
        01:00
        """

    def test_pre_market_open(self):
        """Tests whether US Pre-Market is Open"""

        right_now = datetime.now().replace(tzinfo=timezone.utc).timestamp()
        pre_market_start_time = datetime.now().replace(
            hour=9, minute=00, second=00, tzinfo=timezone.utc).timestamp()
        pre_market_end_time = datetime.now().replace(
            hour=14, minute=30, second=00, tzinfo=timezone.utc).timestamp()

        if pre_market_end_time >= right_now >= pre_market_start_time:
            open = True
        else:
            open = False

        self.assertEqual(open, self.robot.pre_market_open)

    def test_post_market_open(self):
        """Tests whether US Post-Market is Open"""

        right_now = datetime.now().replace(tzinfo=timezone.utc).timestamp()
        post_market_start_time = datetime.now().replace(
            hour=21, minute=00, second=00, tzinfo=timezone.utc).timestamp()
        post_market_end_time = datetime.now().replace(
            hour=1, minute=00, second=00, tzinfo=timezone.utc).timestamp()

        if post_market_end_time >= right_now >= post_market_start_time:
            open = True
        else:
            open = False

        self.assertEqual(open, self.robot.post_market_open)

    def test_historical_prices(self):
        """Tests Grabbing historical prices."""

        # Grab historical prices, first define the start date and end date.
        start_date = datetime.today()
        end_date = start_date - timedelta(days=30)

        # Grab the historical prices.
        self.robot.grab_historical_prices(start=end_date,
                                          end=start_date,
                                          bar_size=1,
                                          bar_type='minute',
                                          symbols=['AAPL'])

        self.assertIn('aggregated', self.robot.historical_prices)

    def tearDown(self) -> None:
        """Teardown the Robot."""

        self.robot = None
class PyRobotIndicatorTest(TestCase):

    """Will perform a unit test for the Indicator Object."""

    def setUp(self) -> None:
        """Set up the Indicator Client."""

        # Grab configuration values.
        config = ConfigParser()
        config.read('configs/config.ini')       

        CLIENT_ID = config.get('main', 'CLIENT_ID')
        REDIRECT_URI = config.get('main', 'REDIRECT_URI')
        CREDENTIALS_PATH = config.get('main', 'JSON_PATH')

        # Create a robot.
        self.robot = PyRobot(
            client_id = CLIENT_ID, 
            redirect_uri = REDIRECT_URI, 
            credentials_path = CREDENTIALS_PATH
        )

        # Grab historical prices, first define the start date and end date.
        start_date = datetime.today()
        end_date = start_date - timedelta(days=30)

        # Grab the historical prices.
        historical_prices = self.robot.grab_historical_prices(
            start=end_date,
            end=start_date,
            bar_size=1,
            bar_type='minute',
            symbols=['AAPL','MSFT']
        )

        # Convert data to a Data Frame.
        self.stock_frame = self.robot.create_stock_frame(data=historical_prices['aggregated'])

        # Create the indicator client.
        self.indicator_client = Indicators(price_data_frame=self.stock_frame)

    def test_creates_instance_of_session(self):
        """Create an instance and make sure it's a StockFrame."""

        self.assertIsInstance(self.stock_frame, StockFrame)
        self.assertIsInstance(self.indicator_client, Indicators)
    
    def test_price_frame_data_property(self):
        """Test getting the Price Data Frame."""

        self.assertIsNotNone(self.indicator_client.price_data_frame)

    def test_is_multi_index_property(self):
        """Test getting the Price Data Frame."""

        self.assertTrue(self.indicator_client.is_multi_index)

    def test_change_in_price(self):
        """Test adding the Change in Price."""
        
        # Create the Change in Price indicator.
        self.indicator_client.change_in_price()

        # Check if we have the column.
        self.assertIn('change_in_price', self.stock_frame.frame.columns)

        # And that it's not empty.
        self.assertFalse(self.stock_frame.frame['change_in_price'].empty)

    def test_rsi(self):
        """Test adding the Relative Strength Index."""
        
        # Create the RSI indicator.
        self.indicator_client.rsi(period=14)

        # Check if we have the column.
        self.assertIn('rsi', self.stock_frame.frame.columns)

        # And that it's not empty.
        self.assertFalse(self.stock_frame.frame['rsi'].empty)

    def test_sma(self):
        """Test adding the Simple Moving Average."""
        
        # Create the SMA indicator.
        self.indicator_client.sma(period=200)

        # Check if we have the column.
        self.assertIn('sma', self.stock_frame.frame.columns)

        # And that it's not empty.
        self.assertFalse(self.stock_frame.frame['sma'].empty)

    def test_ema(self):
        """Test adding the Exponential Moving Average."""
        
        # Create the EMA indicator.
        self.indicator_client.ema(period=50)

        # Check if we have the column.
        self.assertIn('ema', self.stock_frame.frame.columns)

        # And that it's not empty.
        self.assertFalse(self.stock_frame.frame['ema'].empty)

    def test_indicator_exist(self):
        """Test checkinf if an indicator column exist."""
        
        # Create the EMA indicator.
        self.indicator_client.ema(period=50)

        # Check if we have the column.
        self.assertIn('ema', self.stock_frame.frame.columns)

        # And that it's not empty.
        self.assertTrue(self.stock_frame.do_indicator_exist(column_names=['ema']))

    def test_indicator_signal(self):
        """Test checkinf if an indicator column exist."""
        
        # Create the EMA indicator.
        self.indicator_client.ema(period=50)

        self.indicator_client.set_indicator_signal(
            indicator='sma',
            buy=50.0,
            sell=30.0,
            condition_buy=operator.ge,
            condition_sell=operator.le
        )

        func_1 = operator.ge
        func_2 = operator.le

        correct_dict = {
            'buy': 50.0,
            'sell': 30.0,
            'buy_operator': func_1,
            'sell_operator': func_2
        }

        correct_dict_all = {
            'sma':{
                'buy': 50.0,
                'sell': 30.0,
                'buy_operator': func_1,
                'sell_operator': func_2
            }
        }


        # And that it's not empty.
        self.assertDictEqual(
            self.indicator_client.get_indicator_signal(indicator='sma'),
            correct_dict
        )

        # And that it's not empty.
        self.assertDictEqual(
            self.indicator_client.get_indicator_signal(),
            correct_dict_all
        )

    def tearDown(self) -> None:
        """Teardown the Indicator object."""

        self.stock_frame = None
        self.indicator_client = None
Beispiel #11
0
from pyrobot.robot import PyRobot
from pyrobot.indicators import Indicators

# Grab configuration values.
config = ConfigParser()
config.read('configs/config.ini')

CLIENT_ID = config.get('main', 'CLIENT_ID')
REDIRECT_URI = config.get('main', 'REDIRECT_URI')
CREDENTIALS_PATH = config.get('main', 'JSON_PATH')
ACCOUNT_NUMBER = config.get('main', 'ACCOUNT_NUMBER')

# Initalize the robot.
trading_robot = PyRobot(
    client_id=CLIENT_ID,
    redirect_uri=REDIRECT_URI,
    credentials_path=CREDENTIALS_PATH,
    paper_trading=True
)

# Create a Portfolio
trading_robot_portfolio = trading_robot.create_portfolio()

# Add a single position
trading_robot_portfolio.add_position(
    symbol='MSFT',
    quantity=10,
    purchase_price=10,
    asset_type='equity',
    purchase_date='2020-04-01'
)
class PyRobotSession(TestCase):
    """Will perform a unit test for the Azure session."""
    def setUp(self) -> None:
        """Set up the Robot."""

        # Grab configuration values.
        config = ConfigParser()
        config.read('configs/config.ini')

        CLIENT_ID = config.get('main', 'CLIENT_ID')
        REDIRECT_URI = config.get('main', 'REDIRECT_URI')
        CREDENTIALS_PATH = config.get('main', 'JSON_PATH')
        self.ACCOUNT_NUMBER = config.get('main', 'ACCOUNT_NUMBER')

        self.robot = PyRobot(client_id=CLIENT_ID,
                             redirect_uri=REDIRECT_URI,
                             credentials_path=CREDENTIALS_PATH)

    def test_create_new_market_order(self):
        """Create a new market order."""

        # Create a new Trade Object.
        new_trade = self.robot.create_trade(enter_or_exit='enter',
                                            long_or_short='short',
                                            order_type='mkt')

        self.assertIsInstance(new_trade, Trade)
        self.assertEqual(new_trade.order_type, 'mkt')

    def test_create_new_limit_order(self):
        """Create a new limit order."""

        # Create a new Trade Object.
        new_trade = self.robot.create_trade(enter_or_exit='enter',
                                            long_or_short='short',
                                            order_type='lmt')

        self.assertIsInstance(new_trade, Trade)
        self.assertEqual(new_trade.order_type, 'lmt')

    def test_create_new_stop_order(self):
        """Create a new stop order."""

        # Create a new Trade Object.
        new_trade = self.robot.create_trade(enter_or_exit='enter',
                                            long_or_short='short',
                                            order_type='stop')

        self.assertIsInstance(new_trade, Trade)
        self.assertEqual(new_trade.order_type, 'stop')

    def test_add_instrument(self):
        """Tests adding an instrument to an order after creating it."""

        # Create a new Trade Object.
        new_trade = self.robot.create_trade(enter_or_exit='enter',
                                            long_or_short='long',
                                            order_type='lmt',
                                            price=12.00)

        # Define the Order Leg it should be.
        order_leg = {
            "instruction": 'BUY',
            "quantity": 2,
            "instrument": {
                "symbol": 'MSFT',
                "assetType": 'EQUITY'
            }
        }

        # Add an instrument to the Trade.
        new_trade.instrument(symbol='MSFT', quantity=2, asset_type='EQUITY')
        self.assertDictEqual(new_trade.order['orderLegCollection'][0],
                             order_leg)

    def test_add_stop_loss_percentage(self):
        """Tests adding a stop Loss Order to an exisiting Limit Order."""

        # Create a new Trade Object.
        new_trade = self.robot.create_trade(enter_or_exit='enter',
                                            long_or_short='long',
                                            order_type='lmt',
                                            price=12.00)
        new_trade.instrument(symbol='MSFT', quantity=2, asset_type='EQUITY')
        new_trade.add_stop_loss(stop_size=.10, percentage=True)

        stop_loss_order = {
            "orderType":
            "STOP",
            "session":
            "NORMAL",
            "duration":
            "DAY",
            "stopPrice":
            10.8,
            "orderStrategyType":
            "SINGLE",
            "orderLegCollection": [{
                "instruction": 'SELL',
                "quantity": 2,
                "instrument": {
                    "symbol": 'MSFT',
                    "assetType": 'EQUITY'
                }
            }]
        }

        self.assertEqual(new_trade.order_type, 'lmt')
        self.assertIn('childOrderStrategies', new_trade.order)
        self.assertDictEqual(new_trade.stop_loss_order, stop_loss_order)

    def test_add_stop_loss_dollar(self):
        """Tests adding a stop Loss Order to an exisiting Limit Order."""

        # Create a new Trade Object.
        new_trade = self.robot.create_trade(enter_or_exit='enter',
                                            long_or_short='long',
                                            order_type='lmt',
                                            price=12.00)
        new_trade.instrument(symbol='MSFT', quantity=2, asset_type='EQUITY')
        new_trade.add_stop_loss(stop_size=.10, percentage=False)

        stop_loss_order = {
            "orderType":
            "STOP",
            "session":
            "NORMAL",
            "duration":
            "DAY",
            "stopPrice":
            11.90,
            "orderStrategyType":
            "SINGLE",
            "orderLegCollection": [{
                "instruction": 'SELL',
                "quantity": 2,
                "instrument": {
                    "symbol": 'MSFT',
                    "assetType": 'EQUITY'
                }
            }]
        }

        self.assertEqual(new_trade.order_type, 'lmt')
        self.assertIn('childOrderStrategies', new_trade.order)
        self.assertDictEqual(new_trade.stop_loss_order, stop_loss_order)

    # def test_price_calculation(self):
    #     """Tests calculating the new price for Stop Orders."""

    #     new_price = Trade()._calculate_new_price(price=12.00,adjustment=.1, percentage=True)

    def tearDown(self) -> None:
        """Teardown the Robot."""

        self.robot = None
from pyrobot.indicators import Indicators

# Grab configuration values.
config = ConfigParser()
config.read('configs/config.ini')

CLIENT_ID = config.get('main', 'CLIENT_ID')
REDIRECT_URI = config.get('main', 'REDIRECT_URI')
CREDENTIALS_PATH = config.get('main', 'JSON_PATH')
ACCOUNT_NUMBER = config.get('main', 'ACCOUNT_NUMBER')
FIRST_ACCOUNT_NUMBER = config.get('main', 'FIRST_ACCOUNT_NUMBER')

# Initalize the robot.
trading_robot = PyRobot(client_id=CLIENT_ID,
                        redirect_uri=REDIRECT_URI,
                        credentials_path=CREDENTIALS_PATH,
                        trading_account=ACCOUNT_NUMBER,
                        first_trading_account=FIRST_ACCOUNT_NUMBER,
                        paper_trading=False)
trading_robot_positions = trading_robot.get_positions(FIRST_ACCOUNT_NUMBER)
# Create a Portfolio
trading_robot_portfolio = trading_robot.create_portfolio()
trading_robot_portfolio.add_positions(trading_robot_positions)
"""
# Define mutliple positions to add.
multi_position = [
    {
        'asset_type': 'equity',
        'quantity': 2,
        'purchase_price': 4.00,
        'symbol': 'TSLA',
        'purchase_date': '2020-01-31'
Beispiel #14
0
 def when_a_robot_is_created(self):
     self.robot = PyRobot(client_id=self.client_id,
                          redirect_uri=self.redirect_uri,
                          credentials_path=self.credentials_path)
Beispiel #15
0
class PyRobotTest(TestCase):
    """Will perform a unit test for the PyRobot Object."""
    def setUp(self) -> None:
        """Set up the Robot."""

        # Grab configuration values.
        config = ConfigParser()
        config.read('configs/config.ini')

        CLIENT_ID = config.get('main', 'CLIENT_ID')
        REDIRECT_URI = config.get('main', 'REDIRECT_URI')
        CREDENTIALS_PATH = config.get('main', 'JSON_PATH')
        self.ACCOUNT_NUMBER = config.get('main', 'ACCOUNT_NUMBER')

        self.robot = PyRobot(client_id=CLIENT_ID,
                             redirect_uri=REDIRECT_URI,
                             credentials_path=CREDENTIALS_PATH)

    def test_creates_instance_of_session(self):
        """Create an instance and make sure it's a robot."""

        self.assertIsInstance(self.robot, PyRobot)

    def test_create_portofolio(self):
        """Call `create_portfolio` and make sure it's a Portfolio."""

        new_portfolio = self.robot.create_portfolio()

        self.assertIsInstance(new_portfolio, Portfolio)

    def test_regular_market_open(self):
        """Tests whether Market is Open"""

        # Define right now.
        right_now = datetime.utcnow().timestamp()

        # Define the start time.
        regular_market_start_time = datetime.utcnow().replace(
            hour=14, minute=30, second=00).timestamp()

        # Define the end time.
        regular_market_end_time = datetime.utcnow().replace(
            hour=21, minute=00, second=00).timestamp()

        if regular_market_end_time >= right_now >= regular_market_start_time:
            open = True
        else:
            open = False

        self.assertEqual(open, self.robot.regular_market_open)

    def test_pre_market_open(self):
        """Tests whether US Pre-Market is Open"""

        # Define right now.
        right_now = datetime.utcnow().timestamp()

        # Define the start time.
        pre_market_start_time = datetime.utcnow().replace(
            hour=9, minute=00, second=00).timestamp()

        # Define the end time.
        pre_market_end_time = datetime.utcnow().replace(hour=14,
                                                        minute=30,
                                                        second=00).timestamp()

        if pre_market_end_time >= right_now >= pre_market_start_time:
            open = True
        else:
            open = False

        self.assertEqual(open, self.robot.pre_market_open)

    def test_post_market_open(self):
        """Tests whether US Post-Market is Open"""

        # Define right now.
        right_now = datetime.utcnow().timestamp()

        # Define the start time.
        post_market_start_time = datetime.utcnow().replace(
            hour=21, minute=00, second=00).timestamp()

        # Define the end time.
        post_market_end_time = datetime.utcnow().replace(
            hour=1, minute=30, second=00).timestamp()

        if post_market_end_time >= right_now >= post_market_start_time:
            open = True
        else:
            open = False

        self.assertEqual(open, self.robot.post_market_open)

    def test_historical_prices(self):
        """Tests Grabbing historical prices."""

        # Grab historical prices, first define the start date and end date.
        start_date = datetime.today()
        end_date = start_date - timedelta(days=30)

        # Grab the historical prices.
        self.robot.grab_historical_prices(start=end_date,
                                          end=start_date,
                                          bar_size=1,
                                          bar_type='minute',
                                          symbols=['AAPL'])

        self.assertIn('aggregated', self.robot.historical_prices)

    def test_build_portfolio(self):
        """Test building a Portfolio object."""

        # Create a Portfolio
        porfolio_obj = self.robot.create_portfolio()

        self.assertIsInstance(porfolio_obj, Portfolio)

    def test_build_trade(self):
        """Test building a Trade object."""

        # Create a Trade
        trade_obj = self.robot.create_trade(trade_id='long_msft',
                                            enter_or_exit='enter',
                                            long_or_short='short',
                                            order_type='lmt',
                                            price=150.00)

        self.assertIsInstance(trade_obj, Trade)

    def test_grab_accounts(self):
        """Test grabbing accounts using the robot."""

        accounts = self.robot.get_accounts(all_accounts=True)

        pprint.pprint(accounts)

        self.assertIsInstance(accounts, list)

    def test_grab_positions(self):
        """Test grabbing positions using the robot."""

        positions = self.robot.get_positions(all_accounts=True)

        pprint.pprint(positions)

        self.assertIsInstance(positions, list)

    def tearDown(self) -> None:
        """Teardown the Robot."""

        self.robot = None
Beispiel #16
0
# Grab the config file values
os.system("python3 configs/config.py")
config = ConfigParser()
config.read('configs/config.ini')

CLIENT_ID = config.get('main', 'CLIENT_ID')
API_KEY = config.get('main', 'API_KEY')
API_SECRET = config.get('main', 'API_SECRET').encode('UTF-8')
NONCE = config.get('main', 'NONCE')

# init the robot
trading_robot = PyRobot(
    account_number = '1',
    client_id = CLIENT_ID,
    api_key = API_KEY,
    api_secret = API_SECRET,
    nonce = NONCE,
    paper_trading = True
)

# Create a new portfolio
trading_robot_portfolio = trading_robot.create_portfolio()

# add multi positions to portfolio
'''
multi_position = [
    {
        'asset_type': 'bitcoin',
        'quantity': 2,
        'purchase_price': 4.00,
        'symbol': 'btcusd',
Beispiel #17
0
class PyRobotSession(TestCase):
    """Will perform a unit test for the Azure session."""
    def setUp(self) -> None:
        """Set up the Robot."""

        # Grab configuration values.
        config = ConfigParser()
        config.read('configs/config.ini')

        CLIENT_ID = config.get('main', 'CLIENT_ID')
        REDIRECT_URI = config.get('main', 'REDIRECT_URI')
        CREDENTIALS_PATH = config.get('main', 'JSON_PATH')
        self.ACCOUNT_NUMBER = config.get('main', 'ACCOUNT_NUMBER')

        self.robot = PyRobot(client_id=CLIENT_ID,
                             redirect_uri=REDIRECT_URI,
                             credentials_path=CREDENTIALS_PATH)

    def test_creates_instance_of_session(self):
        """Create an instance and make sure it's a robot."""

        self.assertIsInstance(self.robot, PyRobot)

    def test_create_portofolio(self):
        """Call `create_portfolio` and make sure it's a Portfolio."""

        new_portfolio = self.robot.create_portfolio()
        self.assertIsInstance(new_portfolio, Portfolio)

    def test_regular_market_open(self):
        """Tests whether Market is Open"""

        right_now = datetime.now().replace(tzinfo=timezone.utc).timestamp()
        regular_market_start_time = datetime.now().replace(
            hour=14, minute=30, second=00, tzinfo=timezone.utc).timestamp()
        regular_market_end_time = datetime.now().replace(
            hour=21, minute=00, second=00, tzinfo=timezone.utc).timestamp()

        if regular_market_end_time >= right_now >= regular_market_start_time:
            open = True
        else:
            open = False

        self.assertEqual(open, self.robot.regular_market_open)
        """
        Pre
        09:00
        14:30

        Regular
        14:30
        21:00

        Post
        21:00
        01:00
        """

    def test_pre_market_open(self):
        """Tests whether US Pre-Market is Open"""

        right_now = datetime.now().replace(tzinfo=timezone.utc).timestamp()
        pre_market_start_time = datetime.now().replace(
            hour=9, minute=00, second=00, tzinfo=timezone.utc).timestamp()
        pre_market_end_time = datetime.now().replace(
            hour=14, minute=30, second=00, tzinfo=timezone.utc).timestamp()

        if pre_market_end_time >= right_now >= pre_market_start_time:
            open = True
        else:
            open = False

        self.assertEqual(open, self.robot.pre_market_open)

    def test_post_market_open(self):
        """Tests whether US Post-Market is Open"""

        right_now = datetime.now().replace(tzinfo=timezone.utc).timestamp()
        post_market_start_time = datetime.now().replace(
            hour=21, minute=00, second=00, tzinfo=timezone.utc).timestamp()
        post_market_end_time = datetime.now().replace(
            hour=1, minute=00, second=00, tzinfo=timezone.utc).timestamp()

        if post_market_end_time >= right_now >= post_market_start_time:
            open = True
        else:
            open = False

        self.assertEqual(open, self.robot.post_market_open)

    def tearDown(self) -> None:
        """Teardown the Robot."""

        self.robot = None
Beispiel #18
0
import time as true_time
import pprint
import pathlib
import operator
import pandas as pd

from datetime import datetime
from datetime import timedelta
from configparser import ConfigParser
from pyrobot.robot import PyRobot
from pyrobot.indicators import Indicators

#Grab config file values

config = ConfigParser()
config.read("config/config.ini")

CLIENT_ID = config.get("main", "CLIENT_ID")
REDIRECT_URI = config.get("main", "REDIRECT_URI")
CREDENTIALS_PATH = config.get("main", "JSON_PATH")
ACCOUNT_NUMBER = config.get("main", "ACCOUNT_NUMBER")

#initialize robot

trading_robot = PyRobot(client_id=CLIENT_ID,
                        redirect_uri=REDIRECT_URI,
                        credentials_path=CREDENTIALS_PATH,
                        trading_account=ACCOUNT_NUMBER,
                        paper_trading=True)
Beispiel #19
0
from pyrobot.robot import PyRobot
from pyrobot.indicators import Indicators

# Grab configuration values.
config = ConfigParser()
config.read('configs/config.ini')

CLIENT_ID = config.get('main', 'CLIENT_ID')
REDIRECT_URI = config.get('main', 'REDIRECT_URI')
CREDENTIALS_PATH = config.get('main', 'JSON_PATH')
ACCOUNT_NUMBER = config.get('main', 'ACCOUNT_NUMBER')

# Initalize the robot.
trading_robot = PyRobot(client_id=CLIENT_ID,
                        redirect_uri=REDIRECT_URI,
                        credentials_path=CREDENTIALS_PATH,
                        paper_trading=True)

# Create a Portfolio
trading_robot_portfolio = trading_robot.create_portfolio()

# Define mutliple positions to add.
multi_position = [{
    'asset_type': 'equity',
    'quantity': 2,
    'purchase_price': 4.00,
    'symbol': 'TSLA',
    'purchase_date': '2020-01-31'
}, {
    'asset_type': 'equity',
    'quantity': 2,
from configparser import ConfigParser
from pyrobot.robot import PyRobot

# Grab configuration values.
config = ConfigParser()
config.read('configs/config.ini')

CLIENT_ID = config.get('main', 'CLIENT_ID')
REDIRECT_URI = config.get('main', 'REDIRECT_URI')
CREDENTIALS_PATH = config.get('main', 'JSON_PATH')
ACCOUNT_NUMBER = config.get('main', 'ACCOUNT_NUMBER')

# Initalize the robot
trading_robot = PyRobot(
    client_id=CLIENT_ID,
    redirect_uri=REDIRECT_URI,
    credentials_path=CREDENTIALS_PATH
)

# Create a Portfolio
trading_robot_portfolio = trading_robot.create_portfolio()

# Define mutliple positions to add.
multi_position = [
    {
        'asset_type': 'equity',
        'quantity': 2,
        'purchase_price': 4.00,
        'symbol': 'TSLA',
        'purchase_date': '2020-01-31'
    },