예제 #1
0
    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)
예제 #2
0
def golden_cross(trading_robot: PyRobot, indicator_client: Indicators):
    """Set the indicators to reflect the golden cross strategy"""

    indicator_client.ema(period=20, column_name='ema_20')
    indicator_client.ema(period=200, column_name='ema_200')

    # Add a Signal Check
    indicator_client.set_indicator_signal_compare(indicator_1='ema_20',
                                                  indicator_2='ema_200',
                                                  condition_buy=operator.ge,
                                                  condition_sell=operator.le)
예제 #3
0
    def get_and_process_data(self, tickers: [str]):
        # Pull data
        # self.get_data('TDA', tickers=tickers)
        # Clean data
        # Todo implement data cleaning
        # Store data
        end_date = datetime.today()

        start_date = end_date - timedelta(days=20)

        # Get historical data
        historical_prices = self.grab_historical_prices(start=start_date,
                                                        end=end_date,
                                                        bar_size=1,
                                                        bar_type='minute')
        # todo clean data
        # Create stock frame
        self.portfolio.stock_frame = self.create_stock_frame(
            data=historical_prices['aggregated'])
        # Fill in missing values
        # todo fill in missing values

        # Calculate MACD, RSI, and VWAP
        self._indicator_client = Indicators(
            price_data_frame=self.portfolio.stock_frame)
        conf_val.calculate_columns(
            self._indicator_client,
            owned=False,
            trading_symbol=self._tickers[0],
            bot_account=self.get_accounts(account_number=ACCOUNT_NUMBER))

        # todo insert signals data into a column on stock frame

        # Insert into db
        self.insert_into_db(table=tickers[0],
                            stock_frame=self.portfolio.stock_frame)
예제 #4
0
# Convert data to a Data Frame.
stock_frame = trading_robot.create_stock_frame(
    data=historical_prices['aggregated'])

# We can also add the stock frame to the Portfolio object.
trading_robot.portfolio.stock_frame = stock_frame

# Additionally the historical prices can be set as well.
trading_robot.portfolio.historical_prices = historical_prices

# Portfolio Variance
pprint.pprint(trading_robot.portfolio.portfolio_metrics())

# Create an indicator Object.
indicator_client = Indicators(price_data_frame=stock_frame)

# Add the RSI Indicator.
indicator_client.rsi(period=14)

# Add the 200 day simple moving average.
indicator_client.sma(period=200)

# Add the 50 day exponentials moving average.
indicator_client.ema(period=50)

# Add a signal to check for.
indicator_client.set_indicator_signal(indicator='rsi',
                                      buy=40.0,
                                      sell=20.0,
                                      condition_buy=operator.ge,
예제 #5
0
    end=start_date,
    bar_size=1,
    bar_type='minute'
)

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

# We can also add the stock frame to the Portfolio object.
trading_robot.portfolio.stock_frame = stock_frame

# Additionally the historical prices can be set as well.
trading_robot.portfolio.historical_prices = historical_prices

# Create an indicator Object.
indicator_client = Indicators(price_data_frame=stock_frame)

# Add the RSI Indicator.
indicator_client.rsi(period=14)

# Add the 200 day simple moving average.
indicator_client.sma(period=200)

# Add the 50 day exponentials moving average.
indicator_client.ema(period=50)

# Add the Bollinger Bands.
indicator_client.bollinger_bands(period=20)

# Add the Rate of Change.
indicator_client.rate_of_change(period=1)
예제 #6
0
	trading_robot_portfolio = trading_robot.create_portfolio()

	trading_symbol = 'CCIV'

	trading_robot_portfolio.add_position(
		symbol=trading_symbol,
		quantity=1,
		asset_type='equity',
	)

	# Set historical prices for current positions
	set_historical_prices(trading_robot)
	# todo create a new dataframe that is cleaned/normalized for the models

	# Create new indicator client
	indicator_client = Indicators(price_data_frame=trading_robot.portfolio.stock_frame)
	# Set the confirmation validation strategy
	conf_val.define_strat(trading_robot, indicator_client)
	pd.set_option('display.max_columns', None)

	# Create a new Trade Object for Entering position
	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,
예제 #7
0
def define_strat(trading_robot: PyRobot, indicator_client: Indicators):
	"""Set the indicators to reflect the confirmation/validation strategy"""

	indicator_client.ema(period=20, column_name='ema_20')
	indicator_client.ema(period=200, column_name='ema_200')
	indicator_client.rsi(period=14)
예제 #8
0
def calculate_columns(indicator_client: Indicators, owned: bool, trading_symbol: str,
                      bot_account: dict):
	"""Sets buy/sell/hold signals for the conf_val strategy"""

	indicator_client.ema(period=20, column_name='ema_20').dropna(inplace=True)
	indicator_client.ema(period=200, column_name='ema_200').dropna(inplace=True)
	indicator_client.rsi(period=14).dropna(inplace=True)
	indicator_client.macd().dropna(inplace=True)  # Defaults to fast: 12, slow: 26, column_name: macd

	# Calculate the current % gap between the open and current ema_20
	#  This will be used to prevent a buy signal from happening if the open just barely
	#  goes over the ema_20.
	v1 = indicator_client.price_data_frame['open']
	v2 = indicator_client.price_data_frame['ema_20']
	v3 = indicator_client.price_data_frame['ema_200']
	indicator_client.price_data_frame['open_ema_20_percent_diff'] = \
		((v1 - v2) / abs(v2)) * 100
	indicator_client.price_data_frame['ema_20_ema_200_percent_diff'] = \
		((v2 - v3) / abs(v3)) * 100
	indicator_client.price_data_frame['signals'] = indicator_client.price_data_frame.apply(lambda row: calc_sig(row, owned), axis=1)
	print("break")
                                                         end=start_date,
                                                         bar_size=1,
                                                         bar_type='minute')

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

# We can also add the stock frame to the Portfolio object.
trading_robot.portfolio.stock_frame = stock_frame

# Additionally the historical prices can be set as well.
trading_robot.portfolio.historical_prices = historical_prices

# Create an indicator Object.
indicator_client = Indicators(price_data_frame=stock_frame)

# Add the RSI Indicator.
indicator_client.rsi(period=14)

# Add the 200 day simple moving average.
indicator_client.sma(period=200)

# Add the 50 day exponentials moving average.
indicator_client.ema(period=50)

# Add the Bollinger Bands.
indicator_client.bollinger_bands(period=20)

# Add the Rate of Change.
indicator_client.rate_of_change(period=1)
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