Giter VIP home page Giter VIP logo

python-and-taiwan-stock-market's Introduction

Python 金融市場賺大錢聖經:寫出你的專屬指標

重要事記

快速索引

google寄信已不支援低安全性模式

2-3小節yahoo_price爬蟲更新

backtrader FileNotFoundError

借串宣傳線上課程>< - Python期貨程式交易課程

Yahoo股市網站更新

新增進階補充

google寄信已不支援低安全性模式

最後更新2022/6/18

google在五月底時不支援低安全模式,因此書中介紹的寄信方式需要修改. 基本上現在要採用google的應用程式密碼功能產生出來的密碼才可做使用 步驟如下可參考:

  1. 確保您的帳戶通過兩步驟驗證
  2. 通過後,一樣至安全性,您應該可以如下圖看到應用程式密碼,請您利用該功能產出密碼 (要通過兩步驟驗證 才會看到應用程式密碼這個選項)
  3. 將您原先程式中的密碼換成第二步驟google所產生出來的密碼應就可寄信,其他部分無需調整

您也可以參考: #28


2-3小節yahoo_price爬蟲更新

最後更新2023/1/27

經讀者反應,該網頁有小幅度的變更,tag變得不一樣導致爬蟲無法獲取資料。 不過變更的幅度不大,您可以先嘗試自行抓抓看新tag。 經測試以下tag目前可正常獲取資料

price = soup.find("fin-streamer", {"data-test": "qsp-price"})

backtrader FileNotFoundError

最後更新2022/1/3

backtrader的FileNotFoundError看起來是有一段小段時間都未被官方修復,因此如果您看到此Error,請首先嘗試書中4.2章節,4-48頁的backtrader的可能問題之一。


借串宣傳線上課程 - Python全方位期貨課程 - 從基礎、爬蟲、回測、Line提醒到AI應用

最後更新2021/11/10

最近有幸受邀在mastertalk上開設線上課程,對於看完本書股票應用的同學,如果對期貨這個領域有興趣,歡迎參考。

我們會將書上的部分技術如何應用在期貨上做出教學,如backtrader。並且實際的應用一些深度學習、機器學習的模型用於價格、漲跌預測。 (當然如果您只是一些期貨應用的小問題,您可以提出issue,我們可以來聊聊,或者我可以在另一篇進階補充中特別說明。此課程純推廣。)


Yahoo股市網站更新

最後更新2021/09/27

新版的Yahoo新聞爬蟲請參考yahoo_news_2.py

需要特別注意,原先utility.py裡面使用的yahoo_new.py,因為已經失效,建議您將yahoo_news_2.py的函數貼utility.py後,引用yahoo_news_2來獲取新聞

Yahoo股市的網站看起來經歷了一場巨大的更新。 很可惜我三四年前爬新聞到撰寫此書時都沒有什麼會影響到程式的更新,所以我認為他算是教學的穩定標的。 不過最近有一波巨大的更新,因此2.4章節(頁數2.49)開始的爬取Yahoo新聞的環節以及3.9章節(3-148)有使用到新聞的部分失效,但我還是希望您能夠看過內容,大致了解一下舊版的網站的爬蟲過程

除網站的tag變更,風格大幅改變之外,我認為在技術上影響最大的在於原本是頁數,現在變成滾動式下拉才會有新聞出來。 如果要爬取完整新聞,在技術上來說我認為難度就提升了一個檔次,變得不太適合初學者爬蟲的標的。 因為滾動式網頁通常解法就是要用Selenium瀏覽器模擬滾動,然後邊滾邊收集新聞。 我初步測試過,這個新式網頁是可以滾到底的,滾到1個月前的新聞。 如果大家對Selenium有興趣可以在issue中提出,如果人數有個大概三四個,大約一兩周我會生出一個範例(抱歉還有正職工作要做,只能用零碎時間開發)。

不過如果是較基本的應用,倒是挺容易的。 原則上較初階的設計方式是這樣,網頁若直接爬取,大約可獲得18-21篇左右的新聞。 因此在設計上初階的方法就是我們將舊的新聞爬蟲的頁數改為想要獲得頭幾篇新聞。 例如舊的傳入2代表我想要2頁新聞,新的傳入2則代表我只看最新的兩篇新聞。 這樣的設計對初學者來說是更加友善的。 如果您要正式使用,請記得之後章節的utility.py通用那一包的Yahoo新聞的函式要記得替換。 因為設計上較為倉促,有任何bug或者是您希望有任何更活潑的設計,都歡迎提出來大家一起討論研究!感謝您的體諒!


新增進階補充

最後更新2021/09/20

我會在另一個地方不定時的分享一些書中沒有說到,但我們有在使用的其他技術。

