Wyatt Gill
Wyatt Gill

Reputation: 9

Alpaca SMA algo bug


from alpaca_trade_api import REST
import time
import numpy as np
import pandas as pd
import yfinance as yf


api_key = 'PKXE9H6DCGDZ8LU60MAV'
api_secret = 'Zym9PVK7RqgS6mQy0PVhfT4jAwxXCsktQRg25cLT'
base_url = 'https://paper-api.alpaca.markets'

api = REST(api_key, api_secret, base_url)

symbol = 'AAPL'
start_date = '2015-01-01'
end_date = '2022-12-31'
data = yf.download(symbol, start=start_date, end=end_date)

symbol = 'AAPL'
qty = 1

data['SMA_50'] = data['Close'].rolling(window=50).mean()



def check_positions(symbol):
  positions = api.list_positions()
  for position in positions:
    if position.symbol == symbol:
      return int(position.qty)
    return 0


def trade(symbol, qty):
  current_price = api.get_latest_trade(symbol).price
  historical_data = yf.download(symbol,
                                start=start_date,
                                end=end_date,
                                interval='1d')
  historical_data['SMA_50'] = historical_data['Close'].rolling(
      window=50).mean()
  if current_price > historical_data['SMA_50'][-1]:
    if check_positions(symbol) == 0:
      api.submit_order(symbol=symbol,
                       qty=qty,
                       side='buy',
                       type='market',
                       time_in_force=' gtc')
      print("Buy order placed for", symbol, qty)
    elif check_positions(symbol) == 1:
      print("Holding", symbol, qty)
    else:
      print('No positions, Buy side')
  elif current_price < historical_data['SMA_50'][-1]:
    if check_positions(symbol) == 0:
      api.submit_order(symbol=symbol,
                       qty=qty,
                       side='sell',
                       type='market',
                       time_in_force=' gtc')
      print("Short order placed for", symbol, qty)
    elif check_positions(symbol) == 1:
      print("Holding", symbol, qty)
  else:
    print('Stock is one the SMA 50')



while True:
  trade(symbol, qty)
  time.sleep(86400)

[100%%] 1 of 1 completed [100%%] 1 of 1 completed main.py:43: FutureWarning: Series.getitem treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use ser.iloc[pos] if current_price > historical_data['SMA_50'][-1]:

Upvotes: 0

Views: 54

Answers (0)

Related Questions