Kerry Back
from alpaca.data import StockHistoricalDataClient
from alpaca.data.requests import StockLatestQuoteRequest
data_client = StockHistoricalDataClient(KEY, SECRET_KEY)
params = StockLatestQuoteRequest(
symbol_or_symbols=df.index.to_list()
)
quotes = data_client.get_stock_latest_quote(params)
df["ask"] = {x: quotes[x].ask_price for x in quotes}
df["bid"] = {x: quotes[x].bid_price for x in quotes}
df["target_dollars"] = (
(1.5*equity/numlong)*df.long -
(0.5*equity/numshort)*df.short
)
df["current_dollars"] = df.current*(df.bid+df.ask)/2
df["trade_dollars"] = df.target_dollars - df.current_dollars
df["trade"] = (
(df.trade_dollars>0)*df.trade_dollars/df.ask
+ (df.trade_dollars<0)*df.trade_dollars/df.bid
)
df["trade"] = df.trade.fillna(0)
df["trade"] = df.trade.astype(int)
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
for tick in df[df.trade!=0].index:
market_order_data = MarketOrderRequest(
symbol=tick,
qty=abs(df.trade[tick]),
side=OrderSide.BUY if df.trade>0 else OrderSide.SELL,
time_in_force=TimeInForce.DAY
)
market_order = trading_client.submit_order(
order_data=market_order_data
)