Published Date : 2021年1月19日10:12

Part 1 - Pyhonを使ったドルと円の為替レートを使った簡単な計算アプリ
Part 1 - Simple calculation app using dollar-yen exchange rate using Python


This blog has an English translation


ニコニコ動画にアップした動画のまとめ記事です。

This is a summary blog post about a video I uploaded to NicoNico.

細かい部分は動画を参考にしてください。

Please refer to the video for details.


目次

Table of Contents




① 動画の説明
① Video Description



警告:

このアプリは大雑把に大体の見積りを計算して楽しむ為のツールです。

計算の詳細や、端数の処理等は各金融機関等によって異なります。

このアプリを使って何かしらの損害が発生したとしても、私は一切の責任を負いません。

このアプリを使って何かしらの損害が発生したとしても、私は一切の責任を負いません。

Warning:

This application is used to calculate rough estimates and enjoy them.

The details of calculations and the treatment of fractions differ depending on the financial institution.

​I will not be liable for any damage caused by using this app.

ネットで公開されている2002年から2020年までのドルと円の月ごとの平均値のレートが格納されているCSVファイルを使用します。

Use a CSV file that contains rates for monthly averages of the dollar and yen from 2002 to 2020, as published on the Internet.

pandasを利用して、CSVファイルを読み込みます。

Use pandas to import CSV files.

import pandas as pd
path = 'csvfile.csv'
df = pd.read_csv(path)

文字コードがSHIFT-JISなのでデフォルトのUTF-8で読み込むとエラーになります。

Since the character code is SHIFT-JIS, an error occurs when reading with the default UTF-8.

正常にCSVを読み込む為にエンコーディングにSHIFT-JISを指定しましょう。

Specify SHIFT-JIS as encoding to read CSV correctly.

df = pd.read_csv(path, encoding='shift-jis')

列名が一部正しく表示されていません。

Some column names are not displayed correctly.

そして今回使用するのは日付とドルから円の列だけです。

And I will only use the date and dollar to yen columns this time.

なので、この二列だけのデータフレームを別で作成して、独自の分かりやすい列名を新たに作成しましょう。

So let's create a separate data frame with only these two columns, and create a new column names that are easy to identify of our own.

dollar_to_yen = df.iloc[1:, :2]
new_columns = ['年月日', '月平均ドル円']
dollar_to_yen.columns = new_columns

日付の列はストリング型であることが確認できました。

The date column seems to be a string data type.

Pythonオブジェクトのまま保存したいので、データフレームを辞書に変換しましょう。

I want to save it as a Python object, so I'll convert the data frames to dictionaries.

pickleモジュールをインポートして、with/openを使用して、Python辞書のままPickleファイルとして保存してみます。

Import the pickle module and use with/open to save it as a Pickle file, still a Python dictionary.

保存したPickleファイルを読み込んで、利用してみましょう。

Load and use your saved Pickle file.

ユーザーから入力された行のインデックス番号から、その年と月の平均ドル円を表示させてみましょう。

Let's display the average dollar to yen for the year and month from the row index number entered by the user.

今度はユーザーから入力された年と月から、平均ドル円を表示させてみましょう。

Now let's display the average dollar to yen from the year and month entered by the user.

年と月の有効範囲等をif文等で判定します。

To determine the valid range of years and months, use an if statement, etc.

別の関数を作成して、引数の年と月と辞書からその年と月の平均ドル円を表示させてみましょう。

Let's create another function that takes a year, a month, and a dictionary as arguments and displays the average dollar to yen for that year and month.

今度はqueryメソッドを利用して、入力された年と月から、平均ドル円を表示させてみましょう。

Next, let's use the query method to display the average dollar to yen from the year and month entered.

print(dollar_to_yen.query(f'年月日.str.startswith("{year}/{month}")', engine='python'))

こちらの方法のほうがスッキリしているのでこちらを採用しましょう。

This method is simpler, so let's use this one.

pandasのto_pickleメソッドを使用してデータフレームをそのままPickleファイルにして保存しましょう。

Now use the to_pickle method of pandas to save the data frames as Pickle files.

税率と手数料を変数にしましょう。

Let's define tax rates and commissions and make them variables.

先ほどと同じようにユーザーからの入力を受け付けるようにします。

Write a process that accepts input from the user as before.

queryメソッドを利用して、入力された年と月から、平均ドル円をデータフレームから抽出します。

Based on the year and month entered, the query method is used to extract the average dollar yen from the data frame.

先ほど抽出した平均ドル円はvaluesを使って文字列として取り出すことができます。

The average to dollar to yen extracted earlier can be retrieved as a string using values.

ドルの値を入力させて、円に換算します。

Let me enter the dollar value and convert it to yen.

全体でいくらになるかを計算します。

Calculate the total amount.

手数料を求めて、合計金額を計算します。

Calculates the total amount after calculating the charge.

結果をまとめて表示します。

View the results together.

今度は売却した際の計算を行います。

Next, we will calculate when we sell.

入力の項目は先ほどの購入処理とほぼ同じです。

​The input items are almost the same as the previous purchase process.

それらの処理をまとめてtry/exceptionを使用して記述しましょう。

Let's write them all together using try/exception.

税金計算等も同時に行いましょう。

Let's calculate taxes at the same time.

最終的な結果を表示させてみましょう。

Let's view the final result.

お次はまたFlaskを使用してWEBアプリにしてみましょう。

Next, let's turn these processes into Web applications using Flask, which we have used many times.



以上です。お疲れ様です。

That's all. Thank you for your hard work.