为什么我的股票交易算法不交易?

问题描述 投票:0回答:0

所以我正在尝试制作一个非常简单的股票算法。它应该使用每日定价购买标准普尔 500 指数中从 32 RSI 以下到 32 RSI 以上的任何股票。它连接到羊驼进行交易 我似乎没有在代码中遇到任何错误,但它没有进行任何交易。我在 API 调用之间设置了一个 3 秒的休眠计时器,因为它发送了太多、获取和错误,所以这可能导致它休眠太多?哦,如果有帮助的话,我会把它放在谷歌云虚拟机上永久运行以进行交易。 非常感谢您的帮助,您也可以随意使用该策略。

我试着用睡眠功能运行它,没有睡眠功能。奇怪的是,我的朋友说他在市场开盘时运行了没有睡眠功能的程序,它确实为他下了一些交易,但交易是错误的,他还对程序进行了一些编辑。我认为参数非常简单,所以如果我没有提供任何需要的信息,请告诉我。

import alpaca_trade_api as tradeapi
from alpaca_trade_api import REST
import pandas as pd
import ta
import datetime
import time

# Set up Alpaca API
api_key = 'apikey'
api_secret = 'secretkey'
base_url = 'https://paper-api.alpaca.markets'
api = tradeapi.REST(api_key, api_secret, base_url, api_version='v2')

# Get S&P500 stock symbols
assets = api.list_assets(status='active', asset_class='us_equity')
filtered_assets = [asset for asset in assets if asset.exchange == 'NYSE']
symbols = [asset.symbol for asset in filtered_assets]
#symbols = ['AAPL', 'MSFT', 'AMZN']

# Define RSI parameters
rsi_period = 14
rsi_buy_threshold = 32

# Define trade parameters
quantity = 1

# Create position entry timestamps dictionary
position_entry_timestamps = {}

# Set up trading loop
while True:

    # Wait for the next market open
    clock = api.get_clock()
    if clock.is_open:
        time_to_wait = (clock.next_close - clock.timestamp).total_seconds()
    else:
        time_to_wait = (clock.next_open - clock.timestamp).total_seconds()

    # Limit the number of API requests made
    if time_to_wait > 30:
        time_to_wait = 30

    # Wait until it's time to fetch new data
    time.sleep(time_to_wait)

    # Get latest price data for S&P500 stocks
    prices = {}

    for symbol in symbols:
        try:
            bars = api.get_bars(timeframe='1D', symbol=symbol, limit=rsi_period + 1)
            if bars:
                close_prices = [bar.c for bar in bars]
                prices[symbol] = close_prices
        except Exception as e:
            print(f"Error fetching data for {symbol}: {e}")

    # Calculate RSI for each stock
    rsis = pd.DataFrame(index=symbols, columns=['rsi'])
    for symbol in symbols:
        if symbol in prices:
            close_prices = pd.Series(prices[symbol])
            if len(close_prices) >= rsi_period:
                rsi = ta.rsi(close_prices, rsi_period)[-1]
                rsis.at[symbol, 'rsi'] = ta.rsi(close_prices, rsi_period)[-1]

    # Buy shares for stocks with RSI crossing above buy threshold
    for symbol, rsi in rsis.itertuples():
        if rsi is not None and rsi >= rsi_buy_threshold:
            print(f"{symbol} RSI crossed threshold: {rsi}")
            try:
                position = api.get_position(symbol)
                if position.qty == '0':
                    order = api.submit_order(symbol=symbol, qty=quantity, side='buy', type='market',
                                             time_in_force='gtc')
                    position_entry_timestamps[symbol] = pd.Timestamp.now(tz='America/New_York')
            except tradeapi.rest.APIError as e:
                if e.status_code == 404:  # Position not found
                    order = api.submit_order(symbol=symbol, qty=quantity, side='buy', type='market',
                                             time_in_force='gtc')
                    position_entry_timestamps[symbol] = pd.Timestamp.now(tz='America/New_York')

            print(f"Bought {symbol} at market price {order.filled_avg_price}")

    # Sell shares for stocks held for 41 days
    positions = api.list_positions()
    for position in positions:
        if position.symbol in symbols and position.side == 'long':
            if position.symbol in position_entry_timestamps:
                if (pd.Timestamp.now(tz='America/New_York') - position_entry_timestamps[position.symbol]) > pd.Timedelta(days=41):
                    api.submit_order(symbol=position.symbol, qty=abs(int(position.qty)), side='sell', type='market', time_in_force='gtc')

    # Remove the entry timestamp for the sold position
    del position_entry_timestamps[position.symbol]

    print(f"Sold {position.symbol} at market price {api.get_last_trade(position.symbol).price}")

    # Wait for the next trading day
    # Get the current market clock
    clock = api.get_clock()

    # Get the next market open time
    next_open = clock.next_open

    # Convert the next open time to a Unix timestamp
    next_open_timestamp = next_open.timestamp()

    # Get the current time
    current_time = datetime.datetime.now().timestamp()

    # Calculate the time until the next market open
    time_to_wait = next_open_timestamp - current_time

    # Wait until the next market open
    time.sleep(time_to_wait)

python-3.x google-cloud-platform stock quantitative-finance alpaca
© www.soinside.com 2019 - 2024. All rights reserved.