Thursday, November 29, 2018

google tends 反指標可行性? FIX_DATA (二)

資料量可能會呈現全部趨向於100%的狀況


所以我打算先取得該年度區間所有的百分比再去*上每日百分比,這樣數據的呈現應該才是最準確的數字。
先取得2004至今的趨勢

程式碼


def get_historical_interest2(self, keywords, year_start=2018, month_start=1, day_start=1, hour_start=0, year_end=2018, month_end=2, day_end=1, hour_end= 0, cat=0, geo='', gprop='', sleep=0):
"""Gets historical hourly data for interest by chunking requests to 1 week at a time (which is what Google allows)"""
# construct datetime obejcts - raises ValueError if invalid parameters
#start_date = datetime(year_start, month_start, day_start, hour_start)
#end_date = datetime(year_end, month_end, day_end, hour_end)
# the timeframe has to be in 1 week intervals or Google will reject it
df = pd.DataFrame()
tf = "all"
try:
self.build_payload(keywords,cat, tf, geo, gprop)
week_df = self.interest_over_time()
df = df.append(week_df)
print (week_df)
except Exception as e:
print(e)
pass
return df
view raw request.py hosted with ❤ by GitHub
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.stats as scs
from matplotlib import animation
from sklearn import preprocessing
from pytrends.request import TrendReq
# Login to Google. Only need to run this once, the rest of requests will use the same session.
pytrend = TrendReq()
tk = pytrend.get_historical_interest2(['stock'], year_start=2018, month_start=8, day_start=1, year_end=2018, month_end=8, day_end=1, cat=0, geo='', gprop='', sleep=0)
#tk.drop(['isPartial'], axis=1)
#del tk['isPartial']
print (tk.head())
plt.figure(figsize=(20,8))
fig, ax = plt.subplots()
#preprocessing.scale(tk['stock'])
ax.plot(tk['stock'])
plt.show()
運行結果



資料量問題


一開始我還以為要對資料做正規化,思考一下應該不是這問題,這邊會面臨到一直要數據被伺服器阻擋的問題(我先備份了數據)

這是取得每月得數據

這是我們之前取得每日的數據

然後我們要對數據加工一下
這才是正確的等比例數據
來看一下程式碼

程式碼

下載我我是資料~data.csv


import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
import scipy.stats as scs
from matplotlib import animation
from sklearn import preprocessing
from pytrends.request import TrendReq
import datetime
date_time_str = '2018-06-29'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d')
df = pd.read_csv('googletrend_stock_data.csv', index_col='date', parse_dates=['date'])
price = df.squeeze()
price.head()
df = pd.read_csv('googletrend_stock_data2.csv', index_col='date', parse_dates=['date'])
all_price = df.squeeze()
all_price.head()
# print('Date:',date_time_str[5:7])
#Login to Google. Only need to run this once, the rest of requests will use the same session.
# pytrend = TrendReq()
# tk = pytrend.get_historical_interest2(['stock'], year_start=2004, month_start=1, day_start=1, year_end=2018, month_end=8, day_end=1, cat=0, geo='', gprop='', sleep=0)
# print(price)
# #tk.drop(['isPartial'], axis=1)
# #del tk['isPartial']
# print (tk.head())
# type(price)
def get_months( test):
value = ""
for i in range (0,len(all_price),1):
if(test == str(all_price.index[i])[:7]+"-01 00:00:00"):
value = all_price[str(all_price.index[i])[:7]+"-01 00:00:00"]
return value
plt.figure(figsize=(16,8))
fig, ax = plt.subplots()
#preprocessing.scale(tk['stock'])
ax.plot(price)
plt.show()
# print( str(price.index[0])[:7] )
# print (price [price.index[0]])
s = pd.Series(price)
fuck = []
print (price.index)
for x in price.index:
print (x)
get_month = get_months(str(x)[:7]+"-01 00:00:00" )
if(type(price[x]) == type(pd.Series(1))):
fuck.append( [str(x),(np.float64(price[x][0])*(int(get_month)/100))])
else:
fuck.append( ([str(x),(np.float64(price[x])*(int(get_month)/100))]))
#print (get_month/100)
#print (price[x]*(get_month/100))
#print (get_months(str(price.index[str(x)])[:7]+"-01 00:00:00"))
df2 = pd.DataFrame(fuck, columns = ['date', 'price'] )
df2['date'] = pd.to_datetime(df2['date'])
price2 = df2.set_index('date')
plt.figure(figsize=(16,8))
fig, ax = plt.subplots()
#preprocessing.scale(tk['stock'])
ax.plot(price2)
plt.gcf().autofmt_xdate()
plt.show()

