ビットコインの年間利益計算スクリプト作成した。BitFlyerの取引レポートをそのまま読みこめるようにしてある。
間違っている点あればコメントで教えてください。
import pandas as pd def calculate_annual_profit_average_method(csv_file): # CSVファイルの読み込み df = pd.read_csv(csv_file, parse_dates=['取引日時']) # 必要な列のみ取得 df = df[['取引日時', '取引種別', '取引価格', '通貨1数量', '手数料']] df = df.sort_values('取引日時') # 取引日時でソート # 年ごとのデータに分ける df['年'] = df['取引日時'].dt.year annual_profit = {} # 年ごとに計算 total_quantity = 0 # 総購入数量 total_cost = 0 # 総購入金額 for year, group in df.groupby('年'): profit = 0 # 売却利益 # まず、年内の購入取引の合計を計算 for _, row in group.iterrows(): if row['取引種別'] == '買い': price = float(row['取引価格'].replace(",", "")) quantity = abs(float(row['通貨1数量'].replace(",", ""))) # 購入にかかったコスト total_cost += price * quantity # 購入数量 total_quantity += quantity - abs(float(row['手数料'])) if row['取引種別'] == '受取': quantity = abs(float(row['通貨1数量'].replace(",", ""))) total_quantity += quantity # 年末の平均取得原価を計算 if total_quantity > 0: avg_cost_price = total_cost / total_quantity else: avg_cost_price = 0 # 次に売却取引を確認して利益を計算 for _, row in group.iterrows(): if row['取引種別'] == '売り': price = float(row['取引価格'].replace(",", "")) quantity = abs(float(row['通貨1数量'].replace(",", ""))) # 売却利益 = (売却価格 - 平均取得原価) * 売却数量 profit += (price - avg_cost_price) * (quantity - abs(float(row['手数料']))) total_quantity -= quantity total_quantity -= abs(float(row['手数料'])) # 年ごとの利益を辞書に追加 annual_profit[year] = int(profit) total_cost = avg_cost_price * total_quantity return annual_profit def calculate_annual_profit_moving_average(csv_file): # CSVファイルの読み込み df = pd.read_csv(csv_file, parse_dates=['取引日時']) # 必要な列のみ取得 df = df[['取引日時', '取引種別', '取引価格', '通貨1数量', '手数料']] df = df.sort_values('取引日時') # 取引日時でソート # 年ごとのデータに分ける df['年'] = df['取引日時'].dt.year annual_profit = {} # 年ごとに計算 total_quantity = 0 # 保有残高 total_cost = 0 # 総購入金額 for year, group in df.groupby('年'): profit = 0 # 売却利益 for _, row in group.iterrows(): if row['取引種別'] == '買い' or row['取引種別'] == '売り' or row['取引種別'] == '受取': price = float(row['取引価格'].replace(",", "")) quantity = abs(float(row['通貨1数量'].replace(",", ""))) if row['取引種別'] == '買い': # 購入時は総購入金額と保有数量を更新 total_cost += price * quantity total_quantity += quantity total_quantity -= abs(float(row['手数料'])) # 平均取得原価の更新 avg_cost_price = total_cost / total_quantity elif row['取引種別'] == '売り': # 売却利益 = (売却価格 - 平均取得原価) * 売却数量 profit += (price - avg_cost_price) * quantity # 保有数量と総購入金額の更新 total_cost -= (avg_cost_price * quantity) total_quantity -= quantity total_quantity -= abs(float(row['手数料'])) elif row['取引種別'] == '受取': total_quantity += quantity avg_cost_price = total_cost / total_quantity # 年ごとの利益を辞書に追加 annual_profit[year] = int(profit) return annual_profit # 使用例 csv_file = 'TradeHistory.csv' annual_profit = calculate_annual_profit_average_method(csv_file) print("総平均法") print(" 年間利益:", annual_profit) annual_profit = calculate_annual_profit_moving_average(csv_file) print("移動平均法") print(" 年間利益:", annual_profit)