Exemple #1
0
    def __init__(self, profit_per, loss_per, position_size):
        self.api = Alpaca(
            ALPACA_UID,
            ALPACA_SECRET,
            '5Min',
        )
        self.period = 5  # Always in minutes for now (1, 5 or 15)
        self.minutes = self.get_minutes()
        self.symbols = []
        self.profit_per = profit_per
        self.loss_per = loss_per
        self.position_size = position_size
        self.hr = '--------------------------------------------------------------------------------'

        self.psa()
        self.run()
Exemple #2
0
def execute_scan(stocks, lock, sleep_time=60):
    """
    - Scan price action to find the optimal moment for placing BUY order
    - Place order
    - Create dictionary with information on the position
    """

    while market_open():

        lock.acquire()
        debug_logger.debug("Lock acquired by execute_scan()")

        for stock in stocks['buy']:

            if not stock.open:

                stock.get_execution_potential()

                debug_logger.debug(
                    "get_execution_potential() called for '{}'".format(
                        stock.symbol))

                if stock.potential == 2:

                    a = Alpaca()
                    # TO-DO! Add functionality to calculate optimal position?
                    # Temporarily, an arbitrary amount of 10 shares is established
                    if a.place_order(stock.symbol, 'buy', 10):

                        stock.open_position()
                        stocks['bought'].add(stock)
                        stock_logger.info(
                            "Placed order of 10 stocks of '{}'".format(
                                stock.symbol))

                    else:
                        continue

                sleep(2)

        lock.release()
        debug_logger.debug("Lock released by execute_scan()")

        stock_logger.info("Stocks of {} symbol were bought".format(
            len(stocks['bought'])))

        sleep(sleep_time)
Exemple #3
0
def initialize_data():
    """    
    Create a dict of:
        
        - initial set of Stock objects from:
            - Manually created Alpaca watchlist            
            - Automatic selection of stocks from Yahoo Finance watchlists        
        
        - 3 empty sets to be populated by stocks that:
            - show strong potential after trend scan
            - show weak potential after tactical scan
            - show strong potential after tactical scan, are ready to buy
        
        - a set of dictionaries containing information on open positions
        
        - a list of completed trades to be saved and later analized
    """

    trades = {}
    trades[datetime.now().strftime('%Y-%m-%d')] = set()

    a = Alpaca()
    watchlist = a.get_watchlist_symbols()
    watchlist.update(yahoo_watchlist())

    stock_logger.info("Initialized watchlist with '{}' symbols".format(
        len(watchlist)))

    stocks = {
        'initial': {Stock(symbol)
                    for symbol in watchlist},
        'potential': set(),
        'standby': set(),
        'buy': set(),
        'bought': record.get_open_positions(),
        'trades': trades
    }

    debug_logger.debug("Created stocks dictionary")

    return stocks
Exemple #4
0
def sell_scan(stocks, lock, sleep_time=300):
    """
    Scans open position's unrealized profit for optimal sell signal
    """

    while market_open():

        lock.acquire()
        debug_logger.debug("Lock acquired by sell_scan()")

        for stock in stocks['bought']:

            stock.get_sell_signal()
            debug_logger.debug("get_sell_signal() called for '{}'".format(
                stock.symbol))

            if stock.sell:

                a = Alpaca()
                a.close_position(stock.symbol)
                stock.close_position()

                stock_logger.info(
                    "Closed position of 10 stocks of '{}'".format(
                        stock.symbol))
                stocks['trades'].add(stock.position_record)

            else:
                continue

            sleep(2)

        lock.release()
        debug_logger.debug("Lock released by sell_scan()")

        stock_logger.info("{} stocks were sold".format(len(stocks['trades'])))

        sleep(sleep_time)

    record.store_new_trades(stocks['trades'])
Exemple #5
0
from math import floor

c_p = os.getcwd()
if c_p not in sys.path:
    sys.path.append(c_p)

