添加留言

回到首页



留言板

游客6742 于 2024-11-12 05:13:20 留言:
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\a - 副本.py", line 17, in <module>
close_prices = pd.to_numeric(close_prices, errors='coerce').dropna()
NameError: name 'pd' is not defined
游客5650 于 2024-11-12 05:12:16 留言:
[*********************100%***********************] 1 of 1 completed

Warning (from warnings module):
File "C:\Users\Administrator\Desktop\a - 副本.py", line 17
close_prices = close_prices[close_prices.apply(lambda x: isinstance(x, (int, float)))]
UserWarning: Boolean Series key will be reindexed to match DataFrame index.
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\a - 副本.py", line 17, in <module>
close_prices = close_prices[close_prices.apply(lambda x: isinstance(x, (int, float)))]
File "C:\Python313\Lib\site-packages\pandas\core\frame.py", line 4093, in __getitem__
return self._getitem_bool_array(key)
File "C:\Python313\Lib\site-packages\pandas\core\frame.py", line 4149, in _getitem_bool_array
key = check_bool_indexer(self.index, key)
File "C:\Python313\Lib\site-packages\pandas\core\indexing.py", line 2662, in check_bool_indexer
raise IndexingError(
pandas.errors.IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).
游客2666 于 2024-11-12 05:12:09 留言:
# 必须先安装 yfinance: pip install yfinance
import yfinance as yf
from datetime import datetime

# 定义开始和结束日期
start_date = "2018-01-01"
end_date = "2024-11-12"

# 选择标的:纳斯达克100(QQQ)或标普500(SPY)
ticker_symbol = "QQQ" # 或 "SPY" 代表标普500

# 获取历史数据
data = yf.download(ticker_symbol, start=start_date, end=end_date)
close_prices = data['Adj Close'].dropna() # 删除任何 NaN 值

# 确保价格列只包含数值
close_prices = close_prices[close_prices.apply(lambda x: isinstance(x, (int, float)))]

# 每日定投计算
investment_per_day = 1 # 每天投资1单位
units_accumulated = 0
total_invested = 0

# 遍历每一天的价格,计算单位数和总投入
for price in close_prices:
units = investment_per_day / float(price) # 确保 price 为浮点型
units_accumulated += units # 累计购买的单位
total_invested += investment_per_day # 累计投入

# 计算当前总市值和收益率
current_value = units_accumulated * float(close_prices.iloc[-1]) # 使用 iloc 获取最后一个有效价格
roi = (current_value - total_invested) / total_invested # 收益率

# 输出结果
print(f"总投入: {total_invested} 美元")
print(f"当前总市值: {current_value:.2f} 美元")
print(f"收益率: {roi * 100:.2f}%")
游客4275 于 2024-11-12 05:10:47 留言:
[*********************100%***********************] 1 of 1 completed
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\a - 副本.py", line 24, in <module>
units = investment_per_day / float(price) # 确保 price 为浮点型
ValueError: could not convert string to float: 'QQQ'
游客7342 于 2024-11-12 05:09:30 留言:
TypeError: unsupported operand type(s) for /: 'int' and 'str'

管理员登录