arleigh418 / python-and-Taiwan-stock-market

Python 金融市場賺大錢聖經:寫出你的專屬指標
54 stars 17 forks source link

python聖經第三章3.2小節的代碼問題 #42

Open MengDoSan opened 11 months ago

MengDoSan commented 11 months ago

import pandas as pd import yfinance as yf

yfinance產出台積電股價資料

stock = yf.Ticker('2330.TW')

獲取20170101-20210202

df = stock.history(start="2017-01-01",end="2021-02-02")

rolling以6為單位位移並取最大值

Highest_high =df['High'].rolling(6).max()

rolling以6為單位位移並取最小值

Lowest_low = df['Low'].rolling(6).min()

一樣用6根作為rolling,並且設計計算函數第一個值減去最後一個值

O_C_high = df['High'].rolling(6).apply(lambda x : x[0]-x[-1])

加入dataframe

df['OCHIGH'] = O_C_high

存成Excel來看一下結果

df.to_excel(r'D:\tradercode\final.xlsx')

df['Highest_high'] = Highest_high df['Lowest_Low'] = Lowest_low df['OCHIGH'] = O_C_high print(df)

以上是從GITHUB上取得到原代碼(除了換了一換excel路徑外) 問題是在儲存到excel時出現以下錯誤 "Excel does not support datetimes with " ValueError: Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel. 請問解決方法是甚麼?

arleigh418 commented 11 months ago

您好, 謝謝您提出的問題。 推測應該是yfinance對於處理時區的方式有所變更,導致存擋時pandas無法正確處理。 簡單的處置方式有二,二選一即可解決您提出的問題,看您覺得哪一個好:

  1. 直接將時區資料轉為string之後再存 df = stock.history(start="2017-01-01", end="2021-02-02") df.index = df.index.astype(str)

  2. 將檔案存成csv df.to_csv("final.csv")