from kafka import TopicPartition, KafkaConsumer, KafkaProducer

import numpy as np
import pandas as pd

from alpaca import Alpaca
from portfolio import Portfolio
from util import Weight

BROKER = Alpaca()
UPDATEFREQ = 60


class KafkaAgent:
    def __init__(self, kafka_consumer=None, symbols=[]):
        self._assets = symbols
        self._nodestate = {}
        self._kafka = kafka_consumer
        self._broker = BROKER
        self._portfolio = Portfolio(BROKER,
                                    positions={s: 'long'
                                               for s in symbols})
        self._portfolio.value = self._broker.account_value() - 1000

        self._weights = {}
Exemple #6
0
    if dataset == 'uc2':
        X, y = split_df(pd.read_pickle('..\\data\\df_uc2.pkl'),
                        index_column='run_id',
                        feature_columns=['position', 'force'],
                        target_name='label')
        y = np.array(y)
        # Length of timeseries for resampler and cnn
        sz = 200
        # Number of channels for cnn
        num_channels = len(X[0][0])
        # Number of classes for cnn
        num_classes = np.unique(y).shape[0]

    resampler = TimeSeriesResampler(sz=sz)
    alpaca = Pipeline([('resampler', resampler),
                       ('classifier', Alpaca())])
    alpaca.fit(X, y, classifier__stacked=False, classifier__n_clusters=200)

    # Measure time for single sample processing
    t = []
    for i in range(1, max_sample+1):
        for j in range(10):
            rand = np.random.randint(2000)
            sample = np.transpose(to_time_series_dataset(X[rand]), (2, 0, 1))
            start = time.process_time()
            for k in range(100):
                for l in range(i):
                    y_pred_bin, y_pred = alpaca.predict(sample, voting='veto')
            end = time.process_time()
            t.append([i, (end-start)/100, 'single'])
    def setUp(self):

        self.alpaca = Alpaca()
class TestAlpaca(unittest.TestCase):

    _watchlist_url = 'https://paper-api.alpaca.markets/v2/watchlists/5605708b-df0a-4473-8d76-a1303e608587'
    _positions_url = 'https://paper-api.alpaca.markets/v2/positions'
    _orders_url = 'https://paper-api.alpaca.markets/v2/orders'
    _assets_url = 'https://paper-api.alpaca.markets/v2/assets/FAKE'
    _quote_url = 'https://data.alpaca.markets/v1/last_quote/stocks/FAKE'

    def setUp(self):

        self.alpaca = Alpaca()

    @requests_mock.Mocker()
    def test_get_watchlist(self, mock_request):

        mock_request.get(
            self._watchlist_url,
            content=
            b'{"watchlist_id": "fake123", "assets": [{"symbol": "FAKE"}]}')

        actual_result = self.alpaca.get_watchlist()

        self.assertEqual(actual_result, ['FAKE'])

    @requests_mock.Mocker()
    def test_get_positions(self, mock_request):

        mock_request.get(
            self._positions_url,
            content=b'[{"asset_id": "fake123", "symbol": "FAKE"}]')

        actual_result = self.alpaca.get_positions()

        self.assertEqual(actual_result, ['FAKE'])

    @patch('alpaca.Alpaca.take_and_stop')
    @patch('alpaca.Alpaca.is_tradable')
    @requests_mock.Mocker()
    def test_place_order(self, mock_is_tradable, mock_take_and_stop,
                         mock_request):

        mock_request.post(self._orders_url, text='ok')
        mock_is_tradable.return_value = True
        mock_take_and_stop.return_value = ({
            'limit_price': '130.0'
        }, {
            'stop_price': '90.0',
            'limit_price': '88.0'
        })

        actual_result = self.alpaca.place_order('FAKE', 'buy', 15)

        self.assertEqual(actual_result, True)

    @requests_mock.Mocker()
    def test_is_tradable_true(self, mock_request):

        mock_request.get(self._assets_url,
                         content=b'{"status": "active", "tradable": true}')

        actual_result = self.alpaca.is_tradable('FAKE')

        self.assertEqual(actual_result, True)

    @requests_mock.Mocker()
    def test_is_tradable_false_inactive(self, mock_request):

        mock_request.get(self._assets_url,
                         content=b'{"status": "inactive", "tradable": true}')

        actual_result = self.alpaca.is_tradable('FAKE')

        self.assertEqual(actual_result, False)

    @requests_mock.Mocker()
    def test_is_tradable_false_not_tradable(self, mock_request):

        mock_request.get(self._assets_url,
                         content=b'{"status": "active", "tradable": false}')

        actual_result = self.alpaca.is_tradable('FAKE')

        self.assertEqual(actual_result, False)

    @requests_mock.Mocker()
    def test_take_and_stop(self, mock_request):

        mock_request.get(
            self._quote_url,
            content=
            b'{"symbol": "FAKE", "last": {"bidprice": 100, "askprice": 100}}')
        expected_result = ({
            'limit_price': '130.0'
        }, {
            'stop_price': '90.0',
            'limit_price': '88.0'
        })

        actual_result = self.alpaca.take_and_stop('FAKE')

        self.assertEqual(actual_result, expected_result)
