---
title: 'R 語言學習心得-股價篇'
disqus: hackmd
---
R 語言學習心得
股價篇
===
![downloads](https://img.shields.io/badge/download-R-brightgreen)
![grade](https://img.shields.io/badge/Grade-新手-brightgreen)
![chat](https://img.shields.io/discord/:serverId.svg)
---
## 股票分析工具 - quantmod
If you are a beginner to this, start here!
1. Download quantmod packages
```r
install.packages('quantmod')
```
2. Open your editor ! (I do all the code in R)
3. Choose a comfortable chair:kissing_heart:
4. Start learning!
----
基礎知識
---
1. 股票來源 :
yahoo 股票網站(default)
2. 台股要加後綴字:
上市公司 : .TW // 上櫃公司 : .TWO
3. 其餘股市直接搜尋股票代碼 :
EX. [蘋果Apple.Inc (APPL)](https://tw.stock.yahoo.com/us/q?s=AAPL)
---
抓取資料
---
```r
loadSymbols('Apple',auto.assign=FALSE,from="2019-01-01",to="2020-04-01")
```
1. auto.assign一定要是false
2. 時間不指定的話就會從2007年開始抓
----
lineChart
![](https://i.imgur.com/FAFkz2I.jpg)
----
lineChart
---
```r
lineChart(Apple,line.type = 'h', theme = 'white', TA = NULL)
```
![](https://i.imgur.com/NZTc1xV.jpg)
[more TA](https://www.quantmod.com/documentation/TA.html)
----
barChart
---
```r
barChart(Apple,line.type = 'hlc', theme = 'black',TA=NULL)
```
1. 把 TA=NULL 拿掉就可以看到VOL(成交量)
2. theme = 'white'也可以試試看
----
barChart
---
![](https://i.imgur.com/zoPbFa7.png)
----
candleChart
---
1. 有關K線理論的圖(我也是不太懂,可以去查看看)
2. 重點是要設置subset
3. 看要統計哪個時間區間內的值
4. 寫法有3種
```r
subset = '2020'
subset = 'last 2 month'
subset = '2019-12-25::2020-3-25'
```
----
candleChart
---
![](https://i.imgur.com/HnUJD7U.png)
----
來試著加入TA吧~
---
1. MACD = 指數平滑異同移動平均線
2. ADX = 平均趨向指標
3. 圖片有點切到 :crying_cat_face:
```r
candleChart(Apple, TA=c(addMACD(),addVo()), subset = 'last 3 month')
candleChart(Apple, TA=c(addMACD(),addADX()), subset = 'last 3 month')
```
----
![](https://i.imgur.com/OSrPAdQ.jpg)
---
來看看數字吧!
---
1. 把SMA的數據找出來
2. 記得Close的C是大寫的
3. 也把CCI的數據找出來
```r
ma5 <- SMA(Apple$"AAPL.Close",n=5) #n = 幾天一期 常用的有5天或20天
cc20 <- CCI(Apple$"AAPL.Close",n=20)
```
----
找找看5日均線>20日均線
---
1. 設立ma5 & ma20
2. 用 ">"輕鬆找到黃金交叉
3. 也可以反過來用ma5 < ma20(死亡交叉)
```r
ma5 <- SMA(Apple$"AAPL.Close",n=5)
ma20 <- SMA(Apple$"AAPL.Close",n=20)
ma5>ma20 #回傳每一天的True /False
ma5[ma5>ma20] #回傳當時股價
index(ma5[ma5>ma20]) #回傳日期
```
----
儲存plot
---
1. 先建立照片名稱
2. 畫出你的plot
3. dev.off()...把控制權還給主控台
4. 開始-搜尋剛剛的照片名稱 :smiley:
```r
jpeg(file="filename.jpeg")
candleChart(Apple, TA=c(addMACD(),addADX()), subset = 'last 3 month')
dev.off() #把控制權還給主控台
```
---
Showtime
---
![](https://i.imgur.com/hRoqKGx.png)
the code is in tutorial R file
----
## More tutorial / note
1. [my coding-blog](fatcatcat-lab.blogspot.com)
2. [my movie-blog](fatcatcat-movie.blogspot.com)
###### tags: `R` `beginner` `cat` `tutorial`