python list 內的 value 不要變成字串

請問我是想用永豐金的API
想要獲得contracts的資料
代碼如下:

contracts = [api.Contracts.Stocks['2330'], api.Contracts.Stocks['2317']]
snapshots = api.snapshots(contracts)

我contracts 後面想要改成多筆資料

[api.Contracts.Stocks['2330'], api.Contracts.Stocks['2317'], ...]

我先用for迴圈取得字串再變成list

for i in [1101, 1102, 2330, ...]:
    stock_all = "api.Contracts.Stocks['" + str(i) + "']"
    list_all.append(stock_all)
print(list_all)

可以得到:

["api.Contracts.Stocks['1101']", "api.Contracts.Stocks['1102']", "api.Contracts.Stocks['2300]",...]

但是這個list 沒辦法用在 constracts = 後面,因為是字串的形式

Traceback (most recent call last):
  File "c:\!Python\api.py", line 21, in <module>
    snapshots = api.snapshots(contracts)
  File "C:\Users\NeNe\AppData\Local\Programs\Python\Python310\lib\site-packages\shioaji\shioaji.py", line 911, in snapshots
    snapshots = self._solace.snapshots(contracts, timeout, cb)
  File "shioaji\backend\solace\api.pyx", line 1338, in shioaji.backend.solace.api.SolaceAPI.snapshots
AttributeError: 'str' object has no attribute 'dict'

請問應該怎麼做才能夠不要變成字串形式呢?
謝謝

試試看這個?

stocks = [1101, 1102, 2330, ...]
list_all = [api.Contracts.Stocks[str(stock)] for stock in stocks]
1個讚

感謝大大這樣可以用

現在代碼:

list_symbol = [1101, 1102, 2330, ...]
contracts = [api.Contracts.Stocks[str(stock)] for stock in list_symbol]
snapshots = api.snapshots(contracts)

df = pd.DataFrame(snapshots)
df = pd.DataFrame(map(dict, snapshots))

但是會碰到

Traceback (most recent call last):
  File "c:\!Python\api.py", line 33, in <module>
    snapshots = api.snapshots(contracts)
  File "C:\Users\NeNe\AppData\Local\Programs\Python\Python310\lib\site-packages\shioaji\shioaji.py", line 911, in snapshots
    snapshots = self._solace.snapshots(contracts, timeout, cb)
  File "shioaji\backend\solace\api.pyx", line 1338, in shioaji.backend.solace.api.SolaceAPI.snapshots
AttributeError: 'NoneType' object has no attribute 'dict'

用的是永豐金API import shioaji as sj
不知道是不是有股票缺失的
請問要怎麼把None的去除掉
謝謝

如果單純只要濾掉 None 的話,多加一行在 snapshots = ... 前面應該就能解決

contracts = [contract for contract in contracts if contract is not None]

不過我覺得比較正確的作法應該還是要檢查到底哪些是有問題的,我其中一個猜測是 list_symbol 裡面是不是有 0 開頭的? 用數字存的轉字串 0 會被吃掉

1個讚