如果您閱讀完此書,具備一些基本的了解,可以來這裡看看。有任何問題歡迎提出issue或是透過信箱聯繫我。

https://github.com/arleigh418/python-and-Taiwan-stock-market-Advanced

章節對照表

檔案名稱 對照章節
Trading_Strategy_EX/Chapter2/stock_list.py 2.2
Trading_Strategy_EX/Chapter2/yahoo_price.py 2.3
Trading Strategy_EX/Chapter2/yahoo_news.py (因網站更新爬蟲失效)
Trading Strategy_EX/Chapter2/yahoo_news_2.py (因應新網站的新爬蟲)
2.4
Trading_Strategy_EX/Chapter2/TWSE.py 2.5
Trading_Strategy_EX/Chapter3/yfinance_example.py 3.1
Trading_Strategy_EX/Chapter3/pd_example.py
Trading_Strategy_EX/Chapter3/ta_example.py
Trading_Strategy_EX/Chapter3/mine_ta.py
3.2
Trading_Strategy_EX/Chapter3/generate_picture_example.py 3.3
Trading_Strategy_EX/Chapter3/smtp.py 3.4
Trading_Strategy_EX/Chapter3/smtp2.py
Trading_Strategy_EX/Chapter3/AES_Encryption/
3.5
Trading_Strategy_EX/Chapter3/is_open.py
Trading_Strategy_EX/Chapter3/deal_holiday.py
3.6
Trading/1_buy_follow_corp.py 3.7
Trading/2_buy_with_devidend.py
Trading/2_2_buy_with_dividend_price.py
3.8
Trading/3_buy_with_price_fall.py 3.9
Trading/strategy_research.py 4.1
Trading/backtest_research.py 4.2
Trading/tech1_ma_strategy.py 4.3
Trading/tech2_highest.py 4.4
Trading/tech3_macd_ma.py 4.5
Trading Strategy_EX/Chapter3/holidaySchedule.csv 下載下來的2021股市休市表
Trading Strategy_EX\Chapter3\AES_Encryption
Trading\AES_Encryption
帳密加解密工具包
Trading\holiday.xlsx 經處理過後的判斷是否開盤用
Trading\stock_list.xlsx 股票列表(請自行運行程式更新)

勘誤表

訂正日期 對照章節 頁數 對照檔案 錯誤原因 修正內容 勘誤發現

購買

博客來: https://www.books.com.tw/products/0010901963?loc=M_0039_001

momo: https://m.momoshop.com.tw/goods.momo?i_code=9261467

天瓏: https://www.tenlong.com.tw/products/9789860776294

誠品: https://www.eslite.com/product/1001313432682066432001


python-and-taiwan-stock-market's People

Contributors

arleigh418 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

python-and-taiwan-stock-market's Issues

yfinance出错

你好,我是大陆的读者。用yfinance时出现如下错误,试过变更版本没有解决,python亦是3.7.6的版本。不知如何解决,请指教,谢谢。

2021-12-02_130658

新聞僅20筆

您好
依照更新的Yahoo新聞爬蟲
似乎最多只能取得前20筆左右
而該網頁算過並不只如此
不知問題所在

pyfolio 問題