Exemple #9
0
import collections
import datetime as dt
from scipy import stats
from alpaca import Alpaca
# AR example
from statsmodels.tsa.ar_model import AutoReg
# MA example
from statsmodels.tsa.arima_model import ARMA
# import warnings filter
from warnings import simplefilter
# ignore all future warnings
simplefilter(action='ignore', category=FutureWarning)
from alpaca import Alpaca

#Doing some funny math to use overall market sentiment as a value which I can skew predictions either + or - a precentage
connect = Alpaca()
Current_Market_Sentiment = connect.get_tweet_sent(['NASDAQ', 'SP500', 'DOW'],
                                                  0)
Current_Market_Sentiment_Value = sum(Current_Market_Sentiment.values()) / 10
if Current_Market_Sentiment_Value > 0:
    Current_Market_Sentiment_Value = 1 + Current_Market_Sentiment_Value
else:
    Current_Market_Sentiment_Value = 1 - abs(Current_Market_Sentiment_Value)

print("Sentiment Skew:", Current_Market_Sentiment_Value)


def prediction_model(histdata, days):
    slopedata = []
    output = []
Exemple #10
0
    DEFINE RESAMPLING LENGTH IF NEEDED
    sz = 
    """

    # Turn y to numpy array
    y = np.array(y)
    # Split into train and test sets
    X_train, X_test, y_train, y_test = train_test_split(X,
                                                        y,
                                                        test_size=0.2,
                                                        stratify=y,
                                                        random_state=42)

    # Pipeline example
    alpaca = Pipeline([('resampler', TimeSeriesResampler(sz=sz)),
                       ('alpaca', Alpaca())])
    alpaca.fit(X_train, y_train)
    """
    # Example with additional channel derived from channel 0
    alpaca = Pipeline([('resampler', TimeSeriesResampler(sz=sz)),
                       ('differentiator',Differentiator(channel=0)),
                       ('alpaca', Alpaca())])
    """

    y_pred_bin_veto, y_pred_veto = alpaca.predict(X_test, voting="veto")
    y_pred_bin_dem, y_pred_dem = alpaca.predict(X_test, voting="democratic")
    y_pred_bin_meta_dtc, y_pred_meta_dtc = alpaca.predict(X_test,
                                                          voting="meta_dtc")
    y_pred_bin_meta_svc, y_pred_meta_svc = alpaca.predict(X_test,
                                                          voting="meta_svc")
Exemple #11
0
class TrainingBot:
    def __init__(self, profit_per, loss_per, position_size):
        self.api = Alpaca(
            ALPACA_UID,
            ALPACA_SECRET,
            '5Min',
        )
        self.period = 5  # Always in minutes for now (1, 5 or 15)
        self.minutes = self.get_minutes()
        self.symbols = []
        self.profit_per = profit_per
        self.loss_per = loss_per
        self.position_size = position_size
        self.hr = '--------------------------------------------------------------------------------'

        self.psa()
        self.run()

    def get_minutes(self):
        nb_in_hour = int(60 / self.period)
        return [self.period * i for i in range(1, nb_in_hour)]

    def run(self):
        open = False
        notified = False
        pre_market_fetched = False

        while True:
            if datetime.now().minute in self.minutes:  # Every x minutes
                if self.api.are_markets_open(
                ):  # Not on the same line as to not spam the API
                    open = True
                    notified = False
                    pre_market_fetched = False

                    positions = self.api.positions()

                    for symbol in self.symbols:
                        data = self.api.compute(symbol)
                        self.check_buy(data, positions)

                    for position in positions:
                        data = self.api.compute(position.symbol)
                        self.check_sell(data, position)

                    self.psa()
                    time.sleep(60)

            if not open and not notified:
                print('Markets are closed.')
                notified = True

            # 5 minutes before markets open
            if not open and not pre_market_fetched and (
                    datetime.now().minute == 25 and datetime.now().hour == 9):
                print(self.hr)
                self.symbols = self.api.fetch_pre_market()
                print('Trading symbols for the day:')
                for symbol in self.symbols:
                    print(
                        f"{symbol['s']} | {symbol['p']} | {symbol['c']} | {symbol['v']}"
                    )
                pre_market_fetched = True

    def psa(self):
        account = self.api.get_account()
        print(self.hr)
        print(
            f"{datetime.now().strftime('%H:%M:%S')} | Portfolio value: {account['capital']}$ | Today P/L: {account['today_pl']}$ | Open positions: {account['nb_positions']}"
        )
        print(self.hr)

    def check_buy(self, data, positions):
        if not self.api.in_positions(data['symbol']):  # No duplicates
            if data['10_avg'] > data['50_avg'] and data[
                    'rsi'] <= 30:  # Buy conditions
                max_price = self.position_size * self.api.capital()
                qty = int(round((max_price / data['close']), 0))
                if qty > 0:
                    self.api.buy(
                        data['symbol'],
                        qty,
                        take_profit=dict(limit_price=data['close'] +
                                         (data['close'] * self.profit_per), ),
                        stop_loss=dict(
                            stop_price=data['close'] -
                            (data['close'] * self.loss_per),
                            limit_price=data['close'] -
                            (data['close'] * self.loss_per),
                        ))
                    return True
        print(
            f"{data['timestamp'].time()} |  --  | {data['symbol']: <4} | {data['close']}$ | {round(data['rsi'], 2)} rsi | {round(data['10_avg'], 2)}$ 10MA | {round(data['50_avg'], 2)}$ 50MA"
        )

    def check_sell(self, data, position):
        if data['rsi'] is not None and data['rsi'] > 70:
            self.sell(data['symbol'], data['close'], position.qty)
            return True
from alpaca import Alpaca
from price_forcast import prediction_model





#Logic Starts here
days = 30
connect = Alpaca()
#tickers = ['APA']
all = connect.get_all_syms()
#histdata = connect.history(tickers,'day',str(days))
#print(prediction_model(histdata,days))

#Get nasdaq Lists

#print(connect.history('TLEH','day',14))

#Volatility Data



#Current_Market_Sentiment = connect.get_tweet_sent(['NASDAQ','SP500','DOW'],0)

#print(Stock_Picker)
#for v in Stock_Picker:
#   print(str(v).replace("]", "").replace("[", "").replace("'", ""))

Stock_Picker = connect.Stock_Picker(all,'day',7)
#print(Stock_Picker)