1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ビットコインの年間利益計算スクリプト

Posted at

ビットコインの年間利益を総平均法で計算するスクリプト作成しました。何か間違っている点あればご指摘いただきたいです。

移動平均法は以下参照。

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
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?