Skip to content

Instantly share code, notes, and snippets.

@e96031413
Created April 28, 2024 04:07
Show Gist options
  • Save e96031413/e25b3dbf6e0ef8de9be3bd697b79adb6 to your computer and use it in GitHub Desktop.
Save e96031413/e25b3dbf6e0ef8de9be3bd697b79adb6 to your computer and use it in GitHub Desktop.
Total Return Calculation for TW Stock assets using Dollar Cost Average Strategy (DCA)
import pandas as pd
from twstock import Stock
import argparse
def parse():
parser = argparse.ArgumentParser()
parser.add_argument(
"--etf_code", type=str, default="00733",
)
parser.add_argument(
"--year", type=int, default="2023",
)
parser.add_argument(
"--month", type=int, default="6",
)
return parser
# 獲取ETF的歷史價格數據
def get_etf_history_data(etf_code, year, month):
stock = Stock(etf_code)
history_data = stock.fetch_from(year, month)
name_attribute = ['Date', 'Capacity', 'Turnover', 'Open', 'High', 'Low', 'Close', 'Change','Transcation']
df = pd.DataFrame(columns=name_attribute, data=history_data)
return df
# 主程式
if __name__ == "__main__":
# 定義ETF的代碼
args = parse().parse_args()
df = get_etf_history_data(args.etf_code, args.year, args.month)
# 假設每個交易日投入200元
investment_per_day = 200
df['Shares_Purchased'] = investment_per_day / df['Close']
total_investment = investment_per_day* len(df)
# 計算資產終值
final_value = df['Shares_Purchased'].sum()*df['Close'].iloc[-1]
# 計算報酬率
overall_return = (final_value - total_investment) / total_investment
# 打印結果
print("整體報酬率: {:.2%}".format(overall_return))
print("總投入資金: {:.2f}元".format(total_investment))
print("資產終值: {:.2f}元".format(final_value))
print("淨收益: {:.2f}元".format(final_value-total_investment))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment