價格預測通常結合機器學習和深度學習演算法,並運用歷史數據及市場技術指標。以下是常見的一些方法:
使用強化學習的智能交易系統可以在模擬的市場環境中學習,並隨時間優化買賣決策,逐步改善交易策略。
AI 模型可以通過新聞和社交媒體的情感分析,來判斷市場情緒,並根據外部因素預測股票價格變化。
結合多種演算法和外部數據(例如經濟指標、公司基本面分析),通常能產生最有效的 AI 股票價格預測模型。
在使用 AI 進行股票價格預測時,模型會生成多種指標來幫助投資者做出決策。這些指標可以用來判斷市場走向,並根據不同的情境採取相應的交易操作。以下是一些常見的預測指標及其操作策略:
這是模型直接預測的未來股票價格數值。
模型可能會預測股票價格上漲或下跌的概率。
模型可能會基於技術指標(如移動平均線)預測股票的趨勢方向。
技術指標如 RSI(相對強弱指數)可以用來判斷股票是否處於超買或超賣狀態。
模型可以預測股票未來的價格波動區間。
基於市場買賣雙方的強度預測。
模型可能會根據歷史數據建議合理的止損與止盈點。
根據不同的預測指標,投資者可以做出相應的交易決策,如買入、賣出或保持觀望。綜合多種指標有助於在不同的市場情境下做出更合理的投資決策。
CurrencyAPI 提供即時匯率資訊。以下是範例程式碼:
import requests url = 'https://api.currencyapi.com/v3/latest' params = { 'apikey': '您的API金鑰', 'base_currency': 'USD', 'currencies': 'TWD' } response = requests.get(url, params=params) data = response.json() usd_to_twd = data['data']['TWD']['value'] print(f"1 美元等於 {usd_to_twd} 新台幣")
注意:需至 CurrencyAPI 註冊並取得 API 金鑰後才能使用。
ExchangeRatesAPI 同樣提供即時匯率查詢服務:
import requests url = 'https://api.exchangeratesapi.io/latest' params = { 'access_key': '您的API金鑰', 'base': 'USD', 'symbols': 'TWD' } response = requests.get(url, params=params) data = response.json() usd_to_twd = data['rates']['TWD'] print(f"1 美元等於 {usd_to_twd} 新台幣")
請先至 ExchangeRatesAPI 註冊取得 API 金鑰並替換程式碼中的 '您的API金鑰'。
若不想直接調用 API,可使用第三方 Python 套件 forex-python:
from forex_python.converter import CurrencyRates cr = CurrencyRates() usd_to_twd = cr.get_rate('USD', 'TWD') print(f"1 美元等於 {usd_to_twd} 新台幣")
安裝套件命令:
pip install forex-python
若不使用 API,可以透過網頁爬蟲技術直接從 Currency.Wiki 網站擷取美元對台幣的即時匯率。
需要安裝以下 Python 套件:
pip install requests pip install beautifulsoup4
import requests from bs4 import BeautifulSoup # 設定目標網址 url = "https://currency.wiki/usd_twd" # 發送 GET 請求取得網頁內容 response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 查找特定標籤和類別 span_tag = soup.find('span', class_='unit_secondary_value') rate = span_tag.text print(f"1 美元等於 {rate} 新台幣")
透過 Python 爬蟲技術可直接取得即時匯率資訊,但需注意網頁結構變動和合規性問題,適合小規模應用或學習用途。
使用 Python 和隨機森林模型來預測股票的漲跌概率。此範例利用 Yahoo 財經的股票數據,並通過技術指標來訓練模型,最後輸出股票上漲和下跌的概率。
首先,我們需要安裝並匯入 Python 的一些套件:
pip install yfinance scikit-learn pandas numpy
接著匯入這些必要的庫:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import yfinance as yf
接下來,我們從 Yahoo 財經下載股票的歷史數據,並計算簡單移動平均線 (SMA) 作為技術指標。
# 從 Yahoo 財經下載蘋果公司的股票數據
symbol = 'AAPL'
data = yf.download(symbol, start='2020-01-01', end='2023-01-01')
# 計算 10 日和 50 日簡單移動平均線 (SMA)
data['SMA_10'] = data['Close'].rolling(window=10).mean()
data['SMA_50'] = data['Close'].rolling(window=50).mean()
# 設置漲跌目標,若次日收盤價高於當日收盤價,則為1 (表示上漲),否則為0 (表示下跌)
data['Target'] = np.where(data['Close'].shift(-1) > data['Close'], 1, 0)
# 移除缺失值
data.dropna(inplace=True)
我們將使用移動平均線 (SMA) 和收盤價作為特徵,並將數據分為訓練集和測試集。
# 選擇特徵
features = ['SMA_10', 'SMA_50', 'Close']
X = data[features]
y = data['Target']
# 分割訓練集與測試集 (80%訓練,20%測試)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
我們使用隨機森林模型來訓練數據,並預測測試集中股票的漲跌概率。
# 初始化隨機森林分類器
model = RandomForestClassifier(n_estimators=100, random_state=42)
# 訓練模型
model.fit(X_train, y_train)
# 預測測試集中的漲跌
y_pred = model.predict(X_test)
y_prob = model.predict_proba(X_test) # 獲取漲跌的概率
我們可以計算模型的準確率,並顯示每一天的漲跌概率。
# 計算模型準確率
accuracy = accuracy_score(y_test, y_pred)
print(f"模型準確率: {accuracy:.2f}")
# 顯示測試集中前 5 天的漲跌概率
for i in range(5):
print(f"第{i+1}天:上漲概率={y_prob[i][1]:.2f}, 下跌概率={y_prob[i][0]:.2f}")
根據上漲的概率,您可以設定一個閾值來決定是否進行買入操作。例如,如果上漲概率超過 70%,則買入。
# 設定上漲概率的閾值
threshold = 0.7
# 根據概率進行買入決策
for i in range(len(y_prob)):
if y_prob[i][1] > threshold:
print(f"第{i+1}天建議買入,預測上漲概率={y_prob[i][1]:.2f}")
else:
print(f"第{i+1}天不建議買入,預測上漲概率={y_prob[i][1]:.2f}")
這個範例展示了如何使用隨機森林模型來預測股票的漲跌概率,並根據預測結果進行交易決策。這是一種簡單但有效的方式來提高交易決策的準確性。
Binance 是一個全球領先的加密貨幣交易所,為開發者提供豐富的 API 支援,包括 Spot API 和 Client API,方便使用者進行自動交易和數據獲取。
Binance Spot API 是 Binance 為現貨市場交易者設計的 API,可用於查詢市場資訊、下單、取消訂單等操作。此 API 常用於設計交易機器人、自動交易策略和監控市場波動。
Binance Client API 提供一個便捷的方式來存取 Binance 的各種 API 方法。開發者可以使用 binance.client
庫進行 API
認證和管理,並便捷地調用各種現貨和合約市場的功能。
pip install binance
binance.client
進行 API 連接,並調用 binance.spot
方法。
from binance.client import Client
# 初始化客戶端
client = Client(api_key='your_api_key', api_secret='your_secret_key')
# 取得當前的價格
price = client.get_symbol_ticker(symbol="BTCUSDT")
print(price)
Max Coin API 是由 Max Exchange 提供的一套應用程式介面,允許開發者程式化地訪問其加密貨幣交易功能。開發者可以透過 API 自動化執行交易、檢索市場數據以及管理資產。
以下是一個透過 API 獲取市場數據的範例:
GET https://max-api.maicoin.com/api/v1/ticker?market=btctwd
該請求將返回 BTC/TWD 的即時市場數據,包括價格、成交量等。
以下是一個使用 Python 語言調用 Max API 的簡單範例:
import requests BASE_URL = "https://max-api.maicoin.com" def get_ticker(pair): endpoint = "/api/v1/ticker" params = {"market": pair} response = requests.get(BASE_URL + endpoint, params=params) return response.json() # 獲取 BTC/TWD 市場數據 ticker_data = get_ticker("btctwd") print(ticker_data)
Ethereum 虛擬機(Ethereum Virtual Machine,簡稱 EVM)是以太坊的核心組件,負責執行智能合約。EVM 提供了一個沙箱環境,允許開發者在上面運行代碼,而不需要擔心會影響到以太坊網絡的其他部分。
智能合約是自動執行、不可更改的合約,執行時由 EVM 處理。開發者通常使用 Solidity 等高級編程語言來撰寫智能合約,然後將其編譯成 EVM 可理解的字節碼。
Solidity 是 Ethereum 上最常用的編程語言,語法類似於 JavaScript。以下是一個簡單的 Solidity 智能合約示例:
pragma solidity ^0.8.0;
contract SimpleStorage {
uint public storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
上述合約包含一個用來儲存整數數據的變量 storedData
,以及設置和獲取該數據的函數。
當用戶在以太坊網絡上執行一個智能合約時,以下步驟會發生:
EVM 的運算資源是有限的,為了防止網絡濫用,EVM 使用 Gas
機制來計算和收取交易費用。每個操作都有其相應的 Gas 成本,用戶在提交交易時需要提供足夠的 Gas
來支付執行智能合約所需的計算資源。
EVM 是以太坊網絡的核心,提供了一個強大的環境來運行智能合約。通過使用 Solidity 等編程語言,開發者可以創建各種去中心化應用(dApps),並利用 EVM 的功能來實現複雜的邏輯運算和交易處理。
Node.js
和 npm
Hardhat
:npm install --save-dev hardhat
npx hardhat
,選擇「Create a basic sample project」在 contracts
資料夾中新增 LendingProtocol.sol
並貼上你的 Solidity 合約。
於 scripts
資料夾建立 deploy.js
,內容如下:
async function main() {
const [deployer] = await ethers.getSigners();
console.log("部署帳號:", deployer.address);
const TokenAddress = "0xYourTokenAddressHere";
const LendingProtocol = await ethers.getContractFactory("LendingProtocol");
const lending = await LendingProtocol.deploy(TokenAddress);
await lending.deployed();
console.log("LendingProtocol 部署成功:", lending.address);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
啟動 Hardhat 測試鏈:
npx hardhat node
另開一個 terminal 部署:
npx hardhat run scripts/deploy.js --network localhost
hardhat.config.js
中加入:
require("@nomiclabs/hardhat-ethers");
module.exports = {
networks: {
goerli: {
url: "https://goerli.infura.io/v3/你的API金鑰",
accounts: ["0x你的私鑰"]
}
},
solidity: "0.8.20"
};
然後部署:
npx hardhat run scripts/deploy.js --network goerli
部署後會輸出合約地址,可用於前端整合與互動。
本借貸協議為以太坊虛擬機(EVM)上運行的智慧合約,用戶可以透過本合約存入資產賺取利息或借出資產支付利息。此協議支援ERC-20代幣,具備借貸、儲蓄、清算等核心功能。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC20 {
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
function transfer(address recipient, uint amount) external returns (bool);
function balanceOf(address account) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
}
contract LendingProtocol {
IERC20 public token;
address public owner;
uint public interestRate = 5; // 年利率5%
mapping(address => uint) public deposits;
mapping(address => uint) public borrows;
constructor(address _token) {
token = IERC20(_token);
owner = msg.sender;
}
function deposit(uint amount) external {
require(amount > 0, "金額需大於0");
token.transferFrom(msg.sender, address(this), amount);
deposits[msg.sender] += amount;
}
function borrow(uint amount) external {
require(amount > 0, "金額需大於0");
uint collateral = deposits[msg.sender];
require(collateral >= amount * 2, "抵押不足");
borrows[msg.sender] += amount;
token.transfer(msg.sender, amount);
}
function repay(uint amount) external {
require(amount > 0, "金額需大於0");
require(borrows[msg.sender] >= amount, "借款不足");
borrows[msg.sender] -= amount;
token.transferFrom(msg.sender, address(this), amount);
}
function withdraw(uint amount) external {
require(deposits[msg.sender] >= amount, "餘額不足");
require(borrows[msg.sender] == 0, "有未還借款");
deposits[msg.sender] -= amount;
token.transfer(msg.sender, amount);
}
}
可以透過以下網址訪問台灣證券交易所的公開申購公告頁面:
使用 Python 搭配 requests
和 BeautifulSoup
,即可抓取頁面上的公開申購資料。
import requests from bs4 import BeautifulSoup import pandas as pd # 抓取公開申購公告頁面 url = "https://www.twse.com.tw/zh/announcement/public.html" headers = {"User-Agent": "Mozilla/5.0"} response = requests.get(url, headers=headers) if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') tables = pd.read_html(response.text) if tables: df = tables[0] # 取第一個表格 print(df) else: print("未找到表格資料") else: print("無法連接到公開申購公告頁面")
Selenium
模擬瀏覽器操作。MetaQuotes Language(簡稱 MQL)是一種專為金融市場交易開發的程式語言,用於在 MetaTrader 平台(如 MT4 和 MT5)中創建自動交易策略(Expert Advisors)、自定指標、腳本及函數庫。
// 每次新 K 棒開始時進行操作
int start() {
if (OrdersTotal() == 0 && Volume[0] == 1) {
OrderSend(Symbol(), OP_BUY, 0.1, Ask, 3, 0, 0, "Buy Order", 0, 0, clrGreen);
}
return 0;
}
#property indicator_separate_window
#property indicator_buffers 1
double Buffer[];
int OnInit() {
SetIndexBuffer(0, Buffer);
return(INIT_SUCCEEDED);
}
int OnCalculate(const int rates_total, const int prev_calculated,
const datetime &time[], const double &open[],
const double &high[], const double &low[],
const double &close[], const long &tick_volume[],
const long &volume[], const int &spread[]) {
for (int i = 0; i < rates_total; i++) {
Buffer[i] = close[i] - open[i];
}
return(rates_total);
}
MQL 程式碼可透過 MetaTrader 內建的 MetaEditor 編輯與編譯,並在策略測試器中回測與優化。
MetaQuotes Language 是為交易自動化而生的專業語言,無論是初學者還是專業量化交易者,都能利用其強大功能實現精細交易策略。
email: [email protected]