多次买卖股票 python
时间: 2024-09-19 16:13:51 浏览: 33
在Python中,模拟多次买卖股票通常涉及到策略交易的基本算法,例如著名的"买低卖高"的股票交易策略。你可以使用回测库如pandas_datareader、yfinance或者backtrader等来进行模拟。以下是一个简单的示例,展示如何用pandas结合基本的涨跌停规则来操作:
```python
import pandas as pd
# 假设我们有一个收盘价历史数据
def get_stock_prices(ticker):
# 使用pandas_datareader获取股票价格数据
prices = pd.read_csv('stock_prices.csv', index_col='Date', parse_dates=True)
return prices[ticker]
def simulate_trading(prices, buy_threshold=0.95, sell_threshold=1.05, initial_capital=10000):
capital = initial_capital
shares = 0
for i in range(1, len(prices)):
current_price = prices.iloc[i]
if shares == 0 and prices.iloc[i] / prices.iloc[i-1] < buy_threshold: # 买入
shares = capital // current_price
capital -= shares * current_price
elif shares > 0 and prices.iloc[i] / prices.iloc[i-1] > sell_threshold: # 卖出
profit = shares * current_price - capital
capital += profit
shares = 0
return capital
# 示例使用
ticker = 'AAPL'
prices = get_stock_prices(ticker)
final_capital = simulate_trading(prices)
print(f"最终资本: {final_capital}")
阅读全文