Skip to content

johnGitHub24/DataFrame_NumPy

Repository files navigation

DataFrame 和 NumPy 範例專案

本專案提供完整的 DataFrame 和 NumPy 操作範例,使用物件導向程式設計(OOP)架構,並包含詳細的繁體中文註解和使用說明。

📁 專案結構

DataFrame_NumPy/
├── 01_dataframe_crud.py          # DataFrame CRUD 操作範例
├── 02_numpy_examples.py          # NumPy 操作範例
├── 03_format_conversion.py       # 格式轉換範例
├── 04_html_markdown_templates.py # HTML 和 Markdown 範本生成
├── 05_finance_trading_example.py # 金融交易案例
├── test_all_modules.py           # 測試程式
└── README.md                     # 本檔案

🚀 快速開始

安裝依賴套件

pip install pandas numpy tabulate openpyxl

執行範例

# 執行 DataFrame CRUD 範例
python 01_dataframe_crud.py

# 執行 NumPy 範例
python 02_numpy_examples.py

# 執行格式轉換範例
python 03_format_conversion.py

# 執行 HTML/Markdown 範例
python 04_html_markdown_templates.py

# 執行金融交易案例
python 05_finance_trading_example.py

# 執行所有測試
python test_all_modules.py

📚 模組說明

1. DataFrame CRUD 操作 (01_dataframe_crud.py)

提供完整的 DataFrame 建立、讀取、更新、刪除功能。

主要類別:

  • DataFrameCRUD: DataFrame CRUD 操作類別

使用範例:

from dataframe_crud import DataFrameCRUD

# 建立實例
crud = DataFrameCRUD()

# 建立資料
data = {
    '姓名': ['張三', '李四', '王五'],
    '年齡': [25, 30, 35],
    '薪資': [50000, 60000, 70000]
}
crud.create(data)

# 讀取資料
all_data = crud.read()
filtered = crud.read(condition="年齡 > 28")

# 更新資料
crud.update(index=0, column='薪資', value=55000)

# 刪除資料
crud.delete(index=1)

2. NumPy 操作 (02_numpy_examples.py)

提供 NumPy 陣列建立、運算、統計、線性代數等功能。

主要類別:

  • NumPyOperations: NumPy 操作類別

使用範例:

from numpy_examples import NumPyOperations

# 建立實例
np_ops = NumPyOperations()

# 建立陣列
arr = np_ops.create_from_list([1, 2, 3, 4, 5])
zeros = np_ops.create_zeros((3, 4))
random_arr = np_ops.create_random((3, 3), seed=42)

# 陣列運算
result = np_ops.add(10)
result = np_ops.multiply(2)

# 統計運算
mean = np_ops.mean()
std = np_ops.std()

3. 格式轉換 (03_format_conversion.py)

提供各種資料格式之間的轉換功能。

主要類別:

  • FormatConverter: 格式轉換類別

支援的轉換:

  • DataFrame ↔ NumPy
  • DataFrame ↔ 字典
  • DataFrame ↔ JSON
  • DataFrame ↔ CSV
  • DataFrame ↔ Excel

使用範例:

from format_conversion import FormatConverter

converter = FormatConverter()

# DataFrame 轉 NumPy
arr = converter.dataframe_to_numpy(df)

# DataFrame 轉 JSON
json_str = converter.dataframe_to_json(df, orient='records')

# 儲存為 CSV
converter.save_dataframe_to_csv(df, 'data.csv')

# 載入 Excel
df = converter.load_dataframe_from_excel('data.xlsx')

4. HTML 和 Markdown 範本 (04_html_markdown_templates.py)

提供將 DataFrame 轉換為 HTML 和 Markdown 報表的功能。

主要類別:

  • HTMLTemplate: HTML 範本生成類別
  • MarkdownTemplate: Markdown 範本生成類別

使用範例:

from html_markdown_templates import HTMLTemplate, MarkdownTemplate

# 生成 HTML 報表
html_gen = HTMLTemplate(title="資料報表", style="financial")
html_report = html_gen.dataframe_to_html_report(df, 
                                                filepath='report.html')

# 生成 Markdown 報表
md_gen = MarkdownTemplate(title="資料報表")
md_report = md_gen.dataframe_to_markdown_report(df, 
                                                filepath='report.md')

5. 金融交易案例 (05_finance_trading_example.py)

完整的金融資料分析和交易策略實作範例。

主要類別:

  • StockDataProcessor: 股票資料處理類別
  • TechnicalIndicators: 技術指標計算類別
  • TradingStrategy: 交易策略類別
  • FinanceReportGenerator: 金融報表生成類別

使用範例:

from finance_trading_example import (
    StockDataProcessor,
    TechnicalIndicators,
    TradingStrategy
)

# 步驟 1: 建立股票資料
processor = StockDataProcessor()
df = processor.create_sample_data('2330', days=60, start_price=580.0)

# 步驟 2: 計算技術指標
indicators = TechnicalIndicators(df)
df_with_indicators = indicators.add_all_indicators()

# 步驟 3: 實作交易策略
strategy = TradingStrategy(df_with_indicators)
signals = strategy.moving_average_crossover(fast_period=5, slow_period=20)

# 步驟 4: 策略回測
results = strategy.backtest(initial_capital=100000, commission=0.001)
print(f"總報酬率: {results['total_return']:.2%}")

🧪 測試

執行所有測試:

python test_all_modules.py

測試涵蓋:

  • DataFrame CRUD 操作
  • NumPy 陣列操作
  • 格式轉換
  • HTML/Markdown 生成
  • 金融交易案例

💡 使用模式說明

每個模組都包含詳細的使用模式說明,包括:

  1. 類別初始化模式:如何建立類別實例
  2. 方法使用模式:每個方法的詳細使用範例
  3. 參數說明:每個參數的用途和格式
  4. 返回值說明:返回值的類型和內容
  5. 注意事項:使用時需要注意的事項

📊 金融交易案例完整流程

  1. 資料準備

    • 使用 StockDataProcessor 建立或載入股票資料
  2. 技術分析

    • 使用 TechnicalIndicators 計算各種技術指標
    • 支援:SMA、EMA、RSI、MACD、布林通道等
  3. 策略實作

    • 使用 TradingStrategy 實作交易策略
    • 支援:移動平均交叉、RSI 策略等
  4. 回測分析

    • 使用 backtest() 方法進行策略回測
    • 計算總報酬率、夏普比率等指標
  5. 報表生成

    • 使用 FinanceReportGenerator 生成分析報表
    • 支援 HTML 和 Markdown 格式

🔧 進階使用

自訂 HTML 樣式

html_gen = HTMLTemplate(title="報表", style="modern")
# 可選樣式:'modern', 'financial', 'minimal'

自訂技術指標參數

indicators = TechnicalIndicators(df)
rsi = indicators.calculate_rsi(period=14)  # 自訂 RSI 週期
macd = indicators.calculate_macd(fast_period=12, slow_period=26)

自訂交易策略

class MyStrategy(TradingStrategy):
    def custom_strategy(self):
        # 實作自訂策略邏輯
        pass

📝 注意事項

  1. 資料型別:確保資料型別正確,特別是數值運算時
  2. 缺失值處理:某些計算可能需要處理缺失值(NaN)
  3. 效能考量:大量資料時注意記憶體使用
  4. 日期格式:處理日期時注意時區和格式

🤝 貢獻

歡迎提出問題和改進建議!

📄 授權

本專案僅供學習和參考使用。

About

DataFrame 和 NumPy 範例專案,使用 OOP 架構

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors