Model.pb 小註解

這個檔案是用來放 model 的 protocol buffer, 所以叫做 pb. 當我們對 input raw data 做了一些前處理, 然後才去 train model. 那使用這個 model 的天命任意人, 怎麼知道要用那些 pre-processing 的手法來處理他的真實資料呢? 沒錯! 就是去看這個 model.bp.

Model.bp 不只是記錄 metadata 這麼簡單, 它只是三個主要功能之一. 這三個功能分別是:

  1. Model Graph: 把 model 的 graph 記下來. 這個 graph 不是個圖檔, 是資料結構裡面的 graph, 它定義了 model 的資料流向.
  2. Metadata: 主要是 input 和 output 的 tensor information. 不論是做前處理或是後處理都會參考到.
  3. Portability: Model 作者最初可能是用 Tensorflow, Tensorflow Lite, 或者Tensorflow.JS 開發, 使用者 deploy 的 platform 不同於作者時, 也可以參考這個檔案獲得相容性資訊.

講到前處理, 另一個 keyword 是 tf.Transform. 這個 library 專門做 Tensorflow 的前處理用. Graph 也是它產生的. tf.Transform 整合了 Apache Beam, (Google) cloud Dataflow, 和 TensorFlow 兩種不同的處理方式 [1][2].

請留意 tf.Transform 是在 pre-process 階段做 feature engineering, 而 Apache Beam 和 Cloud Dataflow 是在 feature creation 階段. 所以後者提供 API 給 tf.Transform 使用. 第三個可以執行 feture engineering 的階段是 train model. 在 [1] 裡面寫了 1,2,3 三個圈圈, 順序和我提到的相反, 但是那沒關係, 只是做個區隔.

附帶一提 Beam 可以用更多的 programming language, 像是 Java, Python, 和 SQL. Tensorflow 基本上多了 C++, Javascript, 少了 SQL. 總之學 Python 就對了.

[REF]

  1. https://ithelp.ithome.com.tw/articles/10227075
  2. https://www.tensorflow.org/tfx/transform/get_started
  3. https://towardsdatascience.com/hands-on-apache-beam-building-data-pipelines-in-python-6548898b66a5

Feature Engineering 備忘小筆記

對 AI 有興趣的我, 其實比較喜歡研究 model 的原理, 對於資料的處理沒興趣. 不過偶爾要用到某個語法, 卻又記不起來的話, 還是會有點傷腦筋! 所以筆記一下加深印象. 以後也好查詢.

  1. dataframe 轉 dataset
def df_to_dataset(dataframe):
    dataframe = dataframe.copy()
    
    labels = dataframe.pop('your target')
    ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))
                            
    return ds

2. Categorical 轉 Numeral (one-hot)

from tensorflow import feature_column as fc

# invest_df is predefined dataframe

A = ['stock','bond','ETF']
B = []

for C in A:
    D = invest_df[C].unique()
    E = fc.categorical_column_with_vocabulary_list(C, D)
    F = fc.indicator_column(E)
    B.append(F)

3. Bucketized 轉 numerical

G = fc.numeric_column("net_asset")
​
# Bucketized cols
H = fc.bucketized_column(G, boundaries=[10, 20, 30, 40, 50, 60, 80, 100]) # in million USD
B.append(H)

4. Feature Cross (Bucketized + Categorical)

I = invest_df['FATFIRE_proximity'].unique()
J = fc.categorical_column_with_vocabulary_list('FATFIRE_proximity',I)
​
crossed_feature = fc.crossed_column([H, I],hash_bucket_size=1000)
crossed_feature = fc.indicator_column(crossed_feature)
B.append(crossed_feature)

5. 實際運用

# input_dim = 上述的 feature 個數, 此時 = 8
# 假設下一層是 12 nodes.
# 8 x 12 是 fully connected.

feature_layer = tf.keras.layers.DenseFeatures(B, dtype='float64')
​
model = tf.keras.Sequential([
  feature_layer,
  layers.Dense(12, input_dim=8, activation='relu'),
  layers.Dense(8, activation='relu'),
  layers.Dense(1, activation='linear',  name='your target')
])

6. 產生新的 Bucketetized feature 做成 Feature Cross


    M = np.linspace(0, 1, nbuckets).tolist()
    N = np.linspace(0, 1, nbuckets).tolist()

    OP = fc.bucketized_column(B['OPEN_PRICE'], M)
    CP = fc.bucketized_column(B['CLOSE_PRICE'], M)
    OV = fc.bucketized_column(B['OPEN_VOL'], N)
    CV = fc.bucketized_column(B['CLOSE_VOL'], N)

    OO = fc.crossed_column([OP, OV], nbuckets * nbuckets)
    CC = fc.crossed_column([CP, CV], nbuckets * nbuckets)

    new_bucket_cross_feature = fc.crossed_column([OO, CC], nbuckets ** 4)

7. 畫出酷炫流程圖並存檔

tf.keras.utils.plot_model(model, 'model.png', show_shapes=False, rankdir='LR') # or 'TB'

股市震盪小筆記

自美股在 7/23 (二) 開始走下坡之後, 台股先是在 8/2 (五) 大跌破千點之後, 8/5 (一) 又創記錄大跌 1807.21 點. 隨後美股看似有點回神 (其實沒有), 台股就在 8/7 (三) 創下最大的反彈記錄. 真不愧是奧運期間, 破紀錄變成日常.

看著預期中的美股下跌發生, 我準備低接美股. 至於錢從何來呢? 首先就是停泊資金的 SGOV 可以賣掉, 然後把表現怪怪的波克夏也賣掉, 這樣就有銀彈可以買入了. 為何說老巴怪呢? 我可以接受他買 Apple, 但不能接受他又迅速地把 Apple 賣掉. 難道蘋果也有地緣政治風險? 我投資老巴是因為他能判斷投資標的長期潛在價值. 如果波克夏現在只是擅長財務操作, 那跟投資對沖基金也沒什麼區別是吧. 老巴說不懂的東西不要買, 我現在不懂了, 應該要賣出才符合當年老巴的精神.

SGOV 無論什麼時候賣出都會是 100.XX 元, 非常保值可以輕鬆出脫. BRK.B 在這波股災中, 相對跌得很少, 大概掉 5% 而已, 不像 QQQ, SPY 都跌掉 15%. 大家都稱讚老黃老巴眼明手快落跑成功! 既然它掉價少, 策略又引起我的質疑, 正好可以賣掉換子彈. 昨天那部分賣在 434. 本來想賣 433 就好, 但是我會聯想到跟 PM 開會的 433R. 想想還是多賣 1 塊好了. 結果幸運分 4 筆陸續成交. 這樣一來, 陪伴我多年的波克夏也入祀忠烈祠了~~~

接下來要怎麼買呢? 這個月我開啟了定期定額的模式. 雖然可以按照跌 10% 買 10%, 跌 20% 買 20%, … 的這個原則買進. 但是我手中究竟有多少錢是變動很大的. 比方說賣 BRK.B 之前和之後就差很多. 所以我用手續費 0.1 USD 等級的定期定額, 一部分買 QQQ, 一部分買 PFF. QQQ 這單很幸運地買到 425.28, 因為那天開盤就暴跌.

買 QQQ 是我的投資重點, 基本上不會改變. 最近 Nvidia, Intel 出包, 反正就算這兩家沒事, 別家早晚也會出事. 整體而言, AI 浪潮勢不可擋, 我長期看好一籃子科技股. 只要整體會成長就好! 至於 PFF 股價雖然不會成長, 它卻能提供每個月生活費自動進帳的心理支撐. 這跟我們找工作一樣, 年薪再高, 月薪還是要有一定的水準才安心. 這算是個人偏執的心態吧.

年中投資回顧的時候, 我說希望到年底能持平就好. 不過轉眼已經跌掉了 6~8%. 如果不是民生用品和息股增值股 (KO, SHEL, VIG, NOBL) 在幫我分散壓力, 消失的就不是一台車而是一棟房了. 雖然重壓賺比較多, 但分散風險對心理還是比較健康的. 希望增持的 QQQ 能趕快回到原點, 這樣我就會創新高了.

2024 年 Q2 投資回顧