您好,在使用PYTHON 金融市場賺大錢聖經書的tech1_ma_strategy.py時,遇到AttributeError: 'Series' object has no attribute 'iteritems',根據報錯更改(file:///C:/ProgramData/Anaconda3/lib/site-packages/pyfolio/plotting.py)及(file:///C:/ProgramData/Anaconda3/lib/site-packages/pyfolio/tears.py)中的iteritems為items後,仍舊遇到相同報錯,因此想請問是否有遇過此問題及解決方法為何? 感謝~

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

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.
請問解決方法是甚麼?

線上課程請教!!

你好~~請問課程內容中有教學盤中即時運算技術分析嗎??

還有有教怎麼視覺化 盤中運算出來的技術分析圖出來嗎??

煩請回復~~~謝謝老師~~

第1-4虛擬環境

老師您好
關於我在CMD上面輸入python -m venv env
他都沒有任何反應 他只有換行而已
前面PIP安裝套件也一樣 都沒有反應
不知道是不是電腦的問題
未命名

請問關於自動寄信

您好想請問一下
在3-64當中
import sys
sys.path.append('D:\Trading Strategy_EX\Chapter3')
上面這段的用意為何?

另外我嘗試複製一個類似程式,在同一個資料夾下執行範例程式時
出現以下錯誤訊息

File "/Users/mac/Documents/python-and-Taiwan-stock-market-main/Trading Strategy_EX/Chapter3/smtp(def).py", line 16, in
from AES_Encrytion.encrype_process import *

ModuleNotFoundError: No module named 'AES_Encrytion'

之後改為直接執行範例程式smtp.py
就出現下面錯誤訊息
File "/Users/mac/Documents/python-and-Taiwan-stock-market-main/Trading Strategy_EX/Chapter3/smtp.py", line 8, in
from AES_Encryption.encrype_process import *

File "/Users/mac/Documents/python-and-Taiwan-stock-market-main/Trading Strategy_EX/Chapter3/AES_Encryption/encrype_process.py", line 2, in
from AES_Encryption.en_decrype import *

File "/Users/mac/Documents/python-and-Taiwan-stock-market-main/Trading Strategy_EX/Chapter3/AES_Encryption/en_decrype.py", line 1, in
from Crypto.Cipher import AES

ModuleNotFoundError: No module named 'Crypto'

請問是哪裡有問題呢?

stock_list.py執行錯誤

Hello 作者您好 ,
不好意思,我目前打第一個程式就出錯了,請參考以下畫面,我的requests / bs4 / pandas應該都有裝成功,不知道怎麼會這樣,再請您協助解惑一下感謝您

#對網站進行requests,並加入指定的headers一同請求

html_data = requests.get("https://isin.twse.com.tw/isin/C_public.jsp?strMode=2",headers=headers)
Traceback (most recent call last):
File "", line 1, in
NameError: name 'requests' is not defined
print(html_data)
Traceback (most recent call last):
File "", line 1, in
NameError: name 'html_data' is not defined

第二章27頁

老師您好 我照著書上寫的
但目前好像出現了問題
未命名

SMTP問題

您好,
我在嘗試使用SMTP發信時,遇到 smtplib.SMTPAuthenticationError: (535, b'authentication failed (#5.7.1)') 的錯誤問題。
gmail的低安全模式我已經開啟,但仍然無法順利登入發信,還請您協助,謝謝您。

yahoo新聞爬時間問題

你好,我知道yahoo新聞顯示格式後來改變了,不過我想試著一樣在第一頁試著學爬時間來看看,但是怎麼爬都只有報導的資訊,沒有時間,但看網頁上span內是有報單資訊跟時間,想請問這部分該怎麼寫,感謝

image

image

關於yahoo_new小程式

您好:
我在練習3_buy_with_price_fall.py這只程式時
因為有用到get_yahoo_news這個程式
我知道yahoo已經有改版了
所以改寫了下列程式碼
data = requests.get(f"https://tw.stock.yahoo.com/quote/{stock}/news",headers=headers)
但最後呈現的結果是
title url date
0 Error Error Error
是下面的程式都要一併改寫嗎?
能否請板主再放上一個改版後的程式提供參考
謝謝

爬蟲遇到的問題

您好:
之前按照書本在爬蟲抓取股價資料時,發現會出現下列文字
/Users/mac/Documents/spyder/yahoo_price.py:23: GuessedAtParserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 23 of the file /Users/mac/Documents/spyder/yahoo_price.py. To get rid of this warning, pass the additional argument 'features="lxml"' to the BeautifulSoup constructor.

soup = BeautifulSoup(data.text)
Traceback (most recent call last):
請問是什麼問題呢?我是使用mac同時是搭配spyder編譯器

第三章'Crypto'的問題

作者你好,
執行smtp.py時出現No module named 'Crypto'
原因是出在from Crypto.Cipher import AES這行程式碼
pycryptodome已經下載好,請問是甚麼問題呢?
image
image

No module named 'Crypto' after install Crypto through "pip install Crypto".

(env) D:\python-and-Taiwan-stock-market\Trading>python 1_buy_follow_corp.py Traceback (most recent call last): File "D:\python-and-Taiwan-stock-market\Trading\1_buy_follow_corp.py", line 4, in import utility_f as uf File "D:\python-and-Taiwan-stock-market\Trading\utility_f.py", line 10, in from AES_Encryption.encrype_process import * File "D:\python-and-Taiwan-stock-market\Trading\AES_Encryption\encrype_process.py", line 2, in from AES_Encryption.en_decrype import * File "D:\python-and-Taiwan-stock-market\Trading\AES_Encryption\en_decrype.py", line 1, in from Crypto.Cipher import AES ModuleNotFoundError: No module named 'Crypto'

yahoo新聞爬蟲問題

你好,我依照更新的Yahoo新聞爬蟲方法,在最後結果出來的url的連結,都只會連到yahoo首頁,無法連結到相對應的新聞網頁。
不知道是不是我哪裡打錯了,還請麻煩你幫我看一下,謝謝你。
image
image

about pandas rolling

你好,我在練習3-23的程式時,按照書上輸入:

Highest_High=df['High'].rolling(6).max()
Lowest_Low=df['Low'].rolling(6).min()

但最終在excel output時仍然是df的全數據,並無加入"Highest_high"或"Lowest_low" ,我已import pandas,但rolling好像沒生效一樣。

排程的權限問題及執行檔問題

作者您好~在閱讀過程中,發現了3-153頁的程式碼與github程式碼小部分不太一樣,雖然結果不會有太大不同,但不知道是不是不小心的,提供您參考。
問題1:在排程時,會遇到權限不足,要如何提高權限,還是只能使用Administrator 帳號排程?
問題2: 使用Administrator 帳號排程,會出現0*1的錯誤,感覺會是命令應用程式執行的部分有些問題?因為個人不太了解這個結構。
image
image
image
image

您好我想請教關於書上的問題(非常一開始的問題)

作者您好,我想請問在1-21節(虛擬環境那章,我就沒有找到scripts這個資料夾了)
我是使用mac air他有跑出來課本上的include跟lib
但scripts資料夾沒有跑出來,只有一個叫bin的資料夾
其中的檔案是activate.csh/activate.fish/activate/ps1
並沒有deactivate的檔
所以按照課本cd env之後的執行步驟也沒有跑出來

我想說先略過
然後2-20的第一個程式打進去vscode後跳出You don't have an extension for debugging 'Plain Text'. Should we find a 'Plain Text' extension in the Marketplace?(但也沒有可以擴充的掛)

然後我改直接打進cmd跑出來的是zsh: parse error near `}'

我依照我的user-agent打的第一個碼(這是作者的智慧結晶不確定能不能放上來問,如果違反我會馬上刪除,謝謝!!!)
import pandas as pd
import requests
headers = {
"user-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Mobile Safari/537.36"
}
html_data = requests.get ("https://isin.twse.com.tw/isin/C_public.jsp?strMode=2",headers=headers)
print (html_data)

放棄我打的後,改用作者資料夾裡的程式碼也完全不行
不知道是不是在虛擬環境那裡就錯了QQ

麻煩作者了謝謝!

關於 mpl_finance失效的問題

作者您好, 如圖顯示, 舊有的 mpl_finance套件已經被棄用, 進而被新的 mplfinance取代, 我嘗試根據指示安裝並使用 mplfinance, 但卻導致函數 mpf.candlestick2_ochl()失效, 請問新的版本是否已經不支援這個函數? 後面的編碼教學是否也會造成影響? 謝謝.
error
error2

tech2_highest.py執行出錯

您好,
我目前練習到這個程式tech2_highest.py但都會報錯, 用您的程式碼也是如此, 不知道哪裡出問題?

(156) a_return = strat.analyzers.returns.get_analysis()
AttributeError: 'ItemCollection' object has no attribute 'returns'

yfinance的問題

你好,我在使用yfinance套件時發生了一些問題,我上網稍微查過了大家都說要更新yfinance套件,但我已經更新至最新版本,仍然無法解決這個問題,可以請你幫我看一下嗎? 非常感謝你。

import yfinance as yf
import pandas as pd

選擇台積電

stock = yf.Ticker('2330.TW')
df = pd.DataFrame()
df = stock.history(start='2017-01-01', end='2021-02-02')
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\Tim\AppData\Local\Programs\Python\Python39\lib\site-packages\yfinance\base.py", line 157, in history
)
File "C:\Users\Tim\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\Tim\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson_init_.py", line 525, in loads
return _default_decoder.decode(s)
File "C:\Users\Tim\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "C:\Users\Tim\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
File "C:\Users\Tim\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\scanner.py", line 79, in scan_once
return _scan_once(string, idx)
File "C:\Users\Tim\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\scanner.py", line 70, in _scan_once
raise JSONDecodeError(errmsg, string, idx)
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

VS code 跑Jupyter的問題

Dear Sir :
我安裝完擴展後,一樣沒辦法執行,都顯示:找不到指定模組,請問這要怎麼解決?感謝

Log:
Error 23:30:58: DataScience Error [o [Error]: The kernel died. View Jupyter log for further details.
Error: ImportError: DLL load failed while importing error: 找不到指定的模組。....
at c:\Users\MT.vscode\extensions\ms-toolsai.jupyter-2021.11.1001550889\out\client\extension.js:66:1023351
at c:\Users\MT.vscode\extensions\ms-toolsai.jupyter-2021.11.1001550889\out\client\extension.js:66:695951
at c:\Users\MT.vscode\extensions\ms-toolsai.jupyter-2021.11.1001550889\out\client\extension.js:66:696169
at Immediate._onImmediate (c:\Users\MT.vscode\extensions\ms-toolsai.jupyter-2021.11.1001550889\out\client\extension.js:66:697734)
at processImmediate (internal/timers.js:461:21)] {
category: 'kerneldied',
errorMessage: 'ImportError: DLL load failed while importing error: 找不到指定的模組。. \n',
stdErr: 'Traceback (most recent call last):\r\n' +
' File "C:\Users\MT\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 192, in _run_module_as_main\r\n' +
' return _run_code(code, main_globals, None,\r\n' +
' File "C:\Users\MT\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 85, in _run_code\r\n' +
' exec(code, run_globals)\r\n' +
' File "d:\Trading\env\lib\site-packages\ipykernel_launcher.py", line 15, in \r\n' +
' from ipykernel import kernelapp as app\r\n' +
' File "d:\Trading\env\lib\site-packages\ipykernel\init.py", line 2, in \r\n' +
' from .connect import *\r\n' +
' File "d:\Trading\env\lib\site-packages\ipykernel\connect.py", line 10, in \r\n' +
' import jupyter_client\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\init.py", line 6, in \r\n' +
' from .asynchronous import AsyncKernelClient # noqa\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\asynchronous\init.py", line 1, in \r\n' +
' from .client import AsyncKernelClient # noqa\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\asynchronous\client.py", line 6, in \r\n' +
' from jupyter_client.channels import HBChannel\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\channels.py", line 12, in \r\n' +
' import zmq.asyncio\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\init.py", line 125, in \r\n' +
' from zmq import backend\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\init.py", line 32, in \r\n' +
' raise original_error from None\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\init.py", line 27, in \r\n' +
' _ns = select_backend(first)\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\select.py", line 32, in select_backend\r\n' +
' mod = import_module(name)\r\n' +
' File "C:\Users\MT\AppData\Local\Programs\Python\Python38\lib\importlib\init.py", line 127, in import_module\r\n' +
' return _bootstrap._gcd_import(name[level:], package, level)\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\cython\init.py", line 6, in \r\n' +
' from . import (\r\n' +
'ImportError: DLL load failed while importing error: 找不到指定的模組。\r\n',
exitCode: 1,
reason: 'Traceback (most recent call last):\r\n' +
' File "C:\Users\MT\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 192, in _run_module_as_main\r\n' +
' return _run_code(code, main_globals, None,\r\n' +
' File "C:\Users\MT\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 85, in _run_code\r\n' +
' exec(code, run_globals)\r\n' +
' File "d:\Trading\env\lib\site-packages\ipykernel_launcher.py", line 15, in \r\n' +
' from ipykernel import kernelapp as app\r\n' +
' File "d:\Trading\env\lib\site-packages\ipykernel\init.py", line 2, in \r\n' +
' from .connect import *\r\n' +
' File "d:\Trading\env\lib\site-packages\ipykernel\connect.py", line 10, in \r\n' +
' import jupyter_client\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\init.py", line 6, in \r\n' +
' from .asynchronous import AsyncKernelClient # noqa\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\asynchronous\init.py", line 1, in \r\n' +
' from .client import AsyncKernelClient # noqa\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\asynchronous\client.py", line 6, in \r\n' +
' from jupyter_client.channels import HBChannel\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\channels.py", line 12, in \r\n' +
' import zmq.asyncio\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\init.py", line 125, in \r\n' +
' from zmq import backend\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\init.py", line 32, in \r\n' +
' raise original_error from None\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\init.py", line 27, in \r\n' +
' _ns = select_backend(first)\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\select.py", line 32, in select_backend\r\n' +
' mod = import_module(name)\r\n' +
' File "C:\Users\MT\AppData\Local\Programs\Python\Python38\lib\importlib\init.py", line 127, in import_module\r\n' +
' return _bootstrap._gcd_import(name[level:], package, level)\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\cython\init.py", line 6, in \r\n' +
' from . import (\r\n' +
'ImportError: DLL load failed while importing error: 找不到指定的模組。\r\n'
}
Error 23:30:58: DataScience Error [o [Error]: The kernel died. View Jupyter log for further details.
Error: ImportError: DLL load failed while importing error: 找不到指定的模組。....
at c:\Users\MT.vscode\extensions\ms-toolsai.jupyter-2021.11.1001550889\out\client\extension.js:66:1023351
at c:\Users\MT.vscode\extensions\ms-toolsai.jupyter-2021.11.1001550889\out\client\extension.js:66:695951
at c:\Users\MT.vscode\extensions\ms-toolsai.jupyter-2021.11.1001550889\out\client\extension.js:66:696169
at Immediate._onImmediate (c:\Users\MT.vscode\extensions\ms-toolsai.jupyter-2021.11.1001550889\out\client\extension.js:66:697734)
at processImmediate (internal/timers.js:461:21)] {
category: 'kerneldied',
errorMessage: 'ImportError: DLL load failed while importing error: 找不到指定的模組。. \n',
stdErr: 'Traceback (most recent call last):\r\n' +
' File "C:\Users\MT\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 192, in _run_module_as_main\r\n' +
' return _run_code(code, main_globals, None,\r\n' +
' File "C:\Users\MT\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 85, in _run_code\r\n' +
' exec(code, run_globals)\r\n' +
' File "d:\Trading\env\lib\site-packages\ipykernel_launcher.py", line 15, in \r\n' +
' from ipykernel import kernelapp as app\r\n' +
' File "d:\Trading\env\lib\site-packages\ipykernel\init.py", line 2, in \r\n' +
' from .connect import *\r\n' +
' File "d:\Trading\env\lib\site-packages\ipykernel\connect.py", line 10, in \r\n' +
' import jupyter_client\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\init.py", line 6, in \r\n' +
' from .asynchronous import AsyncKernelClient # noqa\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\asynchronous\init.py", line 1, in \r\n' +
' from .client import AsyncKernelClient # noqa\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\asynchronous\client.py", line 6, in \r\n' +
' from jupyter_client.channels import HBChannel\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\channels.py", line 12, in \r\n' +
' import zmq.asyncio\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\init.py", line 125, in \r\n' +
' from zmq import backend\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\init.py", line 32, in \r\n' +
' raise original_error from None\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\init.py", line 27, in \r\n' +
' _ns = select_backend(first)\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\select.py", line 32, in select_backend\r\n' +
' mod = import_module(name)\r\n' +
' File "C:\Users\MT\AppData\Local\Programs\Python\Python38\lib\importlib\init.py", line 127, in import_module\r\n' +
' return _bootstrap._gcd_import(name[level:], package, level)\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\cython\init.py", line 6, in \r\n' +
' from . import (\r\n' +
'ImportError: DLL load failed while importing error: 找不到指定的模組。\r\n',
exitCode: 1,
reason: 'Traceback (most recent call last):\r\n' +
' File "C:\Users\MT\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 192, in _run_module_as_main\r\n' +
' return _run_code(code, main_globals, None,\r\n' +
' File "C:\Users\MT\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 85, in _run_code\r\n' +
' exec(code, run_globals)\r\n' +
' File "d:\Trading\env\lib\site-packages\ipykernel_launcher.py", line 15, in \r\n' +
' from ipykernel import kernelapp as app\r\n' +
' File "d:\Trading\env\lib\site-packages\ipykernel\init.py", line 2, in \r\n' +
' from .connect import *\r\n' +
' File "d:\Trading\env\lib\site-packages\ipykernel\connect.py", line 10, in \r\n' +
' import jupyter_client\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\init.py", line 6, in \r\n' +
' from .asynchronous import AsyncKernelClient # noqa\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\asynchronous\init.py", line 1, in \r\n' +
' from .client import AsyncKernelClient # noqa\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\asynchronous\client.py", line 6, in \r\n' +
' from jupyter_client.channels import HBChannel\r\n' +
' File "d:\Trading\env\lib\site-packages\jupyter_client\channels.py", line 12, in \r\n' +
' import zmq.asyncio\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\init.py", line 125, in \r\n' +
' from zmq import backend\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\init.py", line 32, in \r\n' +
' raise original_error from None\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\init.py", line 27, in \r\n' +
' _ns = select_backend(first)\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\select.py", line 32, in select_backend\r\n' +
' mod = import_module(name)\r\n' +
' File "C:\Users\MT\AppData\Local\Programs\Python\Python38\lib\importlib\init.py", line 127, in import_module\r\n' +
' return _bootstrap._gcd_import(name[level:], package, level)\r\n' +
' File "d:\Trading\env\lib\site-packages\zmq\backend\cython\init.py", line 6, in \r\n' +
' from . import (\r\n' +
'ImportError: DLL load failed while importing error: 找不到指定的模組。\r\n'
}

UserWarning: Module "zipline.assets" not found; mutltipliers will not be applied to position notionals.

(env) D:\Trading>python strategy_research.py
D:\Trading\env\lib\site-packages\pyfolio\pos.py:26: UserWarning: Module "zipline.assets" not found; mutltipliers will not be applied to position notionals.
warnings.warn(
<IPython.core.display.HTML object>
Traceback (most recent call last):
File "D:\Trading\strategy_research.py", line 9, in
pf.create_returns_tear_sheet(return_ser['Close'].pct_change())
File "D:\Trading\env\lib\site-packages\pyfolio\plotting.py", line 52, in call_w_context
return func(*args, **kwargs)
File "D:\Trading\env\lib\site-packages\pyfolio\tears.py", line 504, in create_returns_tear_sheet
plotting.show_worst_drawdown_periods(returns)
File "D:\Trading\env\lib\site-packages\pyfolio\plotting.py", line 1664, in show_worst_drawdown_periods
drawdown_df = timeseries.gen_drawdown_table(returns, top=top)
File "D:\Trading\env\lib\site-packages\pyfolio\timeseries.py", line 1008, in gen_drawdown_table
df_drawdowns.loc[i, 'Valley date'] = (valley.to_pydatetime()
AttributeError: 'numpy.int64' object has no attribute 'to_pydatetime'

yahoo_news.py 無法使用

更改後恢復正常
#find尋找元素
price = soup.find("fin-streamer",attrs = {"data-pricehint":"2"})

問題請教

作者您好

我是使用spider來跑您的程式
但出現一些問題

  1. section 2.3 您提供的程式僅為
    image 之後我依照2-47頁的程式輸入,卻無法執行,是否提供您2-47/與2-48的程式參考
  2. 新聞爬蟲 如圖 我執行之後卻無法看到列印結果,能否告知問題在哪

image

謝謝

tech_macd_ma的疑問

你好,
在bt.ind.MACDHisto(period_me1=12,.......)這段程式碼中,你是如何知道 "( )" 內要放進什麼參數的?
因為我想使用其他指標,可是我從bt的官方文件中,看不懂要如何在其他指標的 ( ) 內的放相關的參數
還請你幫忙解惑一下,謝謝你!!!

btw, 在bt的KD指標他的算法是不是跟台灣的KD指標算法不太一樣?
我看Stochastic裡面有很多種類,不知道該用哪一個

關於matplotlib

您好-:
在練習backtest_research.py程式時
由於遇到書中4-50 ImportError的問題
因此卸載了原本的matplotlib
但在安裝3.2.2版本時,似乎無法順利安裝
出現下列字樣
IMPORTANT WARNING:
pkg-config is not installed.
Matplotlib may not be able to find some of its dependencies.
使得在執行程式時會出現:No module named 'matplotlib'
請問是版本相容的問題嗎?
我使用的是spyder 5.0.5

smtp.2

作者您好,我在嘗試3-83的練習時,遇到了兩個問題。1.如何會有可以輸入帳密的地方?2.key、cofing內好像過程中指令沒有完整跑完,導致資料夾沒有東西?我應該如何調整呢?
image
image
image
image
image
image
image

遇到 OSError?

作者您好~感覺是路徑讀取的問題要如何打才會是最安全的路徑讀取方式呢?
1.安裝 多個套件過程
image
2.讀取路徑
image
image

有關更多操作自動化的問題

作者您好! 剛花了一週時間看完您的書, 獲益良多. 從以前單純研究技術指標, 目測k線圖和指標的變化判斷策略的成敗, 到把所有回測用暴力演算程序化, 嘗試代入不同參數, 真的節省很多時間. 謝謝您的教學!

其實我還有一事冒昧請教, 我和朋友近來一起研究如何將整個外匯保證金日內交易的過程自動化, 包括回測, 掛單開倉, 到平倉. 當然回測資料我們是有的. 這個情況也和您示範的股票投資在策略上也很不同, 我們會再仔細構思. 但我想問的是, 回測我算是學了一個大概, 但下單方便又是另一門學問, 找到的網上教學資源確實也不多. 於是我就想知道python 會否存在一些關於即時檢測當前市場是否符合買賣策略, 並輸出買賣操作連接到證券商下單API(或者MT4)的套件, 不知道您有沒有這方面的經驗, 或者知道哪裏可以了解更多? 謝謝!

mpl_finance過時?

每次執行K線圖,
皆會出現:

WARNING: mpl_finance is deprecated:

Please use `mplfinance` instead (no hyphen, no underscore).

To install: `pip install --upgrade mplfinance`

For more information, see: https://pypi.org/project/mplfinance/

=================================================================

__warnings.warn('\n\n ================================================================='+
但改用mplfinance則會報錯,
無candlestick2_ochl方法。

backtrader問題

不好意思打擾了
照著書本複製官方文件程式碼逐步修改
至P4-46執行時發生錯誤
麻煩您指導了
謝謝

Traceback (most recent call last):
File "D:\Trading\test.py", line 141, in
cerebro.run()
File "D:\Trading\env\lib\site-packages\backtrader\cerebro.py", line 1127, in run
runstrat = self.runstrategies(iterstrat)
File "D:\Trading\env\lib\site-packages\backtrader\cerebro.py", line 1210, in runstrategies
data._start()
File "D:\Trading\env\lib\site-packages\backtrader\feed.py", line 203, in _start
self.start()
File "D:\Trading\env\lib\site-packages\backtrader\feeds\yahoo.py", line 355, in start
super(YahooFinanceData, self).start()
File "D:\Trading\env\lib\site-packages\backtrader\feeds\yahoo.py", line 94, in start
super(YahooFinanceCSVData, self).start()
File "D:\Trading\env\lib\site-packages\backtrader\feed.py", line 674, in start
self.f = io.open(self.p.dataname, 'r')
FileNotFoundError: [Errno 2] No such file or directory: '2330.TW'

程式碼如下
from future import (absolute_import, division,
print_function, unicode_literals)

import datetime # For datetime objects
import os.path # To manage paths
import sys # To find out the script name (in argv[0])

Import the backtrader platform

import backtrader as bt

Create a Stratey

class TestStrategy(bt.Strategy):
params = (
('maperiod', 15),
)

def log(self, txt, dt=None):
    ''' Logging function fot this strategy'''
    dt = dt or self.datas[0].datetime.date(0)
    print('%s, %s' % (dt.isoformat(), txt))

def __init__(self):
    # Keep a reference to the "close" line in the data[0] dataseries
    self.dataclose = self.datas[0].close

    # To keep track of pending orders and buy price/commission
    self.order = None
    self.buyprice = None
    self.buycomm = None

    # Add a MovingAverageSimple indicator
    self.sma = bt.indicators.SimpleMovingAverage(
        self.datas[0], period=self.params.maperiod)

def notify_order(self, order):
    if order.status in [order.Submitted, order.Accepted]:
        # Buy/Sell order submitted/accepted to/by broker - Nothing to do
        return

    # Check if an order has been completed
    # Attention: broker could reject order if not enough cash
    if order.status in [order.Completed]:
        if order.isbuy():
            self.log(
                'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                (order.executed.price,
                 order.executed.value,
                 order.executed.comm))

            self.buyprice = order.executed.price
            self.buycomm = order.executed.comm
        else:  # Sell
            self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                     (order.executed.price,
                      order.executed.value,
                      order.executed.comm))

        self.bar_executed = len(self)

    elif order.status in [order.Canceled, order.Margin, order.Rejected]:
        self.log('Order Canceled/Margin/Rejected')

    self.order = None

def notify_trade(self, trade):
    if not trade.isclosed:
        return

    self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
             (trade.pnl, trade.pnlcomm))

def next(self):
    # Simply log the closing price of the series from the reference
    self.log('Close, %.2f' % self.dataclose[0])

    # Check if an order is pending ... if yes, we cannot send a 2nd one
    if self.order:
        return

    # Check if we are in the market
    if not self.position:

        # Not yet ... we MIGHT BUY if ...
        if self.dataclose[0] > self.sma[0]:

            # BUY, BUY, BUY!!! (with all possible default parameters)
            self.log('BUY CREATE, %.2f' % self.dataclose[0])

            # Keep track of the created order to avoid a 2nd order
            self.order = self.buy()

    else:

        if self.dataclose[0] < self.sma[0]:
            # SELL, SELL, SELL!!! (with all possible default parameters)
            self.log('SELL CREATE, %.2f' % self.dataclose[0])

            # Keep track of the created order to avoid a 2nd order
            self.order = self.sell()

if name == 'main':
# Create a cerebro entity
cerebro = bt.Cerebro()

# Add a strategy
cerebro.addstrategy(TestStrategy)

# Datas are in a subfolder of the samples. Need to find where the script is
# because it could have been called from anywhere
# modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
# datapath = os.path.join(modpath, '../../datas/orcl-1995-2014.txt')

# Create a Data Feed
data = bt.feeds.YahooFinanceData(
    dataname='2330.TW',
    # Do not pass values before this date
    fromdate=datetime.datetime(2014, 1, 1),
    # Do not pass values before this date
    todate=datetime.datetime(2020, 12, 31),
    # Do not pass values after this date
    reverse=False)

# Add the Data Feed to Cerebro
cerebro.adddata(data)

# Set our desired cash start
cerebro.broker.setcash(1000000.0)

# Add a FixedSize sizer according to the stake
cerebro.addsizer(bt.sizers.FixedSize, stake=1000)

# Set the commission
cerebro.broker.setcommission(commission=0.0015)

# Print out the starting conditions
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

# Run over everything
cerebro.run()

cerebro.plot()

# Print out the final result
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

關於AES_Encryption等第三章問題

想請教作者出現在第三章的一些問題
1.在smtp的章節中有需要一個AES_Encryption的模組,我有照著您的說明放到sys.path.append那個目錄裡,但每次依然會出現找不到模組的錯誤,請問該如何解決? 謝謝回覆
擷取
2

2.在smtp的章節中,一開始會先遇到AES_Encryption的模組的問題,即使我先註解掉AES_Encryption那一行,也會馬上再遇到msg的問題,想請教該如何處理? 謝謝
2222

3.在1_buy_follow_corp這個章節裡,我們會匯入utility_f這個之前做的模組,但是檢驗結果時卻會一直出現找不到模組的錯誤,請問該如何解決? 謝謝
擷取

4.每次在填寫路徑時都會出現unicode error,上網查了一下好像只要在路徑前面加上r就能改善,但是我看書本都沒加上r,想請教作者這部分有可能是什麼原因所導致?
123132

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.