Last active
September 6, 2023 10:50
-
-
Save e96031413/13503766e32a314cff10687fe2ac5fdb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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="2018", | |
) | |
parser.add_argument( | |
"--month", type=int, default="9", | |
) | |
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 = 300 | |
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