示範如何計算移動平均、RSI 布林通道等技術指標
股票指標 詳細的定義 這邊就先不詳談
會玩股票的都當作這些為基本的知識
確保你已經安裝了必要的 Python 庫,如 pandas、numpy 和 matplotlib
import pandas as pd
import numpy as np
# 創建示例數據框(日期、開盤價格、高價格、低價格、收盤價格)
data = {'Date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05'],
'Open': [100, 102, 105, 103, 108],
'High': [105, 110, 112, 105, 115],
'Low': [98, 100, 103, 100, 106],
'Close': [102, 105, 108, 102, 112]}
df = pd.DataFrame(data)
# 將日期列轉換為日期時間對象
df['Date'] = pd.to_datetime(df['Date'])
# 計算簡單移動平均(SMA)
def calculate_sma(data, window):
sma = data['Close'].rolling(window=window).mean()
return sma
# 計算相對強度指標(RSI)
def calculate_rsi(data, window):
price_diff = data['Close'].diff(1)
gain = price_diff.where(price_diff > 0, 0)
loss = -price_diff.where(price_diff < 0, 0)
avg_gain = gain.rolling(window=window).mean()
avg_loss = loss.rolling(window=window).mean()
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))
return rsi
# 計算5日簡單移動平均
df['5-day SMA'] = calculate_sma(df, 5)
# 計算14天相對強度指標(RSI)
df['14-day RSI'] = calculate_rsi(df, 14)
# 印出計算結果
print(df)
當短期移動平均 (如10日SMA) 超過長期移動平均 (如50日SMA) 時,我們進行買進。當RSI指標超過70時,我們將進行賣出。當RSI指標低於30時,我們將買進。
data['SMA10'] = data['Close'].rolling(window=10).mean()
data['SMA50'] = data['Close'].rolling(window=50).mean()
# 計算14日RSI指標
def calculate_rsi(data, window=14):
delta = data['Close'].diff()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(window=window).mean()
avg_loss = loss.rolling(window=window).mean()
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))
return rsi
data['RSI'] = calculate_rsi(data)
# 初始化交易信號列
data['Signal'] = 0
# 生成交易信號
for i in range(1, len(data)):
if data['SMA10'][i] > data['SMA50'][i] and data['RSI'][i] < 30:
data['Signal'][i] = 1 # 買入信號
elif data['SMA10'][i] < data['SMA50'][i] or data['RSI'][i] > 70:
data['Signal'][i] = -1 # 賣出信號
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 讀取台股創意股票價格數據,假設數據包含日期('Date')和收盤價格('Close')
# 你需要替換下面的路徑和文件名為你自己的數據
data = pd.read_csv('path_to_your_data.csv')
data['Date'] = pd.to_datetime(data['Date'])
data.set_index('Date', inplace=True)
# 計算布林通道的中軌道(20日簡單移動平均)
data['SMA'] = data['Close'].rolling(window=20).mean()
#計算布林通道的上軌道(20日簡單移動平均 + 2倍20日價格的標準差)
data['Upper'] = data['SMA'] + (2 * data['Close'].rolling(window=20).std())
#計算布林通道的下軌道(20日簡單移動平均 - 2倍20日價格的標準差)
data['Lower'] = data['SMA'] - (2 * data['Close'].rolling(window=20).std())
#初始化交易信號
data['Signal'] = 0
#生成交易信號
for i in range(20, len(data)):
if data['Close'][i] > data['Upper'][i - 1]:
data['Signal'][i] = -1 # 賣出信號
elif data['Close'][i] < data['Lower'][i - 1]:
data['Signal'][i] = 1 # 買進信號
#計算每日持倉股數
data['Position'] = data['Signal'].cumsum()
# 繪製價格圖和布林通道
plt.figure(figsize=(12, 6))
plt.plot(data.index, data['Close'], label='Close Price', color='blue')
plt.plot(data.index, data['SMA'], label='20-day SMA', color='orange')
plt.plot(data.index, data['Upper'], label='Upper Bollinger Band', color='red', linestyle='--')
plt.plot(data.index, data['Lower'], label='Lower Bollinger Band', color='green', linestyle='--')
plt.fill_between(data.index, data['Lower'], data['Upper'], alpha=0.2, color='gray')
#標記買進和賣出點
plt.plot(data[data['Signal'] == 1].index, data['SMA'][data['Signal'] == 1], '^', markersize=10, color='g', label='Buy Signal')
plt.plot(data[data['Signal'] == -1].index, data['SMA'][data['Signal'] == -1], 'v', markersize=10, color='r', label='Sell Signal')
plt.title('Taiwan Creative Stock Bollinger Band Strategy')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()