2024 年中美股市都在高點, 雖然看起來有站不穩, 但是今年截至目前為止, 要虧錢都很難. 預期大家都是賺錢的, 恭喜恭喜!

在這一季當中, 基本上我沒有改變投資組合. Firstrade 繼續 DRIP (股息再投入). 上一次嘗試選擇權失敗, 這次就不試了. 唯一新奇的作為是 Firtrade 廣告可以定額買零股. 我看看戶頭還有 11.08 左右. 於是就想要玩玩看.

6/10 用它買了0.09233 股 Nvidia. 原先我是用市價買, 想說 11.08 元虧光也不怕! 但是 Firstrade 跳出警告說 “你沒資格啊, 你沒資格"[1]. 我只好改下限價 120 元, 立刻就買到了, 看起來不但能買, 還可以 DRIP. 不過 11.08 要怎麼樣才能可以利滾利就財富自由了呢? 想想也不太可能, 所以隔 3 天就賣了. 改買 QQQ 0.02579 股, 免得我圓餅圖畫不出來.

圓餅圖在此. 還是一樣的投資組合, 比去年年底成長 22.2%, 半年獲利超過去年加前年的獲利. 那一整年豈不是….哇哈哈哈…… 嗯, 沒人知道未來會發生什麼事! 我從 Q1 居高思危到現在, 真的是有錢也不敢投資. 於是我把公司發的獎金都拿去繳稅了, 這樣等到股市跌下來, 我至少可以定期定額往上買. 現在就定期定額將會是往下買的機會比較大吧? 總之, 沒錢就不會胡思亂想了.

公司同事法總最喜歡問我哪一支最賺錢? 如果比漲幅一定是 0050 大勝! 它從去年年底 135.25 漲到 186.6, 漲幅是 38%. QQQ 從 409.52 漲到 479.11 只有 17%. 而我原本 1/3 是 QQQ, 1/12 是 0050, 比例就差了 4 倍左右(編按,有更正). 加成效果後終究是 QQQ 惠我更多. 要是沒有台灣價值的話, 今年上半年也不會這麼好!

未來怎麼走呢? 賣掉美股就可能要繳海外所得稅, 即使賣也不能賣太多. 但是少量賣又沒有換股的效果. 尤其是不知道可以換到哪裡去? 所以我考慮的就是維持 buy and hold. 近期都不做大筆投資, 台灣複委託配出來的台幣, 就定期定額再投入 PFF – 這是我殖利率最高的一檔. 雖然投入 QQQ 長期絕對比較賺, but 短期真不好說. 至於複委託配出來的美金就定存, 日幣….跌到新低不可能再拿去換別的幣別, 真的是只能湊整數再投入, 用股市成長來彌補匯兌損失. 大致上就這樣規劃, 看天公能否疼惜一下憨人, 下半年持平就好. 感恩!

[REF]

  1. 以我的理解。Firstrade 的獲利管道之一是把 order 賣給高頻交易公司,如果是限價單,高頻交易公司可以自己配對買賣單賺差價。但 11.08 元的市價單他們程式可能不好 sorting. 還要保證成交, 又讓客戶滿意成交價,所以乾脆不接單吧。

用 Multi-LLM 解釋投資風險

Coursera 有一門新的課 [1], 由該公司老闆 Andrew 介紹 CrewAI 來講課. 主要是講多個 LLM 怎麼應用. 課程不長, 有 Lab, 沒證書. 看在老闆推薦的份上, 我也來蹭一下.

用最簡單的話來講, 它的技術就是叫每個 Agent 執行一個 task. 雖然大家平平都是 LLM, 但是指定了不同的角色, 每個 agent 就會各自專注在它的 task 上, 達到互相幫忙的結果. 當然每個 agent 的排列方式 (hierachy) 會影響他們共事的結果.

可不可 search 網路? 需不需要 human input, 可不可以非同步? 這些在 CrewAI 這家公司的 library 中都可以設定. 每個 agent 透過 memory 互相溝通, 因此即使不指定誰 (agent) 要傳訊息給誰 (other agents), 資料也可以共用.

