def __init__(self, prv_rest_url: str, pub_rest_url: str, pub_stream_endpoint: str, prv_stream_endpoint: str, key_id: str, secret_key: str): self.prv_rest = REST(key_id=key_id, secret_key=secret_key, base_url=prv_rest_url) self.pub_rest = REST(key_id=key_id, secret_key=secret_key, base_url=pub_rest_url) self.pub_stream = PublicStream(key_id=key_id, secret_key=secret_key, endpoint=pub_stream_endpoint) self.prv_stream = PrivateStream(key_id=key_id, secret_key=secret_key, endpoint=prv_stream_endpoint)
class AlpacaTrader(Trader): def __init__(self): self.alpaca_rest_client = REST(key_id=config.alpaca_api_key, secret_key=config.alpaca_api_secret) if not self.alpaca_rest_client: raise AssertionError( "Failed to authenticate Alpaca RESTful client") super().__init__() async def get_tradeable_symbols(self) -> List[str]: if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated polygon client") data = self.alpaca_rest_client.list_assets() return [asset.symbol for asset in data if asset.tradable] async def get_shortable_symbols(self) -> List[str]: if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated polygon client") data = self.alpaca_rest_client.list_assets() return [ asset.symbol for asset in data if asset.tradable and asset.easy_to_borrow and asset.shortable ]
def __init__(self): self.alpaca_rest_client = REST( key_id=config.alpaca_api_key, secret_key=config.alpaca_api_secret ) if not self.alpaca_rest_client: raise AssertionError( "Failed to authenticate Alpaca RESTful client" )
def __init__(self, qm: QueueMapper = None): self.market_open: Optional[datetime] self.market_close: Optional[datetime] self.alpaca_rest_client = REST( base_url=URL(config.alpaca_base_url), key_id=config.alpaca_api_key, secret_key=config.alpaca_api_secret, ) if not self.alpaca_rest_client: raise AssertionError( "Failed to authenticate Alpaca RESTful client" ) if qm: self.alpaca_ws_client = Stream( base_url=URL(config.alpaca_base_url), key_id=config.alpaca_api_key, secret_key=config.alpaca_api_secret, ) if not self.alpaca_ws_client: raise AssertionError( "Failed to authenticate Alpaca web_socket client" ) self.alpaca_ws_client.subscribe_trade_updates( AlpacaTrader.trade_update_handler ) self.running_task: Optional[asyncio.Task] = None now = datetime.now(nyc) calendar = self.alpaca_rest_client.get_calendar( start=now.strftime("%Y-%m-%d"), end=now.strftime("%Y-%m-%d") )[0] if now.date() >= calendar.date.date(): self.market_open = now.replace( hour=calendar.open.hour, minute=calendar.open.minute, second=0, microsecond=0, ) self.market_close = now.replace( hour=calendar.close.hour, minute=calendar.close.minute, second=0, microsecond=0, ) else: self.market_open = self.market_close = None super().__init__(qm)
class AlpacaData(DataAPI): def __init__(self): self.alpaca_rest_client = REST(key_id=config.alpaca_api_key, secret_key=config.alpaca_api_secret) if not self.alpaca_rest_client: raise AssertionError( "Failed to authenticate Alpaca RESTful client") def get_symbols(self) -> List[Dict]: if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated Alpaca client") return self.alpaca_rest_client.list_assets() def get_symbol_data( self, symbol: str, start: date, end: date = date.today(), scale: TimeScale = TimeScale.minute, ) -> pd.DataFrame: _start = nytz.localize(datetime.combine( start, datetime.min.time())).isoformat() _end = (nytz.localize(datetime.now().replace( microsecond=0)).isoformat() if end >= date.today() else end) if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated Alpaca client") t: TimeFrame = (TimeFrame.Minute if scale == TimeScale.minute else TimeFrame.Day if scale == TimeScale.day else None) data = self.alpaca_rest_client.get_bars( symbol=symbol, timeframe=t, start=_start, end=_end, limit=10000, adjustment="raw", ).df data = data.tz_convert("America/New_York") data["vwap"] = None data["average"] = None data["count"] = None if data.empty: raise ValueError( f"[ERROR] {symbol} has no data for {_start} to {_end} w {scale.name}" ) return data
class TestAssetSelector(TestCase): config = parse_configs(path=os.path.join("../../", "config.ini")) args = parse_args() # if args.mode is None: # args.mode = 'long' if args.period is None: args.period = "1D" if args.algorithm is None: args.algorithm = "efficient_frontier" if args.testperiods is None: args.testperiods = 30 if args.max is None: args.max = 26 if args.min is None: args.min = 6 alpaca = REST(base_url=config["alpaca"]["APCA_API_BASE_URL"], key_id=config["alpaca"]["APCA_API_KEY_ID"], secret_key=config["alpaca"]["APCA_API_SECRET_KEY"], api_version=config["alpaca"]["VERSION"]) broker = Broker(alpaca) selector = AssetSelector(broker, cli_args=args) def test_get_assets(self): res = TestAssetSelector.selector.get_assets('equity', 'efficient_frontier') print('[] ') def test_candle_pattern_direction(self): pass
class AlpacaData(DataAPI): def __init__(self): self.alpaca_rest_client = REST( key_id=config.alpaca_api_key, secret_key=config.alpaca_api_secret ) if not self.alpaca_rest_client: raise AssertionError( "Failed to authenticate Alpaca RESTful client" ) def get_symbols(self) -> List[Dict]: if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated polygon client") data = self.alpaca_rest_client.list_assets() return data def get_symbol_data( self, symbol: str, start: date, end: date = date.today(), scale: TimeScale = TimeScale.minute, ) -> pd.DataFrame: if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated Alpaca client") t: TimeFrame = ( TimeFrame.Minute if scale == TimeScale.minute else TimeFrame.Day if scale == TimeScale.day else None ) data = self.alpaca_rest_client.get_bars( symbol=symbol, timeframe=t, start=start, end=end, limit=10000 ).df if data.empty: raise ValueError( f"[ERROR] {symbol} has no data for {start} to {end} w {scale.name}" ) return data
from analysis import NumAnalysis from alpaca_trade_api.rest import REST import sys BASE_URL = "https://paper-api.alpaca.markets" ALPACA_API_KEY = sys.argv[1] ALPACA_SECRET_KEY = sys.argv[2] api = REST(ALPACA_API_KEY,ALPACA_SECRET_KEY,BASE_URL) result = NumAnalysis(api).IsActive() assert result == "ACTIVE" result = NumAnalysis(api).IsBuy("TSLA") print("Is Tesla a buy?") print(result) print("Is Peloton a buy?") print(NumAnalysis(api).IsBuy("PTON"))
def runTicker(api, ticker): today = datetime.datetime.now() yesterday = today + datetime.timedelta(days=-1) d1 = yesterday.strftime("%Y-%m-%d") fouryao = (today + datetime.timedelta(days=-364 * 4.5)).strftime("%Y-%m-%d") trade_days = api.get_bars(ticker, TimeFrame.Day, fouryao, d1, 'raw').df return trade_days #print(ticker) #print(trade_days) ALPACA_ID = os.getenv('ALPACA_ID') ALPACA_PAPER_KEY = os.getenv('ALPACA_PAPER_KEY') ALPHA_ID = os.getenv('ALPHA_ID') api = REST(ALPACA_ID, ALPACA_PAPER_KEY) ts = TimeSeries(key=ALPHA_ID) spy = runTicker(api, 'SPY') ticker = 'X' ticker = 'TSLA' stock_info = runTicker(api, ticker) stock_info = runTickerAlpha(ts, ticker) spy = runTickerAlpha(ts, 'SPY') print(spy['close'][0]) #spy['adj_close']/=spy['adj_close'][0] print(spy) #stock_info['adj_close']/=stock_info['adj_close'][0] #stock_info['adj_close']/=spy['adj_close'] print(stock_info) spy_info = GetPastPerformance(spy)
class AlpacaTrader(Trader): def __init__(self, qm: QueueMapper = None): self.market_open: Optional[datetime] self.market_close: Optional[datetime] self.alpaca_rest_client = REST( base_url=URL(config.alpaca_base_url), key_id=config.alpaca_api_key, secret_key=config.alpaca_api_secret, ) if not self.alpaca_rest_client: raise AssertionError( "Failed to authenticate Alpaca RESTful client" ) if qm: self.alpaca_ws_client = Stream( base_url=URL(config.alpaca_base_url), key_id=config.alpaca_api_key, secret_key=config.alpaca_api_secret, ) if not self.alpaca_ws_client: raise AssertionError( "Failed to authenticate Alpaca web_socket client" ) self.alpaca_ws_client.subscribe_trade_updates( AlpacaTrader.trade_update_handler ) self.running_task: Optional[asyncio.Task] = None now = datetime.now(nyc) calendar = self.alpaca_rest_client.get_calendar( start=now.strftime("%Y-%m-%d"), end=now.strftime("%Y-%m-%d") )[0] if now.date() >= calendar.date.date(): self.market_open = now.replace( hour=calendar.open.hour, minute=calendar.open.minute, second=0, microsecond=0, ) self.market_close = now.replace( hour=calendar.close.hour, minute=calendar.close.minute, second=0, microsecond=0, ) else: self.market_open = self.market_close = None super().__init__(qm) async def is_order_completed(self, order) -> Tuple[bool, float]: if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated Alpaca client") status = self.alpaca_rest_client.get_order(order_id=order.id) if status.filled_qty == order.qty: return True, float(status.filled_avg_price) return False, 0.0 def get_market_schedule( self, ) -> Tuple[Optional[datetime], Optional[datetime]]: if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated Alpaca client") return self.market_open, self.market_close def get_trading_days( self, start_date: date, end_date: date = date.today() ) -> pd.DataFrame: if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated Alpaca client") calendars = self.alpaca_rest_client.get_calendar( start=str(start_date), end=str(end_date) ) _df = pd.DataFrame.from_dict([calendar._raw for calendar in calendars]) _df["date"] = pd.to_datetime(_df.date) return _df.set_index("date") def get_position(self, symbol: str) -> float: if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated Alpaca client") return self.alpaca_rest_client.get_position(symbol) async def get_order(self, order_id: str): if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated Alpaca client") return self.alpaca_rest_client.get_order(order_id) def is_market_open_today(self) -> bool: return self.market_open is not None def get_time_market_close(self) -> Optional[timedelta]: if not self.is_market_open_today(): raise AssertionError("Market closed today") return ( self.market_close - datetime.now(nyc) if self.market_close else None ) async def reconnect(self): self.alpaca_rest_client = REST( key_id=config.alpaca_api_key, secret_key=config.alpaca_api_secret ) if not self.alpaca_rest_client: raise AssertionError( "Failed to authenticate Alpaca RESTful client" ) async def run(self) -> Optional[asyncio.Task]: if not self.running_task: tlog("starting Alpaca listener") self.running_task = asyncio.create_task( self.alpaca_ws_client._trading_ws._run_forever() ) return self.running_task async def close(self): if not self.alpaca_ws_client: raise AssertionError("Must call w/ authenticated Alpaca client") if self.running_task: await self.alpaca_ws_client.stop_ws() async def get_tradeable_symbols(self) -> List[str]: if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated Alpaca client") data = self.alpaca_rest_client.list_assets() return [asset.symbol for asset in data if asset.tradable] async def get_shortable_symbols(self) -> List[str]: if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated Alpaca client") data = self.alpaca_rest_client.list_assets() return [ asset.symbol for asset in data if asset.tradable and asset.easy_to_borrow and asset.shortable ] async def is_shortable(self, symbol) -> bool: if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated Alpaca client") asset = self.alpaca_rest_client.get_asset(symbol) return ( asset.tradable is not False and asset.shortable is not False and asset.status != "inactive" and asset.easy_to_borrow is not False ) async def cancel_order(self, order_id: str): if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated Alpaca client") self.alpaca_rest_client.cancel_order(order_id) async def submit_order( self, symbol: str, qty: float, side: str, order_type: str, time_in_force: str, limit_price: str = None, stop_price: str = None, client_order_id: str = None, extended_hours: bool = None, order_class: str = None, take_profit: dict = None, stop_loss: dict = None, trail_price: str = None, trail_percent: str = None, ): if not self.alpaca_rest_client: raise AssertionError("Must call w/ authenticated Alpaca client") return self.alpaca_rest_client.submit_order( symbol, str(qty), side, order_type, time_in_force, limit_price, stop_price, client_order_id, extended_hours, order_class, take_profit, stop_loss, trail_price, trail_percent, ) @classmethod async def trade_update_handler(cls, data): symbol = data.__dict__["_raw"]["order"]["symbol"] data.__dict__["_raw"]["EV"] = "trade_update" data.__dict__["_raw"]["symbol"] = symbol try: cls.get_instance().queues[symbol].put( data.__dict__["_raw"], timeout=1 ) except queue.Full as f: tlog( f"[EXCEPTION] process_message(): queue for {symbol} is FULL:{f}, sleeping for 2 seconds and re-trying." ) raise except AssertionError: for q in cls.get_instance().queues.get_allqueues(): q.put(data.__dict__["_raw"], timeout=1) except Exception as e: tlog(f"[EXCEPTION] process_message(): exception {e}") traceback.print_exc()
PERCENT_HOLD = try_cast(params['PERCENT_HOLD'], float, 1 / 20) #Get stock list from Sheets df = pd.DataFrame(get_range(gs, config['SHEETS']['SPREADSHEET_ID'], config['SHEETS']['STOCK_SHEET'], config['SHEETS']['RANGE']), columns=['Symbol', 'Name', 'Price', 'Market Cap']) #Convert string numbers into floats df['Price'] = df['Price'].str.replace(',', '').str.replace('$', '').astype(np.double) df['Market Cap'] = df['Market Cap'].str.replace(',', '').str.replace( '$', '').astype(np.double) api = REST(key_id=config['ALPACA']['API_KEY'], secret_key=config['ALPACA']['SECRET_KEY']) account = api.get_account() buying_power = float(account.buying_power) positions = pd.DataFrame.from_dict([{ "Symbol": p.symbol, "Quantity": float(p.qty), "Avg Entry Price": float(p.avg_entry_price), "Current Price": float(p.current_price), "Total Cost": float(p.cost_basis),
if min_price < (0.9 * low_price): days_less_thr10 += 1 if min_price < (0.85 * low_price): days_less_thr15 += 1 sys.stdout.flush() print('Summary %s:' % ticker) print(' %s tested days: %s' % (ticker, total_days_tested)) print(' %s days below thr: %s' % (ticker, days_less_thr)) print( ' %s tested days: %s days below thr: %s, 5perc: %s, 10perc: %s, 15perc: %s' % (ticker, total_days_tested, days_less_thr, days_less_thr5, days_less_thr10, days_less_thr15)) sys.stdout.flush() api = REST('PKBYDGSHYI2IGLDVEGDY', '1LpyIHmJXN7F7uT1C2ZPydjh9LcVbToBJD7E5e3Y') ticker = 'TSLA' #ticker='AAPL' #ticker='RTX' #ticker='JFU' #ticker='MPC' #ticker='GOOGL' #ticker='F' skip = True if False: #for t in b.stock_lista: for t in b.stock_list: #for t in [[ticker]]: #if t[0]=='SCCO': if t[0] == 'VIAB':
s3 = boto3.resource("s3") secrets = aws_secrets.get_secrets() APCA_API_KEY_ID = secrets["APCA-API-KEY-ID"] APCA_API_SECRET_KEY = secrets["APCA-API-SECRET-KEY"] APCA_DATA_BARS_URL = secrets["APCA-DATA-BARS-V1-URL"] APCA_API_PORTFOLIO_BASE_URL = secrets["APCA-API-PORTFOLIO-BASE-URL"] APCA_WEB_SOCKET = secrets["APCA-WEB-SOCKET"] HEADERS = json.loads(secrets["HEADERS"]) HEADERS["APCA-API-KEY-ID"] = APCA_API_KEY_ID HEADERS["APCA-API-SECRET-KEY"] = APCA_API_SECRET_KEY screened_tickers = (s3.Bucket("trading-bot-s3").Object( "screened_tickers.json").get()["Body"].read().decode("UTF-8").split(",")) api = REST(APCA_API_KEY_ID, APCA_API_SECRET_KEY, APCA_API_PORTFOLIO_BASE_URL) # Alpaca WebSocket config stuff AUTH = { "action": "auth", "key": APCA_API_KEY_ID, "secret": APCA_API_SECRET_KEY, } LISTEN = {"action": "subscribe", "bars": screened_tickers} def on_open(ws): ws.send(json.dumps(AUTH)) ws.send(json.dumps(LISTEN))
def main(config, args): # are we trading forex? if args.forex: print('[-] do stuff with Oanda.') try: oanda = v20.Context( config['oanda']['host'], config['oanda']['port'], token=config['oanda']['token'] ) except V20ConnectionError as error: raise error pair = 'EUR_USD' try: broker = ForexBroker(oanda, pair) except BrokerException as error: raise error else: # is our account restricted from trading? if broker.trading_blocked: raise BrokerException('[!] Insufficient trading balances, or account is otherwise restricted from trading.') # how much money can we use to open new positions? if args.cash is not None: print('[?] ${} in simulated account balance.'.format(args.cash)) else: print('[?] ${} is available in cash.'.format(broker.trade_balance['tb'])) # are we trading crypto? if args.crypto: print('[-] do stuff with Kraken.') try: api = krakenex.API( key=config['kraken']['api_key'], secret=config['kraken']['private_key']) kraken = KrakenAPI(api, tier='Starter') except KrakenAPIError as error: raise error pair = 'BATUSD' try: broker = KrakDealer(kraken, pair=pair) except BrokerException as error: raise error else: # is our account restricted from trading? if broker.trading_blocked: raise BrokerException('[!] Insufficient trading balances, or account is otherwise restricted from trading.') # how much money can we use to open new positions? if args.cash is not None: print('[?] ${} in simulated account balance.'.format(args.cash)) else: print('[?] ${} is available in cash.'.format(broker.trade_balance['tb'])) else: # we must be trading stocks try: alpaca = REST( base_url=config['alpaca']['APCA_API_BASE_URL'], key_id=config['alpaca']['APCA_API_KEY_ID'], secret_key=config['alpaca']['APCA_API_SECRET_KEY'], api_version=config['alpaca']['VERSION']) except APIError as error: raise error try: broker = Broker(alpaca) except (BrokerException, BrokerValidationException) as error: raise error else: # is our account restricted from trading? if broker.trading_blocked: raise BrokerException('[!] Account is currently restricted from trading.') # how much money can we use to open new positions? if args.cash is not None: print('[?] ${} in simulated account balance.'.format(args.cash)) else: print('[?] ${} is available in cash.'.format(broker.cash)) # try and import the corresponding Python file from algos try: algorithm = import_module(f'algos.{args.algorithm}', package='Algorithm') except ImportError as error: raise error else: algorithm.run(broker, args)
from alpaca_trade_api.rest import REST, TimeFrame import sys BASE_URL = "https://paper-api.alpaca.markets" ALPACA_API_KEY = sys.argv[1] ALPACA_SECRET_KEY = sys.argv[2] api = REST(ALPACA_API_KEY, ALPACA_SECRET_KEY, BASE_URL) account = api.get_account() print("Your account is:" + account.status) rawData = api.get_bars("KO", TimeFrame.Day, "2021-06-01", "2021-07-07", limit=10, adjustment='raw').df print(rawData) order = api.submit_order( symbol='KO', qty=1, side='buy', type='market', time_in_force='day', ) print(order)
from dotenv import load_dotenv import os from alpaca_trade_api.rest import REST, TimeFrame import pandas as pd from alpaca_trade_api.stream2 import StreamConn import threading #load_dotenv() API_KEY = "your api key here" API_SECRET = "your api secret here" BASE_URL = "https://paper-api.alpaca.markets" api = REST(API_KEY, API_SECRET, BASE_URL, api_version='v2') account = REST(API_KEY, API_SECRET, BASE_URL, api_version="v2").get_account() def runTest(): blocked = False if account.trading_blocked: blocked = True if blocked == False: print("running") connection = StreamConn(API_KEY, API_SECRET, base_url=BASE_URL, data_url="wss://data.alpaca.markets", data_stream="alpacadatav1")
class TestBroker(TestCase): config = parse_configs(path=os.path.join('../../', 'config.ini')) alpaca = REST(base_url=config['alpaca']['APCA_API_BASE_URL'], key_id=config['alpaca']['APCA_API_KEY_ID'], secret_key=config['alpaca']['APCA_API_SECRET_KEY'], api_version=config['alpaca']['VERSION']) broker = Broker(alpaca) def test_get_account(self): res = TestBroker.broker.get_account() self.assertIsInstance(res, Ent.Account) def test_get_clock(self): res = TestBroker.broker.get_clock() self.assertIsInstance(res, Ent.Clock) def test_get_calendar(self): start = time_from_timestamp(time.time() - (604800 * 54)) end = time_from_timestamp(time.time()) res = TestBroker.broker.get_calendar(start_date=start, end_date=end) self.assertIsInstance(res, list) self.assertIsInstance(res[0], Ent.Calendar) def test_get_assets(self): res = TestBroker.broker.get_assets() self.assertIsInstance(res, list) self.assertIsInstance(res[0], Ent.Asset) def test_get_asset(self): ticker = 'AAPL' res = TestBroker.broker.get_asset(ticker) self.assertIsInstance(res, Ent.Asset) def test_get_positions(self): res = TestBroker.broker.get_positions() self.assertIsInstance(res, list) self.assertIsInstance(res[0], Ent.Position) def test_get_position(self): ticker = 'AAPL' res = TestBroker.broker.get_position(ticker) self.assertIsInstance(res, Ent.Position) def test_close_all_positions(self): res = TestBroker.broker.close_all_positions() self.assertIsInstance(res, list) self.assertEqual(len(res), 0) def test_close_position(self): ticker = 'AAPL' res = TestBroker.broker.close_position(ticker) self.assertIsInstance(res, Ent.Order) def test_get_orders(self): res = TestBroker.broker.get_orders() self.assertIsInstance(res, list) self.assertIsInstance(res[0], Ent.Order) def test_get_order(self): ticker = 'AAPL' res = TestBroker.broker.get_order() print('[] ') def test_submit_order(self): res = TestBroker.broker.submit_order() print('[] ') def test_replace_order(self): res = TestBroker.broker.replace_order() print('[] ') def cancel_all_orders(self): res = TestBroker.broker.cancel_all_orders() print('[] ') def test_cancel_order(self): res = TestBroker.broker.cancel_order() print('[] ') def test_get_asset_df(self): res = TestBroker.broker.get_asset_df() print('[] ') def test_get_watchlists(self): res = TestBroker.broker.get_watchlists() print('[] ') def test_get_watchlist(self): res = TestBroker.broker.get_watchlist() print('[] ') def test_add_watchlist(self): res = TestBroker.broker.add_watchlist() print('[] ') def test_add_to_watchlist(self): res = TestBroker.broker.add_to_watchlist() print('[] ') def test_clear_watchlist(self): res = TestBroker.broker.clear_watchlist() print('[] ') def test_calculate_tolerable_risk(self): res = TestBroker.broker.calculate_tolerable_risk() print('[] ') def test_calculate_position_size(self): res = TestBroker.broker.calculate_position_size() print('[] ')
def download_symbol(cls, symbol: str, timeframe: str = '1d', start: tp.DatetimeLike = 0, end: tp.DatetimeLike = 'now UTC', adjustment: tp.Optional[str] = 'all', limit: int = 500, exchange: tp.Optional[str] = 'CBSE', **kwargs) -> tp.Frame: """Download the symbol. Args: symbol (str): Symbol. timeframe (str): Timeframe of data. Must be integer multiple of 'm' (minute), 'h' (hour) or 'd' (day). i.e. '15m'. See https://alpaca.markets/data. !!! note Data from the latest 15 minutes is not available with a free data plan. start (any): Start datetime. See `vectorbt.utils.datetime_.to_tzaware_datetime`. end (any): End datetime. See `vectorbt.utils.datetime_.to_tzaware_datetime`. adjustment (str): Specifies the corporate action adjustment for the stocks. Allowed are `raw`, `split`, `dividend` or `all`. limit (int): The maximum number of returned items. exchange (str): For crypto symbols. Which exchange you wish to retrieve data from. Allowed are `FTX`, `ERSX`, `CBSE` For defaults, see `data.alpaca` in `vectorbt._settings.settings`. """ from vectorbt._settings import settings from alpaca_trade_api.rest import TimeFrameUnit, TimeFrame, REST alpaca_cfg = settings['data']['alpaca'] client_kwargs = dict() for k in get_func_kwargs(REST): if k in kwargs: client_kwargs[k] = kwargs.pop(k) client_kwargs = merge_dicts(alpaca_cfg, client_kwargs) client = REST(**client_kwargs) _timeframe_units = {'d': TimeFrameUnit.Day, 'h': TimeFrameUnit.Hour, 'm': TimeFrameUnit.Minute} if len(timeframe) < 2: raise ValueError("invalid timeframe") amount_str = timeframe[:-1] unit_str = timeframe[-1] if not amount_str.isnumeric() or unit_str not in _timeframe_units: raise ValueError("invalid timeframe") amount = int(amount_str) unit = _timeframe_units[unit_str] _timeframe = TimeFrame(amount, unit) start_ts = to_tzaware_datetime(start, tz=get_utc_tz()).isoformat() end_ts = to_tzaware_datetime(end, tz=get_utc_tz()).isoformat() def _is_crypto_symbol(symbol): return len(symbol) == 6 and "USD" in symbol if _is_crypto_symbol(symbol): df = client.get_crypto_bars( symbol=symbol, timeframe=_timeframe, start=start_ts, end=end_ts, limit=limit, exchanges=exchange ).df else: df = client.get_bars( symbol=symbol, timeframe=_timeframe, start=start_ts, end=end_ts, adjustment=adjustment, limit=limit ).df # filter for OHLCV # remove extra columns df.drop(['trade_count', 'vwap'], axis=1, errors='ignore', inplace=True) # capitalize df.rename(columns={ 'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close', 'volume': 'Volume', 'exchange': 'Exchange' }, inplace=True) df['Open'] = df['Open'].astype(float) df['High'] = df['High'].astype(float) df['Low'] = df['Low'].astype(float) df['Close'] = df['Close'].astype(float) df['Volume'] = df['Volume'].astype(float) return df
def main(): rest = REST(API_KEY, SECRET_KEY, base_url='https://paper-api.alpaca.markets') all_assets = rest.list_assets() working_symbols = [ x.symbol for x in all_assets if x.tradable and x.status == 'active' ] positions = {} trading = False today = datetime.datetime.today() start = datetime.datetime(today.year, today.month, today.day, 6, 30, 30) end = datetime.datetime(today.year, today.month, today.day, 7, 0, 0) total_cash = float(rest.get_account().equity) cash_per_trade = (total_cash - 25000) / NUM_TRADES current_trades = 0 while True: now = datetime.datetime.today() if now > start: trading = True if now > end: break if trading and current_trades < NUM_TRADES: snapshots = rest.get_snapshots(working_symbols) for stock, data in snapshots.items(): try: prev_close = float(data.prev_daily_bar.c) today_open = float(data.daily_bar.o) current = float(data.daily_bar.c) except: continue if (today_open - prev_close) / prev_close > 0.15: working_symbols.remove(stock) continue if current < today_open * 0.9 and current < 40 and current_trades < NUM_TRADES: qty = cash_per_trade // (today_open * 0.9) order = rest.submit_order( symbol=stock, side="buy", qty=qty, type="limit", time_in_force="gtc", limit_price=today_open * 0.9, order_class="bracket", stop_loss={"stop_price": today_open * 0.6}, take_profit={"limit_price": today_open * 0.95}) print(order) if order.status in [ "new", "accepted", "filled", "partially_filled" ]: positions[stock] = order.id working_symbols.remove(stock) current_trades += 1 time.sleep(20) actual_positions = [x.symbol for x in rest.list_positions()] for stock, order_id in positions.items(): if stock not in actual_positions: rest.cancel_order(order_id)
from dotenv import load_dotenv import os from alpaca_trade_api.rest import REST, TimeFrame load_dotenv() api = REST() bars = api.get_bars("AAPL", TimeFrame.Hour, "2021-02-08", "2021-02-08", limit=10, adjustment='raw').df print(bars)
def run(): config = ConfigParser() config.read('./config.ini') API_KEY = config['ALPACA']['API_KEY'] SECRET_KEY = config['ALPACA']['SECRET_KEY'] api = REST(key_id=API_KEY, secret_key=SECRET_KEY) GOOGLE_SA_PATH = './service_account.json' assert os.path.exists( GOOGLE_SA_PATH ), "Unable to locate Google Sheets service account credentials" #Google Sheets Auth gs = auth(GOOGLE_SA_PATH) #Get params from Sheets params = { row[0]: row[1] for row in get_range(gs, config['SHEETS']['SPREADSHEET_ID'], config['SHEETS'] ['PARAM_SHEET'], config['SHEETS']['PARAM_RANGE']) } #Read params into variables POWER = try_cast(params['POWER'], float, 1 / 3) PERCENT_HOLD = try_cast(params['PERCENT_HOLD'], float, 1 / 20) df = pd.DataFrame(get_range(gs, config['SHEETS']['SPREADSHEET_ID'], config['SHEETS']['STOCK_SHEET'], config['SHEETS']['STOCK_RANGE']), columns=['Symbol', 'Name', 'Price', 'Market Cap']) #Convert string numbers into floats df['Price'] = df['Price'].str.replace(',', '').str.replace('$', '').astype(np.double) df['Market Cap'] = df['Market Cap'].str.replace(',', '').str.replace( '$', '').astype(np.double) #Get cash available to trade buying_power = get_buying_power(api) * (1 - PERCENT_HOLD) #Get currently held positions positions = get_positions(api) df = df.merge(positions, on='Symbol', how='left').fillna('0').astype({'Total Value': np.double}) df['Derived Percentage'] = np.power(df['Market Cap'], POWER) / np.power( df['Market Cap'], POWER).sum() df['Current Percentage'] = df['Total Value'] / df['Total Value'].sum() df['Transaction Percentage'] = df['Derived Percentage'] - df[ 'Current Percentage'] df = df[df['Transaction Percentage'] > 0] df['Purchase Value'] = (df['Transaction Percentage'] / df['Transaction Percentage'].sum()) * buying_power api.cancel_all_orders() for r in df[df['Purchase Value'] > 5].to_dict(orient='records'): put_fractional_order(api, r['Symbol'], r['Purchase Value'], 'buy')
timeframes = { '1D':1, } def process_bar(bar): # process bar print(bar) store = alpaca.AlpacaStore( #key_id=LIVE_KEY, #secret_key=LIVE_SECRET_KEY, key_id=ALPACA_API_KEY, secret_key=ALPACA_SECRET_KEY, paper=ALPACA_PAPER ) api = REST(ALPACA_API_KEY, ALPACA_SECRET_KEY, api_version="v2") bars = api.get_bars_iter("AAPL", TimeFrame.Minute, "2021-02-08", "2021-02-08", limit=120, adjustment="raw") for i in bars: print(i.c) if not ALPACA_PAPER: print(f"LIVE TRADING") broker = store.getbroker() cerebro.setbroker(broker)
if min_price<(0.95*low_price): days_less_thr5+=1 if min_price<(0.9*low_price): days_less_thr10+=1 if min_price<(0.85*low_price): days_less_thr15+=1 sys.stdout.flush() print('Summary %s:' %ticker) print(' %s tested days: %s' %(ticker,total_days_tested)) print(' %s days below thr: %s' %(ticker,days_less_thr)) print(' %s tested days: %s days below thr: %s, 5perc: %s, 10perc: %s, 15perc: %s' %(ticker, total_days_tested, days_less_thr,days_less_thr5,days_less_thr10,days_less_thr15)) sys.stdout.flush() ALPACA_ID = os.getenv('ALPACA_ID') ALPACA_PAPER_KEY = os.getenv('ALPACA_PAPER_KEY') api = REST(ALPACA_ID,ALPACA_PAPER_KEY) ticker='DZSI' ticker='CBT' ticker='X' #ticker='HAL' runTicker(api,ticker) #sys.exit(0) #ticker='AAPL' #ticker='RTX' #ticker='JFU' #ticker='MPC' #ticker='GOOGL' #ticker='F' skip=True
def run(): config = ConfigParser() config.read('./config.ini') #The bucket in s3 to write to BUCKET_NAME = config['AWS']['S3_BUCKET_NAME'] #The location of the logging files to write to POSITIONS_PATH = config['LOGGING']['POSITIONS_PATH'] TRANSFERS_PATH = config['LOGGING']['TRANSFERS_PATH'] PORFOLIO_VALUE_PATH = config['LOGGING']['PORTFOLIO_VALUE_PATH'] #Whether to overwrite positions overwrite = os.environ.get('OVERWRITE', 'False').capitalize() == 'True' df_to_json = {'indent': 4, 'orient': 'records', 'date_format': 'iso'} #Alpaca API connection api = REST(key_id=config['ALPACA']['API_KEY'], secret_key=config['ALPACA']['SECRET_KEY']) #Get cash transfers and write to s# transfers = get_account_activity(api, "TRANS") write_object_to_s3(json.dumps(transfers, indent=4), BUCKET_NAME, TRANSFERS_PATH, ACL="public-read") #Get positions df = get_positions(api) df['Date'] = date.today() df['Date'] = pd.to_datetime(df['Date']).dt.tz_localize(None) if not overwrite and s3_object_exists(BUCKET_NAME, POSITIONS_PATH): #Join the most recent data with what exists in s3 old = pd.read_json(f's3://{BUCKET_NAME}/{POSITIONS_PATH}', orient='records') old['Date'] = df['Date'].dt.tz_localize(None) df = old.merge(df, on=["Symbol", "Date"], how='outer', suffixes=[' Old', " New"]) df['Latest Price'] = df['Latest Price New'].combine_first( df['Latest Price Old']) df['Quantity'] = df['Quantity New'].combine_first(df['Quantity Old']) df['Total Cost'] = df['Total Cost New'].combine_first( df['Total Cost Old']) df['Average Cost'] = df['Average Cost New'].combine_first( df['Average Cost Old']) df['Total Value'] = df['Total Value New'].combine_first( df['Total Value Old']) df = df[[ 'Symbol', 'Latest Price', 'Quantity', 'Total Cost', 'Average Cost', 'Total Value', 'Date' ]] #Write positions to s3 write_object_to_s3(df.to_json(**df_to_json), BUCKET_NAME, POSITIONS_PATH, ACL="public-read") #Get account value over time and write to s3 gr = df.groupby( 'Date', as_index=False).sum()[['Date', 'Total Cost', 'Total Value']] write_object_to_s3(gr.to_json(**df_to_json), BUCKET_NAME, PORFOLIO_VALUE_PATH, ACL='public-read')