Sunday, November 18, 2018

風險分析與蒙特卡羅模擬股市路徑


又多了一項分析武器老早就想跑這張圖了,終於有空來跑一下那麼就開始。

蒙特卡羅方法


第一次人们开始研究蒙特卡罗方法是要评估π。

通过概率论,蒙特卡罗可以用作数值积分法。 例如,




其中p(x)是U(0;1)的概率密度函数。


实践中,蒙特卡罗广泛应用于统计力学,量子物理学,金融衍生产品定价和风险管理。


##一个MC示例:期权定价


蒙特卡洛通常用于评估期权价格。


我们不会涉及任何理论推论。 对于欧式看涨期权,其价格可以通过公式给出




其中S为当前基本股票价格,σ为股票波动率,r为利率,T为期权期权,K为行使价,Φ为标准正态随机变量。


股票布朗運動


布朗运动、伊藤引理、BS 公式

所以到底有沒有可能股市是基於布朗運動呢,上方網址點入,
那我假設是有一定規律性的


本周我們介紹股市波動最基本的特性: 對數常態分配(Log-normal Distribution)。有接觸過財務工程的投資朋友可能都聽過這個名詞,因為...

教科書說,股市的漲跌幅,呈現對數常態分配。

這個觀察是奧斯本(Matthew Maury Osborne,1916~2003)發現的。然而,這個現象並不那麼直觀! 我們介紹如下:

這邊也符合對數常態分配,在99%的信心水平下,統二的股票一年後的價格不會低於64塊ㄏㄏ,風險值有35%,掉那麼快也倒了,或許是我用錯了?參考那網站是好像是用正規常態,我是用對數或許有些關聯。
這是模擬五萬次蒙特卡羅(好像沒什麼意義xd。

程式碼


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.stats as scs
S0 = 100
r = 0.05
sigma = 0.25
T = 1.0
I = 50000
M = 50
dt = T/M
S = np.zeros((M + 1,I))
S[0] = S0
print (S[0])
for t in range(1,M+1):
S[t] = S[t-1]*np.exp((r-0.5*sigma**2)*dt+sigma*np.sqrt(dt)*np.random.standard_normal(I))
print (t)
print (M+1)
plt.figure(figsize=(16,8))
#define q as the 1% empirical qunatile, this basically means that 99% of the values should fall between here
q = np.percentile(S, 1)
# Plot a line at the 1% quantile result
plt.axvline(x=q, linewidth=4, color='r')
# Starting Price
plt.figtext(0.6, 0.8, s="Start price: $%.2f" %S0 )
# Mean ending price
plt.figtext(0.6, 0.7, "Mean final price: $%.2f" % S.mean())
# Variance of the price (within 99% confidence interval)
plt.figtext(0.6, 0.6, "VaR(0.99): $%.2f" % (S0 - q,))
# Display 1% quantile
plt.figtext(0.15, 0.6, "q(0.99): $%.2f" % q)
plt.hist(S[-1],bins = 50)
plt.xlabel('price')
plt.ylabel('frequency')
plt.show()
plt.figure(figsize=(16,8))
plt.plot(S[:,:],lw = 1.5)
plt.xlabel('time')
plt.ylabel('price')
plt.show()
view raw MonteCarlo.py hosted with ❤ by GitHub

增加動畫


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.stats as scs
from matplotlib import animation
S0 = 100
r = 0.05
sigma = 0.25
T = 1.0
I = 10
M = 50
dt = T/M
S = np.zeros((M + 1,I))
S[0] = S0
print (S[0])
for t in range(1,M+1):
S[t] = S[t-1]*np.exp((r-0.5*sigma**2)*dt+sigma*np.sqrt(dt)*np.random.standard_normal(I))
print (t)
print (M+1)
plt.figure(figsize=(16,8))
#define q as the 1% empirical qunatile, this basically means that 99% of the values should fall between here
q = np.percentile(S, 1)
# Plot a line at the 1% quantile result
plt.axvline(x=q, linewidth=4, color='r')
# Starting Price
plt.figtext(0.6, 0.8, s="Start price: $%.2f" %S0 )
# Mean ending price
plt.figtext(0.6, 0.7, "Mean final price: $%.2f" % S.mean())
# Variance of the price (within 99% confidence interval)
plt.figtext(0.6, 0.6, "VaR(0.99): $%.2f" % (S0 - q,))
# Display 1% quantile
plt.figtext(0.15, 0.6, "q(0.99): $%.2f" % q)
plt.hist(S[-1],bins = 50)
plt.xlabel('price')
plt.ylabel('frequency')
#plt.show()
plt.figure(figsize=(16,8))
fig, ax = plt.subplots()
global test
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
#graph_data = open('example.txt','r').read()
#lines = graph_data.split('\n')
xs = []
ys = []
for line in range (0,I ,1):
xs.append(line)
test =0
def animate(i):
global test
if(test < I):
#ax1.plot(xs[:test], ys[ :test])
#ax1.clear()
for y in range (0,M ,1):
ax1.plot(S[:test,:])
test= test +1
ani = animation.FuncAnimation(fig, animate, frames=100, interval=20,
blit=False)
#plt.show()
ani.save('/animation.gif', writer='imagemagick', fps=60)
view raw MonteCarlo2.py hosted with ❤ by GitHub

google tends 反指標可行性?(一)

反指標可行性?


如何用Google Trends找到「逃命訊號」?打一個關鍵字,就找出股價高點的方法 

從線圖可以看到,在Google上搜尋「股票」的人,在2007年3月開始異常增加,並在6月達到高峰,在此之後搜尋程度都一直相較過去維持在高檔,股市則於2007年10月後開始下跌。

「你覺得,什麼人會在Google上搜尋『股票』這種無關緊要的關鍵字?」我問,
「只有剛入門的散戶有可能吧...」他已經懂了,並用詭譎的笑容看著這張圖。

那如何取得資料到python?


pytrends 裝好後,我們切換到程式碼面,我們要一次爬一年,我遇到了一個問題怎麼爬著爬著到2014年資料都是空的,
奇怪有資料阿,切去看程式碼面
觀察一下網址

https://trends.google.com/trends/explore?date=2004-01-01%202004-01-02&q=stock

得到結論,在2015年前,都只有儲存當日資料,到2015開始可能才有每小時搜尋資料紀錄。
那麼接下來就可以爬2004年到2018年資料。
驗證成功,開爬

程式碼


from pytrends.request import TrendReq
# Login to Google. Only need to run this once, the rest of requests will use the same session.
pytrend = TrendReq()
tk = pytrend.get_historical_interest(['stock'], year_start=2014, month_start=1, day_start=1, year_end=2014, month_end=10, day_end=1, cat=0, geo='', gprop='', sleep=0)
print (tk.head())
view raw stockpytrend.py hosted with ❤ by GitHub


結論



還蠻方便的可以快速地取得搜尋熱度,在github還有更多使用方法,希望早日可以找尋其中較穩的組合。
https://github.com/GeneralMills/pytrends

fbprophet 預測家模型 股票?

超簡單用Python預測股價

如圖,我也不知道我在寫什麼東西,就吸收整合,大不分的內容還是由比較正規的文章所引用,也有附上連結,有錯別來找我诶,我想入門的小白在搭建環境上會很雷,所以我通常會附上搭建環境的過程,以便大家可以快速run起來~

預測股票?


之前有寫過用lstm預測股票的東西,當然股票這種東西,不是長就是跌,大牛最多也是逼近50%50%不是漲就是碟嗎。不過放到中長期就不一樣了,如果再加入google tend關鍵字分析再來預測股票是否有其關聯性呢???,恩以後再來說先來做這實作先~

剛好聽同學說它們有參加一個比賽,然後呢,它們的主要工作是需要預測下一個禮拜股市的精準度,就我這旁門走道來看,lstm或者用這預言家模型,應該都可以達到不錯的效果,
假設我們要預測一個麗拜的資料需要大概那些能用的工具呢,第一步我們要把我們的資料禿通通時間序列化,再來就是套國外solution(公司大牛)說的,哈哈在接下來我們來看看之前兩個月沒動的程式碼吧。
首先呢我們打開我們的老程式碼跑一下範例。

速度迷思


我覺得痾應該速度再跑回測的時候有差拉,不過在觀察其規律性,要求速度的話在急速下單邏輯判斷一定要超快,像我之前寫的一個比特幣交易軟體,取得買賣單量瞬間下單,最後還是被官網鎖了,只能說莊家最大,然後喔一定會找到適合你的組合最重要,程式跑回測,不一定是找到聖杯,除非你的策略寫的超棒,無破綻,去跑當沖,每秒幾十萬上下,2018二月全球股災~黑天鵝是機器人? 遇到一次就gg囉,不過有人贏就有人輸,我是年輕人還是先在旁邊觀察一陣子好了。
「連鎖破壞」的圖片搜尋結果

搭建環境與安裝


# bash $ pip install fbprophet

慘慘慘 轉用anaconda裝

conda update -c conda-forge conda
conda update -n base conda
conda config --add pinned_packages defaults::conda
conda install  -c conda-forge fbprophet -y
conda install -c masdeseiscaracteres ta-lib


複製stocker


不想下一堆指令的話,可以偷懶學我把關聯py丟到目錄下



nice解決環境好利器,搜尋了快一小時還以為當機,惱人的環境設定,中途還跑去裝docker,結果windows hyper 要專業版才有QQ 我畚箕安裝的python 資源包,一堆元件衝突總而言之,安裝好後呢(anaconda裝了很多次結果降版本Anaconda3-5.2.0-Windows-x86_64.exe 這就大概裝完囉。

程式碼


小改
import pandas as pd
# 去除煩人的 warrning
import warnings
from stocker import Stocker
warnings.filterwarnings('ignore')
# 讀入series
df = pd.read_csv('price.csv', index_col='date', parse_dates=['date'])
price = df.squeeze()
price.head()
tsmc = Stocker(price)
tsmc.evaluate_prediction()
tsmc.changepoint_prior_analysis(changepoint_priors=[0.001, 0.05, 0.1, 0.2])
tsmc.predict_future(days=100)
view raw stockpro.py hosted with ❤ by GitHub

運行畫面

其實,用來預測一些事情也蠻好玩的。


國外github
預言家github


幻想


目前大概再搭建玩平台後,現在目前都是寫小策略,那麼嘗試投資組合使用基因演算法(?),
簡單成效好、不簡單成效好、簡單成效不好、不簡單成效不好。(取自量化實驗室片段)
就上述這幾種情況,大家應該都會偏向於第一種方法因為就算是失敗的話,也很好找出原因並且除錯,大概在跑兩個範例,google tend對金融性產品 是否也有其關聯,在來就是一些小策略的紀錄。
沒意外後其大概都是

  1. 提出組合
  2. 回測
  3. 修正

回測 - > 修正 - > 回測 - > 修正 - > 回測 - > 修正 - > 回測 - > 修正 .......

public int debug()
{
if(debug == 1)
debug(1);
return debug(1);
}目前活在這種地獄,重構,非同步,deubg無限循環,體驗新手村的感覺,什麼時候可以用嘴巴寫程式。。。。。。。

Thursday, November 8, 2018

弔詭

想留也留不住的東西,只能隨他去了,如果這樣能夠高興的話!!
找到以前畫的中二東西,RECORD 換個興趣應該也不錯?

汗...終於完成員工訓練了zzz雖然是假資料,當然還是要做一下假處理