有個 Lab 很好玩, 就是建立一個 crew 去分析買股票的風險. 它的架構是 Crew 叫 agent 做 task. Task 就只是明訂工作內容 (description) 和預期成果 (expect output), 然後註明給哪個 agent. Agent 要指定 role, goal, backstroy (工作指導), 標記可以用那些 tools? 標記可不可以餵資料給別人 (delegation), log 要多詳細 (verbose).

from crewai import Crew, Process
from langchain_openai import ChatOpenAI

# Define the crew with agents and tasks
financial_trading_crew = Crew(
    agents=[data_analyst_agent, 
            trading_strategy_agent, 
            execution_agent, 
            risk_management_agent],
    
    tasks=[data_analysis_task, 
           strategy_development_task, 
           execution_planning_task, 
           risk_assessment_task],
    
    manager_llm=ChatOpenAI(model="gpt-3.5-turbo", 
                           temperature=0.7),
    process=Process.hierarchical,
    verbose=True
)

Crew kickoff 之後, agent 就會去做事. 至於要做什麼? 寫在 input string 裡, 相當於一個 prompt. 舉例指定用 1000 元去買 Nvidia, 風險承受度中等, 應該如何操作? 在課程的例子中, 因為指定 process 是 hierachy. 所以叫第一個 agent 去做 data analysis, 它有 search 網路的 tool, 因此就會各個網站 search Nvidia 的新聞. 總結出 10 條. 交給下一棒 Trade agent.

Trade agent 的工作是要分析標的物的統計值, 它也有網路工具. 所以它也去找了一堆網站. 總結出 Nvidia 的評價.

Based on the information gathered from various analyst forecasts and recommendations, the average 12-month price target for NVDA is $130.68, with the highest target being $200.00 and the lowest at $90.00. The consensus rating for NVDA is “Strong Buy," supported by 38 buy ratings and 3 hold ratings. The stock has a current price of $135.58. The analysis suggests that there is a potential -3.61% downside from the current price based on the average price target. The historical performance of NVDA shows consistent outperformance relative to the industry.

接一下到了 execution agent. 它有甚麼大膽的創見嗎? 沒有. 即使它收到這麼明顯地看多訊息: Considering the historical performance and analyst forecasts, developing a trading strategy that aligns with the bullish sentiment towards NVDA could be a profitable approach, especially for day trading preferences.

它還是說我要上網查看看, 然後歸納出 5 點結論:

Execution Plan for NVDA:
1. Utilize historical performance data to identify key trends and patterns in NVDA’s stock price movements.
2. Implement a strategy that leverages the ‘Strong Buy’ recommendation and average 12-month price target of $130.68.
3. Monitor market trends and movements closely to capitalize on potential trading opportunities presented by NVDA’s growth potential.
4. Develop a risk management strategy that aligns with the user-defined risk tolerance (Medium) and trading preferences (Day Trading).
5. Regularly review and adjust the execution plan based on new market data and insights to optimize trading outcomes for NVDA.

接著回到 Crew. 它根據風險承受度為 Medium 這個條件, 再上網去跑一輪. 對每個網站的內容做一個小結論. 最後叫 risk management agent 彙總, 結果就是給安全牌 (因為風險承受度不高).

Overall, the risk analysis for NVDA’s trading strategies should focus on understanding the potential risks associated with each strategy, assessing the firm’s risk tolerance, and implementing appropriate safeguards to manage and mitigate risks effectively.

我認為畢竟 Crew 收到的指令就是風險承受度中等而已. 已經預設立場, 不用問 AI 也知道結果. 當我把風險承受度改為 Ultra High 重跑一次. 這次它的結論就變狠了! 建議了一些選擇權策略: Straddle Strategy、Iron Condor Strategy 、Long Call Butterfly Spread Strategy、LEAPS Contracts Strategy 等等.

這告訴我們兩件事.:

  1. CrewAI 使用 multi LLM 的功效很強大. 大家做完自己的事就交給同事 (co-worker), 各司其職. 可以用同一個 LLM 做出一群同事開會的效果!
  2. 你跟 AI 講我風險承受度低, AI 就叫你保守. 你說你不怕死, AI 就叫你玩選擇權. 這些不用問 AI, 應該是問施主你自己就好了.

[REF]

  1. https://www.coursera.org/learn/multi-ai-agent-systems-with-crewai/home/welcome