M1mac へmetasploitableインストール

M1mac へmetasploitableインストール

https://dev.to/merlos/how-to-setup-metasploitable-in-a-mac-with-m1-chip-44ph
を参考に

既にUTMはインストール済みなので
https://app.vagrantup.com/rapid7
へアクセスし
metasploitable3-ub1404
をダウンロードする

ダウンロードするのは
Virtual box のファイル

そのままだとわかりにくいので

Cd Download
mv 383cc30c-ae33-481e-b8e6-d0831964d33c metasploitable3-ub1404.zip

でファイル名変更

unzip metasploitable3-ub1404.zip

で解凍

しかし

Archive:  metasploitable3-ub1404.zip
  End-of-central-directory signature not found.  Either this file is not
  a zipfile, or it constitutes one disk of a multi-part archive.  In the
  latter case the central directory and zipfile comment will be found on
  the last disk(s) of this archive.
unzip:  cannot find zipfile directory in one of metasploitable3-ub1404.zip or
        metasploitable3-ub1404.zip.zip, and cannot find metasploitable3-ub1404.zip.ZIP, period.

となる

とりあえず解凍は
Gzip で解凍して
Tar コマンドで展開することで解決

次に
Qemu のインストール

brew install qemu

でOK

これは brew で簡単にインストールできるが時間が2時間ほどかかった

次に

cd Downloads
cd metasploitable3-ub1404

で対象ディレクトリに移動し

qemu-img convert -O qcow2 -c ./metasploitable3-ub1404-disk001.vmdk ./metasploitable3-ub1404-disk001.qcow2

を実行し変換

次にUTM 起動

仮想マシンを作成
をクリック

エミュレートをクリック

OSはその他を選択

ISO 起動をスキップ
にチェックを入れる

メモリを
1024 に変更する

データ保存ドライブは20GBに設定

あとはそのまま続けていき
仮想マシンの設定で
QEMU で
UEFI起動のチェックを外す

次にIDEドライブ
をクリックし
ドライブを削除
をクリック

これで消去されるので
ドライブの新規をクリック

読み込むをクリックし

metasploitable3-ub1404-disk001.qcow2
を選択

これで保存すれば起動できる

ログインユーザとパスワードは
デフォルトは vagrant になっている

M1Mac で UTM で仮想マシンを起動

M1Mac で UTM で仮想マシンを起動

UTMを使ってm1 macにKaliLinuxの仮想環境を構築する話

を参考に行ったが
Utm を
https://mac.getutm.app/
からダウンロード

https://www.kali.org/get-kali/#kali-installer-images
から
Kali linux をダウンロードしたが
Weekly
Installer
ともに黒い画面のままになる

参考サイトを変更

M1 mac で Windows11を : 無償のUTM (準備編)
を参考に行う

Brew は以前にインストール済み

brew install aria2

を実効

aria2 はマルチプロトコルのダウンローダ

しかし変わらない

次に
Graphical installを選択すると画像のような『_』が点滅している画面から動かなくなってしまいます

によれば
https://www.youtube.com/watch?v=WHlZEU5ejek&t=247s
にあるように
When I selected “Graphical Install” I ended up with a black screen and blinking cursor. I needed to make two changes. 1) Under the Kali Linux launcher in the left panel select “Edit” and goto “Display”. Change to “Console Only”. Save. 2) When you “Run” choose the “Install” option and NOT the “Graphical Install”

って書いてあるけど
最新のUTM だと
https://docs.getutm.app/guides/kali/#black-screen-on-start
に載っているように
仮想マシンの編集で
デバイス > 新規. > シリアル
とすることで
ターミナル画面が一緒に起動するようになり
インストールする時に
Install
というコマンドラインで行う方で立ち上げすればできる

ラズパイドラレコ作成

ラズパイドラレコ作成

ssh
でアクセスし

sudo apt-get update
sudo apt-get upgrade

のあと

sudo raspi-config


最初のメニューの5番目の項目、Interfacing Optionsを開くと1番上にカメラの項目があるのでこれを有効化

ここまでできたら

v4l2-ctl --list-devices

使用するカメラのデバイスファイルを調べる
通常は

/dev/video0

となる

デバイスファイルを特定しておくと、下記のコマンドでサポートしている動画のフォーマットを表示することが可能

v4l2-ctl -d /dev/video0 --list-formats

ラズパイで動画を撮影する方法として、FFmpegを使用してリアルタイムでハードウェアエンコードする方法がよく紹介されていますが、特にRaspberry Pi Zeroだとフレームレートがあまり出ないのでドラレコには不向き

しかしハードウェアエンコードなんてしなくても、H.264をサポートしているカメラモジュールを使用すれば、専用の動画撮影コマンドraspividを実行することで簡単にH.264動画を撮影することが可能

安価なUSB接続のWebカメラだとH.264をサポートしていなかったりしますが、私が確認した限りではラズパイ向けのカメラモジュールはどれもH.264をサポートしているので、基本的にraspividで録画することをおすすめ

raspividで動画を撮影するには
もっともシンプルに書くなら、-oで出力ファイル名のみを指定してこのように記述
なお指定した名前のファイルが既に存在する場合は実行に失敗するので注意

raspivid -o test.h264

このように何も指定せずに実行すると5秒の動画ファイルが生成される

拡張子がH.264と扱いにくい形式ですが、一応このままでもVLCなどの動画プレーヤーで再生することが可能 

撮影してみてカメラの向きが上下反転していた場合は-vf、左右反転していた場合は-hfを付け加えることで正常な向きに補正されるはず

また-rotで角度を指定して回転させることもできる

raspivid -o test.h264 -rot 180

正しい方向で撮影できるようになったら-wと-hで解像度、-tで撮影時間、-fpsでフレームレート、-bでビットレートを指定

raspivid -o test.h264 -rot 180 -w 1280 -h 720 -t 10000 -fps 30 -b 2000000

撮影時間はミリ秒で指定するため、-t 10000だと10秒の動画を生成

ただし-t 0で時間を指定しなければずっと録画し続けることが可能

Ctrl+Cで録画を停止

解像度やビットレートを上げれば高画質な動画を撮影できますが、それに比例してファイルサイズも大きくなるので注意

raspividの実行中にWi-Fiから切断されるとコマンドラインが閉じられるために録画も停止してしまう
車内にWi-Fi環境が整っている場合はともかく、そうでないならもう一工夫が必要

Raspberry Pi Zeroがネットワークから切断されてもraspividを停止しないようにするために、まずコマンドを実行するシェルスクリプトを作成

sudo nano test.sh

中身は

#!/bin/sh

raspivid -o `date '+%Y%m%d-%H%M'`.h264 \
-rot 180 -w 1280 -h 720 -t 10000 -fps 30 -b 2000000

あとは

sh test.sh

で録画できればok

次は
作成したスクリプトをサービスとしてシステム管理デーモンのsystemdに登録

まずは自動実行させたいスクリプトを/optに作成

sudo nano /opt/test.sh

今回は録画時間を指定しない

#!/bin/sh

raspivid -o `date '+%Y%m%d-%H%M'`.h264 \
-rot 180 -w 1280 -h 720 -t 0 -fps 30 -b 2000000

次は

sudo chmod 0755 /opt/test.sh

で実行権限付与

このスクリプトをサービスとしてsystemdに登録するため、ユニットファイルを作成

sudo nano /etc/systemd/system/test.service

中身は

[Unit]
Description = test

[Service]
ExecStart = /opt/test.sh
Restart = always
Type = simple

[Install]
WantedBy = multi-user.target

解説
Descriptionはユニットファイルの説明です。これは自由に記述

ExecStartに登録したいスクリプトを記述

Restartはalwaysを設定しておくことで、プロセスが不意に終了しても再起動させることが可能です。再起動する条件として異常終了した場合のみ、あるいは逆に正常終了した場合のみなどを設定することも可能ですが、通常はalwaysで良い

例外として後述するsystemctlコマンドで停止した場合のみ再起動されない

Typeはプロセスの起動タイプを設定するオプションです。simpleがデフォルトで、メインプロセスとして登録

WantedByは弱く依存するユニットを記述します。噛み砕いて説明すると、multi-user.targetの起動時にtest.serviceの起動も試みてほしい、ということです。多くのサービスがmulti-user.targetに紐付いていて、OS起動時にまとめて実行されます。

ユニットを定義できたら、サービスを有効化するために下記のコマンドを実行

sudo systemctl enable test.service

正常に有効化されていれば、下記のコマンドを入力するとバックグラウンドでサービスが実行されます。

サービスの状態は下記のコマンドで確認

sudo systemctl status test.service

しかし

Loaded: loaded (/etc/systemd/system/test.service; enabled; vendor preset: > Active: inactive (dead)

と表示されて固まる

Systemd を利用してサービスを追加・登録する

を参考に

systemctl list-unit-files --type=service |grep test

を実行し

glamor-test.service                        enabled         enabled
gldriver-test.service                      enabled         enabled
test.service                               enabled         enabled

で稼働しているのを確認

またサービスを手動で停止したい場合は下記のコマンドを実行

sudo systemctl stop test.service

とりあえず止めておく
理由は

ただし普通にraspividコマンドを実行すると1つの巨大な動画ファイルが生成されてしまうので、特にWi-Fi経由でデータを取り出そうとするとかなり時間がかかります

解決策として
FFmpegへパイプ入力して動画ファイルの分割&変換処理を自動的に実行させることで対策

https://gadget-live.net/raspberry-pi-raspivid-ffmpeg-pipe-input/
を参考に

あとは
Raspberry Pi Zeroをシャットダウンして安全に電源を切る方法

スマートフォンのテザリングでSSH接続
これだと
Bluetoothテザリング

があるが
問題は複数のペアリングが可能かということ

Alexaを利用してハンズフリーで操作
これもありだけど
スマホでテザリングしてる状態で
Alexaが使えるのか?

とりあえずSSHでログインしてシャットダウンがベスト
あとはBluetoothボタンが候補
あとは人感センサーか音声でシャットダウンが候補

動画については
raspividからFFmpegへパイプ入力してFFmpegのsegmentオプションで分割すれば、これらの問題がすべて簡単に解決
この方法なら録画した動画を一定時間毎に分割することも、ファイルの名前をそれぞれの録画を開始した時間にすることも、さらに拡張子をH.264からMP4に変換するのもすべて自動的に実行することが可能

例えば解像度1280×720、ビットレート2000kbps、フレームレート30fpsで録画して1分単位で分割すればファイルサイズは1つあたり約15MBなので、ピンポイントで転送すればWi-Fiでもそれほど時間をかけずに取り出せます。

ようやく実際に手を動かしてraspividからFFmpegへパイプ入力するスクリプトを実装
既にドラレコとしてraspividコマンドを実行するスクリプトを組んであるなら、それを書き換えるだけなのですごく簡単

#!/bin/sh

raspivid -o - -w 1280 -h 720 -t 0 -fps 30 -b 2000000 |
ffmpeg -r 30 -i - -vcodec copy \
-f segment -strftime 1 -segment_time 60 \
-segment_format_options movflags=+faststart -segment_format mp4 \
-reset_timestamps 1 \
/home/pi/%Y-%m-%d_%H-%M.mp4

スクリプトの完成系はこんな感じです。これをサービスとしてsystemdに登録しておけば、ラズパイが起動すると自動的に録画を開始

raspividのオプション
オプション 説明
-o 出力ファイル名
-w,-h 解像度
-t 録画時間
-fps フレームレート
-b ビットレート

取得した動画データはFFmpegに渡すので-oでは出力ファイル名を指定しません。録画時間に上限を設けないなら0で良いでしょう。解像度やビットレート等はお好みで。

必要なオプションを記述したら、|でFFmpegにパイプ入力

FFmpegのオプション
オプション 説明
-r フレームレート
-i 入力ファイル
-vcodec 動画のコーデック
-strftime 出力ファイル名に日時を使用するためのオプション
-segment_time 分割時間
-segment_format_options movflags=+faststart 動画のメタデータ情報を先頭に付与する
-segment_format 分割する動画のフォーマット
-reset_timestamps セグメントのタイムスタンプのリセット

4行目以降はFFmpegについての記述になります。見やすくするために適宜改行してありますが、もちろん不要なら改行しなくてもOKです。

フレームレートはraspividコマンドで指定した数字に合わせましょう。入力ファイルについては、今回はパイプ入力するので指定しません。動画の拡張子は変換しますがコーデックは変わらないのでcopyです。

-strftimeは出力ファイル名に日時を使用するためのオプションです。-segment_timeで何秒毎に分割するのか時間を指定します。

-segment_format_options movflags=+faststartを記述しておくと、動画の読み込みにかかる時間が短縮されて再生開始が早くなります。-segment_formatはそのままです

タイムスタンプをリセットせずにセグメントファイルとして保存すると、再生時に早送りやシークができなかったり何かと不便なことになります。リセットしておけば普通の独立した動画として再生することが可能なので、リセットしておきました。

最後に出力ファイル名の指定についてですが、今回使用しているのはDATEコマンドではないので書式が異なることに注意してください。-や_の区切り方などについては自由に書き換えて大丈夫

これをもとにファイルパスを変更し
角度を調整したのが以下のスクリプト

raspivid -o - -rot 270  -w 1280 -h 720 -t 0 -fps 30 -b 2000000 | ffmpeg -r 30 -i - -vcodec copy -f segment -strftime 1 -segment_time 60 -segment_format_options movflags=+faststart -segment_format mp4 -reset_timestamps 1 /home/snowpool/Videos/%Y-%m-%d_%H-%M.mp4

これで Videosディレクトリに1分ごとの動画が保存される

あとはこれを

sudo nano /opt/record.sh

へ記述して

問題がなければ、ラズパイの起動と同時に録画を開始するためにスクリプトをサービスとしてsystemdに登録

sudo nano /etc/systemd/system/record.service

中身は

[Unit]
Description = Drive Recorder

[Service]
ExecStart = /opt/record.sh #スクリプトのパス
Restart = always
Type = simple

[Install]
WantedBy = multi-user.target

登録が完了したらサービスを有効化、起動

sudo systemctl enable record.service

sudo systemctl start record.service

サービスが正常に起動してスクリプトが実行されたらひとまずOK

ubuntu touch へPython3.5以降をインストール

ubuntu touch へPython3.5以降をインストール

一度電源が落ちると
USB接続して

adb shell android-gadget-service enable ssh

を再度実行する必要がある

そして鍵認証でログイン

ssh -i .ssh/id_rsa_touch phablet@192.168.1.10https://codechacha.com/ja/ubuntu-install-python39/

Ubuntu – Python 3.9のインストール方法
を参考に

sudo apt update

を実行するが

[sudo] password for phablet:
無視:1 http://ports.ubuntu.com/ubuntu-ports xenial InRelease
無視:2 http://repo.ubports.com xenial InRelease
無視:3 http://ports.ubuntu.com/ubuntu-ports xenial-updates InRelease
エラー:4 http://repo.ubports.com xenial Release
ファイル /var/lib/apt/lists/partial/repo.ubports.com_dists_xenial_Release をオープンできませんでした - open (30: Read-only file system) [IP: 172.67.150.210 80]
無視:5 http://ports.ubuntu.com/ubuntu-ports xenial-security InRelease
エラー:6 http://ports.ubuntu.com/ubuntu-ports xenial Release
ファイル /var/lib/apt/lists/partial/ports.ubuntu.com_ubuntu-ports_dists_xenial_Release をオープンできませんでした - open (30: Read-only file system) [IP: 185.125.190.39 80]
エラー:7 http://ports.ubuntu.com/ubuntu-ports xenial-updates Release
ファイル /var/lib/apt/lists/partial/ports.ubuntu.com_ubuntu-ports_dists_xenial-updates_Release をオープンできませんでした - open (30: Read-only file system) [IP: 185.125.190.36 80]
エラー:8 http://ports.ubuntu.com/ubuntu-ports xenial-security Release
ファイル /var/lib/apt/lists/partial/ports.ubuntu.com_ubuntu-ports_dists_xenial-security_Release をオープンできませんでした - open (30: Read-only file system) [IP: 185.125.190.39 80]
パッケージリストを読み込んでいます... 完了
W: chmod 0700 of directory /var/lib/apt/lists/partial failed - SetupAPTPartialDirectory (30: Read-only file system)
W: 読み込み専用のロックファイル /var/lib/apt/lists/lock にロックは使用しません
W: システムにサンドボックスユーザ '_apt' がありません。権限を削除できません
E: リポジトリ http://repo.ubports.com xenial Release には Release ファイルがありません。
N: このようなリポジトリから更新を安全に行うことができないので、デフォルトでは更新が無効になっています。
N: リポジトリの作成とユーザ設定の詳細は、apt-secure(8) man ページを参照してください。
E: リポジトリ http://ports.ubuntu.com/ubuntu-ports xenial Release には Release ファイルがありません。
N: このようなリポジトリから更新を安全に行うことができないので、デフォルトでは更新が無効になっています。
N: リポジトリの作成とユーザ設定の詳細は、apt-secure(8) man ページを参照してください。
E: リポジトリ http://ports.ubuntu.com/ubuntu-ports xenial-updates Release には Release ファイルがありません。
N: このようなリポジトリから更新を安全に行うことができないので、デフォルトでは更新が無効になっています。
N: リポジトリの作成とユーザ設定の詳細は、apt-secure(8) man ページを参照してください。
E: リポジトリ http://ports.ubuntu.com/ubuntu-ports xenial-security Release には Release ファイルがありません。
N: このようなリポジトリから更新を安全に行うことができないので、デフォルトでは更新が無効になっています。
N: リポジトリの作成とユーザ設定の詳細は、apt-secure(8) man ページを参照してください。

となる

sudo apt install software-properties-common

を実行するが

パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています
状態情報を読み取っています... 完了
software-properties-common はすでに最新バージョン (0.96.20.10) です。
software-properties-common は手動でインストールしたと設定されました。
W: 読み込み専用のロックファイル /var/lib/dpkg/lock-frontend にロックは使用しません
W: 読み込み専用のロックファイル /var/lib/dpkg/lock にロックは使用しません
E: Could not create temporary file for /var/lib/apt/extended_states - mkstemp (30: Read-only file system)
E: 一時状態ファイル /var/lib/apt/extended_states の書き込みに失敗しました

となる
どうやら書き込み権限がないようなので

Google Nexus5 に Ubuntu Touch をインストールする。(第6版)
https://rfriends.hatenablog.com/entry/2020/05/02/110033#%EF%BC%93ssh%E3%81%AE%E6%9C%89%E5%8A%B9%E5%8C%96
を参考に

sudo mount -o rw,remount /

を実行し
root を r/w にする

再起動すると元に戻ってしまうので

sudo vi /etc/rc.local

でファイルを開く

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

exit 0

となっているので

mount -o rw,remount /

を最終行に追記し保存

これで再度

sudo apt update

をすればできたけど

アップグレードできるパッケージが 32 個あります。表示するには 'apt list --upgradable' を実行してください。
W: システムにサンドボックスユーザ '_apt' がありません。権限を削除できません

とでる

システムにサンドボックスユーザー「_apt」はありません。権限を削除できません
を参考に

sudo adduser _apt --force-badname

を実行し
すべてEnter

再度

sudo apt update

を実行し
エラーがでないのを確認

sudo add-apt-repository ppa:deadsnakes/ppa

でリポジトリ追加

sudo apt install python3.9

でインストール

しかし

パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています
状態情報を読み取っています... 完了
注意、regex 'python3.9' のために 'postgresql-plpython3-9.5' を選択します
以下の追加パッケージがインストールされます:
libpq5 postgresql-9.5 postgresql-client-9.5 postgresql-client-common
postgresql-common ssl-cert
提案パッケージ:
locales-all postgresql-doc-9.5 openssl-blacklist
推奨パッケージ:
postgresql-contrib-9.5 sysstat
以下のパッケージが新たにインストールされます:
libpq5 postgresql-9.5 postgresql-client-9.5 postgresql-client-common
postgresql-common postgresql-plpython3-9.5 ssl-cert
アップグレード: 0 個、新規インストール: 7 個、削除: 0 個、保留: 35 個。
3,638 kB のアーカイブを取得する必要があります。
この操作後に追加で 13.2 MB のディスク容量が消費されます。
続行しますか? [Y/n] y
取得:1 http://ports.ubuntu.com/ubuntu-ports xenial-updates/main armhf libpq5 armhf 9.5.25-0ubuntu0.16.04.1 [66.4 kB]
取得:2 http://ports.ubuntu.com/ubuntu-ports xenial-updates/main armhf postgresql-client-common all 173ubuntu0.3 [28.4 kB]
取得:3 http://ports.ubuntu.com/ubuntu-ports xenial-updates/main armhf postgresql-client-9.5 armhf 9.5.25-0ubuntu0.16.04.1 [800 kB]
取得:4 http://ports.ubuntu.com/ubuntu-ports xenial/main armhf ssl-cert all 1.0.37 [16.9 kB]
取得:5 http://ports.ubuntu.com/ubuntu-ports xenial-updates/main armhf postgresql-common all 173ubuntu0.3 [154 kB]
取得:6 http://ports.ubuntu.com/ubuntu-ports xenial-updates/main armhf postgresql-9.5 armhf 9.5.25-0ubuntu0.16.04.1 [2,537 kB]
取得:7 http://ports.ubuntu.com/ubuntu-ports xenial-updates/universe armhf postgresql-plpython3-9.5 armhf 9.5.25-0ubuntu0.16.04.1 [36.2 kB]
3,638 kB を 4秒 で取得しました (767 kB/s)
パッケージを事前設定しています ...
以前に未選択のパッケージ libpq5:armhf を選択しています。
(データベースを読み込んでいます ... 現在 51462 個のファイルとディレクトリがインストールされています。)
.../libpq5_9.5.25-0ubuntu0.16.04.1_armhf.deb を展開する準備をしています ...
libpq5:armhf (9.5.25-0ubuntu0.16.04.1) を展開しています...
以前に未選択のパッケージ postgresql-client-common を選択しています。
.../postgresql-client-common_173ubuntu0.3_all.deb を展開する準備をしています ...
postgresql-client-common (173ubuntu0.3) を展開しています...
以前に未選択のパッケージ postgresql-client-9.5 を選択しています。
.../postgresql-client-9.5_9.5.25-0ubuntu0.16.04.1_armhf.deb を展開する準備をしています ...
postgresql-client-9.5 (9.5.25-0ubuntu0.16.04.1) を展開しています...
以前に未選択のパッケージ ssl-cert を選択しています。
.../ssl-cert_1.0.37_all.deb を展開する準備をしています ...
ssl-cert (1.0.37) を展開しています...
以前に未選択のパッケージ postgresql-common を選択しています。
.../postgresql-common_173ubuntu0.3_all.deb を展開する準備をしています ...
'postgresql-common による /usr/bin/pg_config から /usr/bin/pg_config.libpq-dev への退避 (divert)' を追加しています
postgresql-common (173ubuntu0.3) を展開しています...
以前に未選択のパッケージ postgresql-9.5 を選択しています。
.../postgresql-9.5_9.5.25-0ubuntu0.16.04.1_armhf.deb を展開する準備をしています ...
postgresql-9.5 (9.5.25-0ubuntu0.16.04.1) を展開しています...
以前に未選択のパッケージ postgresql-plpython3-9.5 を選択しています。
.../postgresql-plpython3-9.5_9.5.25-0ubuntu0.16.04.1_armhf.deb を展開する準備をしています ...
postgresql-plpython3-9.5 (9.5.25-0ubuntu0.16.04.1) を展開しています...
libc-bin (2.23-0ubuntu11.3) のトリガを処理しています ...
ureadahead (0.100.0-19.1) のトリガを処理しています ...
ureadahead will be reprofiled on next reboot
systemd (229-4ubuntu21.28ubports2) のトリガを処理しています ...
libpq5:armhf (9.5.25-0ubuntu0.16.04.1) を設定しています ...
postgresql-client-common (173ubuntu0.3) を設定しています ...
postgresql-client-9.5 (9.5.25-0ubuntu0.16.04.1) を設定しています ...
update-alternatives: /usr/share/man/man1/psql.1.gz (psql.1.gz) を提供するために自動モードで /usr/share/postgresql/9.5/man/man1/psql.1.gz を使います
ssl-cert (1.0.37) を設定しています ...
postgresql-common (173ubuntu0.3) を設定しています ...
Adding user postgres to group ssl-cert

Creating config file /etc/postgresql-common/createcluster.conf with new version

Creating config file /etc/logrotate.d/postgresql-common with new version
Building PostgreSQL dictionaries from installed myspell/hunspell packages...
ERROR: no ecoding defined in /usr/share/hunspell/ar.aff, ignoring
iconv: conversion from `microsoft-cp1251' is not supported
Try `iconv --help' or `iconv --usage' for more information.
ERROR: Conversion of /usr/share/hunspell/bg_BG.aff failed
ca
ca_es-valencia
cs_cz
da_dk
de_de
el_gr
en_us
es
fa_ir
fr
gd_gb
he
hr_hr
hu_hu
iconv: illegal input sequence at position 131
ERROR: Conversion of /usr/share/hunspell/hu_HU.aff failed
it_it
ko
lt_lt
lv_lv
nb_no
nl
pl
pt
pt_br
ro_ro
ERROR: no ecoding defined in /usr/share/hunspell/ru_RU.aff, ignoring
sl_si
sr_latn_rs
sr_rs
sv_fi
sv_se
uk_ua
Removing obsolete dictionary files:
* No PostgreSQL clusters exist; see "man pg_createcluster"
postgresql-9.5 (9.5.25-0ubuntu0.16.04.1) を設定しています ...
Creating new cluster 9.5/main ...
config /etc/postgresql/9.5/main
data /var/lib/postgresql/9.5/main
locale en_US.UTF-8
initdb: could not create directory "/var/lib/postgresql/9.5/main/pg_xlog": No space left on device
initdb: removing contents of data directory "/var/lib/postgresql/9.5/main"
Error: initdb failed
Error: could not create default cluster. Please create it manually with

pg_createcluster 9.5 main --start

or a similar command (see 'man pg_createcluster').
update-alternatives: using /usr/share/postgresql/9.5/man/man1/postmaster.1.gz to provide /usr/share/man/man1/postmaster.1.gz (postmaster.1.gz) in auto mode
* No PostgreSQL clusters exist; see "man pg_createcluster"
postgresql-plpython3-9.5 (9.5.25-0ubuntu0.16.04.1) を設定しています ...
libc-bin (2.23-0ubuntu11.3) のトリガを処理しています ...
ureadahead (0.100.0-19.1) のトリガを処理しています ...
systemd (229-4ubuntu21.28ubports2) のトリガを処理しています ...

となる

あとpip
Ubuntu環境のPython ¦ pip ¦ 仮想環境

を参考に

sudo apt install python3-pip

でインストールできるはずだったが

パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています
状態情報を読み取っています... 完了
以下の追加パッケージがインストールされます:
python-pip-whl
推奨パッケージ:
build-essential python3-dev python3-setuptools python3-wheel
以下のパッケージが新たにインストールされます:
python-pip-whl python3-pip
アップグレード: 0 個、新規インストール: 2 個、削除: 0 個、保留: 35 個。
1,221 kB のアーカイブを取得する必要があります。
この操作後に追加で 1,791 kB のディスク容量が消費されます。
E: /var/cache/apt/archives/ に充分な空きスペースがありません。

となるため
cache を増やす必要がある

swap領域を拡張する
を参考に

cd /userdata
sudo swapoff SWAP.img
sudo fallocate -l 262144 SWAP.img
sudo mkswap SWAP.img

を実行すると

mkswap: SWAP.img: warning: wiping old swap signature.
Setting up swapspace version 1, size = 32 MiB (33550336 bytes)
no label, UUID=dd114233-087e-441c-9e25-90a353bdab97

となる

df

の結果は

Filesystem 1K-blocks Used Available Use% Mounted on
udev 913144 4 913140 1% /dev
tmpfs 184804 728 184076 1% /run
/dev/mmcblk0p30 12794436 2982388 9160584 25% /userdata
/dev/loop0 2015824 2001036 0 100% /
/dev/loop1 120296 120244 52 100% /android/system
none 4 0 4 0% /android
tmpfs 924012 4 924008 1% /etc/fstab
tmpfs 924012 948 923064 1% /var/lib/lxc/android/rootfs/dev/disk/by-partlabel/cache 564988 10068 554920 2% /android/cache/dev/disk/by-partlabel/persist 14800 4332 10468 30% /android/persist
none 4 0 4 0% /sys/fs/cgroup
tmpfs 924012 12 924000 1% /tmp
none 5120 0 5120 0% /run/lock
none 924012 164 923848 1% /run/shm
none 102400 0 102400 0% /run/user
tmpfs 924012 0 924012 0% /media
cgmfs 100 0 100 0% /run/cgmanager/fs
tmpfs 924012 0 924012 0% /var/lib/openvpn/chroot/tmp
tmpfs 924012 0 924012 0% /var/lib/sudo
tmpfs 184804 0 184804 0% /run/user/0
tmpfs 184804 40 184764 1% /run/user/32011

sudo swapon SWAP.img

次にシステムイメージの拡張

sudo losetup /dev/loop0

/dev/loop0: [45854]:16 (/userdata/system.img)

となる

このコマンドは
loop デバイスの設定と制御

今回はオプションなしなので
/dev/loop0 の情報の取得

その他オプションについては

losetup – システム管理コマンドの説明 – Linux コマンド集 一覧表
を参考に

sudo blockdev --getsize64 /dev/loop0

2097152000

このコマンドは
コマンドラインからブロックデバイスの ioctl を呼び出す

https://kazmax.zpp.jp/cmd/b/blockdev.8.html
を参考に

–getsize オプションにより
デバイスの容量を (512 バイトセクタ単位で) 表示

次に

sudo truncate -s 2684354560 /userdata/system.img


ファイルサイズを変える

【 truncate 】コマンド――ファイルを指定したサイズに変える
-s オプションでサイズを指定

次に

sudo losetup --set-capacity /dev/loop0


ループバックデバイスのサイズを変更

これらのオプションについては

losetupコマンドの使い方
を参考に

ここまでできたら
Nexus 7 をリカバリモードにする

音量大、音量小、電源の 3 つのボタンを押しながら起動

Recovery modeを選択し、電源キーを押す

ubuntu で

adb devices

を実行すると

List of devices attached
09fed9ec recovery

となっているので

adb shell losetup /dev/block/loop0/data/system.img

を実行したが

losetup: /dev/block/loop0: No such file or directory

となってしまった

[/shell]
sudo du -sh /var/cache/apt/archives/
[/shell]

で容量を確認したけど

8.0K /var/cache/apt/archives/

となり
たしかに足りない

6.rfriendsのインストール
を参考に

aptcacheディレクトリの容量が少ないので、ホームディレクトリに変更

mkdir -p ~/aptcache
sudo mount --bind /home/phablet/aptcache/var/cache/apt
sudo vi /etc/rc.local


最終行だと反映されていなかったので

exit 0

の前に

mount --bind /home/phablet/aptcache/var/cache/apt

を追記して保存

sudo apt install python3-pip

でインストール

pip3 install pyttsx3

でパッケージを追加

しかし
そのままだとバージョンが古い

pip3 install --upgrade pip

でアップデート

しかし

pip3 install pyttsx3

を実行すると

Traceback (most recent call last):
File "/usr/bin/pip3", line 11, in <module>
sys.exit(main())
File "/home/phablet/.local/lib/python3.5/site-packages/pip/__init__.py", line 11, in main
from pip._internal.utils.entrypoints import _wrapper
File "/home/phablet/.local/lib/python3.5/site-packages/pip/_internal/utils/entrypoints.py", line 12
f"pip{sys.version_info.major}",
^
SyntaxError: invalid syntax

となってしまう

pip 実行時に sys.stderr.write(f”ERROR: {exc} “) とエラーが出てpipを実行できないときの対処方法
によれば
pip21 から python3.6 からの機能を使っているかららしい

python3 -V

を実行したら
[/shell]
Python 3.5.2[/shell]

sudo apt-get install python3

を実行したけど
python3 はすでに最新バージョン (3.5.1-3) です。
となる

【初心者向け】Pythonのインストール手順(Ubuntu)
を参考に
[/shell]
sudo apt install git[/shell]

を実行したがインストールできなかった

W: リポジトリ http://ppa.launchpad.net/deadsnakes/ppa/ubuntu xenial Release には Release ファイルがありません。
N: このようなリポジトリから取得したデータは認証できないので、データの使用は潜在的に危険です。
N: リポジトリの作成とユーザ設定の詳細は、apt-secure(8) man ページを参照してください。
W: リポジトリ http://ports.ubuntu.com/ubuntu-ports xenial-updates Release には Release ファイルがありません。
N: このようなリポジトリから取得したデータは認証できないので、データの使用は潜在的に危険です。
N: リポジトリの作成とユーザ設定の詳細は、apt-secure(8) man ページを参照してください。
W: リポジトリ http://ports.ubuntu.com/ubuntu-ports xenial-security Release には Release ファイルがありません。
N: このようなリポジトリから取得したデータは認証できないので、データの使用は潜在的に危険です。
N: リポジトリの作成とユーザ設定の詳細は、apt-secure(8) man ページを参照してください。
E: http://ppa.launchpad.net/deadsnakes/ppa/ubuntu/dists/xenial/main/binary-armhf/Packages の取得に失敗しました 出力ファイルへの書き込みでエラーが発生しました - write (28: No space left on device) ファイルへの書き込みでエラーが発生しました - write (28: No space left on device) [IP: 185.125.190.52 80]
E: http://ports.ubuntu.com/ubuntu-ports/dists/xenial-updates/main/source/Sources の取得に失敗しました 出力ファイルへの書き込みでエラーが発生しました - write (28: No space left on device) ファイルへの書き込みでエラーが発生しました - write (28: No space left on device) [IP: 185.125.190.39 80]
E: http://ports.ubuntu.com/ubuntu-ports/dists/xenial-security/main/source/Sources の取得に失敗しました 出力ファイルへの書き込みでエラーが発生しました - write (28: No space left on device) ファイルへの書き込みでエラーが発生しました - write (28: No space left on device) [IP: 185.125.190.39 80]
E: いくつかのインデックスファイルのダウンロードに失敗しました。これらは無視されるか、古いものが代わりに使われます。

どうやらリポジトリ関連の問題らしい

【Ubuntu】PPAを追加・削除する方法について

ubuntu add-apt-repository ppa エラー:リポジトリの作成とユーザ設定の詳細は、apt-secure(8) man ページを参照してください。

を参考にリポジトリをいじる

とりあえず

Ubuntu 20.10でapt-get updateしたらエラーが出た
で似たような症状が載っていた

自分の場合
http://ports.ubuntu.com/ubuntu-ports/dists/xenial/universe/i18n/Translation-jahttp://ports.ubuntu.com/ubuntu-ports/dists/xenial-updates/main/source/Sourceshttp://ports.ubuntu.com/ubuntu-ports/dists/xenial-security/main/source/Sources

の3つの取得に失敗している

また

How can I install Python 3.8 on Ubuntu 16.04? (ppa:deadsnakes doesn’t support Ubuntu 16.04 anymore)
にあるように 

ppa:deadsnakes doesn't support Ubuntu 16.04 anymore

となっていて
サポート対象外のため
リポジトリを追加してもインストールはできない

Wi Fi が使えないので再起動

sudo mount -o rw,remount /
sudo mount --bind /home/phablet/aptcache/var/cache/apt

をしないと書き込み権限がないのと
空き容量不足でエラーになる

sudo rm -rf /var/lib/apt/lists/*
sudo apt update
sudo apt -f install

のあとに

sudo apt autoremove

そして

sudo apt remove python3-pip

で一度パッケージを削除

lsb_release -a

で ubuntu のバージョンを確認

No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 16.04.7 LTS
Release: 16.04
Codename: xenial

Ubuntu 20.10でapt-get updateしたらエラーが出た

サポートが切れたubuntu 20.10 での対処方法が載っていたので

cat /etc/apt/sources.list | grep -v "#"

を実行

deb http://ports.ubuntu.com/ubuntu-ports/ xenial main restricted
deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial main restricted

deb http://ports.ubuntu.com/ubuntu-ports/ xenial-updates main restricted
deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-updates main restricted

deb http://ports.ubuntu.com/ubuntu-ports/ xenial universe
deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial universe
deb http://ports.ubuntu.com/ubuntu-ports/ xenial-updates universe
deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-updates universe


deb http://ports.ubuntu.com/ubuntu-ports/ xenial-security main restricted
deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-security main restricted
deb http://ports.ubuntu.com/ubuntu-ports/ xenial-security universe
deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-security universe

みなれない
deb-src
があったので検索

aptで使うsources.listのオプションいろいろ
によれば

「deb」で始まるのはバイナリパッケージ
「⁠deb-src」で始まるのはソースパッケージを提供するリポジトリ

普段使う分には、バイナリパッケージだけで十分
これは
ソースパッケージリポジトリを有効化すると
その分だけダウンロードするメタデータの情報なども増えるから

パッケージングなど特別な理由がない限りはdeb-srcを有効化しなくて良い

とのこと

とりあえず気にせず続行する

次に
http://old-releases.ubuntu.com/ubuntu/dists/

xenial
があるか確認するが存在しない

https://ubuntu.com/about/release-cycle
でバージョンとコードネームを元に調べたら
20.10 以上のものしかない

このためこの方法は使えない

vim も apt でインストールできないので
一度PCでも調べることにする

cat /etc/apt/sources.list | grep -v "#"

の結果は

deb http://jp.archive.ubuntu.com/ubuntu/ xenial main restricted

deb http://jp.archive.ubuntu.com/ubuntu/ xenial-updates main restricted

deb http://jp.archive.ubuntu.com/ubuntu/ xenial universe
deb http://jp.archive.ubuntu.com/ubuntu/ xenial-updates universe

deb http://jp.archive.ubuntu.com/ubuntu/ xenial multiverse
deb http://jp.archive.ubuntu.com/ubuntu/ xenial-updates multiverse

deb http://jp.archive.ubuntu.com/ubuntu/ xenial-backports main restricted universe multiverse


deb http://security.ubuntu.com/ubuntu xenial-security main restricted
deb http://security.ubuntu.com/ubuntu xenial-security universe
deb http://security.ubuntu.com/ubuntu xenial-security multiverse
deb http://download.virtualbox.org/virtualbox/debian xenial contrib
deb http://download.ebz.epson.net/dsc/op/stable/debian/ lsb3.2 main
deb https://dl.winehq.org/wine-builds/ubuntu/ xenial main
deb [arch=amd64] https://download.virtualbox.org/virtualbox/debian xenial contrib
deb https://download.virtualbox.org/virtualbox/debian xenial contrib
deb https://typora.io/linux ./
deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/ /
deb http://www.geogebra.net/linux/ stable main
deb [arch=amd64] https://apt.releases.hashicorp.com xenial main
(base) snowpool@snowpool-Prime-Series:~$ sudo apt update
[sudo] snowpool のパスワード:
取得:1 file:/var/cuda-repo-9-0-local InRelease
無視:1 file:/var/cuda-repo-9-0-local InRelease
取得:2 file:/var/cuda-repo-9-0-local Release [574 B]
取得:2 file:/var/cuda-repo-9-0-local Release [574 B]
無視:4 http://download.ebz.epson.net/dsc/op/stable/debian lsb3.2 InRelease
ヒット:5 http://download.virtualbox.org/virtualbox/debian xenial InRelease
ヒット:6 http://download.ebz.epson.net/dsc/op/stable/debian lsb3.2 Release
ヒット:7 http://archive.ubuntulinux.jp/ubuntu xenial InRelease
ヒット:8 http://dl.google.com/linux/chrome/deb stable InRelease
無視:9 http://archive.ubuntulinux.jp/ubuntu-ja-non-free xenial InRelease
取得:10 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64 InRelease [1,581 B]
ヒット:11 http://packages.microsoft.com/repos/code stable InRelease
ヒット:12 https://apt.releases.hashicorp.com xenial InRelease
ヒット:13 http://archive.ubuntulinux.jp/ubuntu-ja-non-free xenial Release
ヒット:16 https://download.virtualbox.org/virtualbox/debian xenial InRelease
取得:17 http://download.virtualbox.org/virtualbox/debian xenial/contrib amd64 Packages [2,312 B]
取得:18 https://typora.io/linux ./ InRelease [793 B]
エラー:10 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64 InRelease
公開鍵を利用できないため、以下の署名は検証できませんでした: NO_PUBKEY A4B469963BF863CC
ヒット:20 https://packages.cloud.google.com/apt cloud-sdk InRelease
エラー:14 https://dl.winehq.org/wine-builds/ubuntu xenial InRelease
公開鍵を利用できないため、以下の署名は検証できませんでした: NO_PUBKEY 76F1A20FF987672F
取得:21 http://www.geogebra.net/linux stable InRelease [8,690 B]
取得:22 http://security.ubuntu.com/ubuntu xenial-security InRelease [99.8 kB]
ヒット:23 http://jp.archive.ubuntu.com/ubuntu xenial InRelease
取得:24 https://download.virtualbox.org/virtualbox/debian xenial/contrib amd64 Packages [2,312 B]
取得:25 http://jp.archive.ubuntu.com/ubuntu xenial-updates InRelease [99.8 kB]
ヒット:26 http://ppa.launchpad.net/alessandro-strada/ppa/ubuntu xenial InRelease
ヒット:27 http://ppa.launchpad.net/alex-p/tesseract-ocr/ubuntu xenial InRelease
取得:28 https://esm.ubuntu.com/infra/ubuntu xenial-infra-security InRelease [7,524 B]
取得:29 https://esm.ubuntu.com/infra/ubuntu xenial-infra-updates InRelease [7,475 B]
取得:30 http://jp.archive.ubuntu.com/ubuntu xenial-backports InRelease [97.4 kB]
ヒット:31 http://ppa.launchpad.net/chris-lea/redis-server/ubuntu xenial InRelease
ヒット:32 http://ppa.launchpad.net/clipgrab-team/ppa/ubuntu xenial InRelease
ヒット:33 http://ppa.launchpad.net/eugenesan/ppa/ubuntu xenial InRelease
ヒット:34 http://ppa.launchpad.net/git-core/ppa/ubuntu xenial InRelease
ヒット:35 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu xenial InRelease
ヒット:36 http://ppa.launchpad.net/hluk/copyq/ubuntu xenial InRelease
ヒット:37 http://ppa.launchpad.net/inkscape.dev/stable/ubuntu xenial InRelease
ヒット:38 http://ppa.launchpad.net/jonathonf/ffmpeg-4/ubuntu xenial InRelease
ヒット:39 http://ppa.launchpad.net/jonathonf/vim/ubuntu xenial InRelease
ヒット:40 http://ppa.launchpad.net/jonathonf/vlc-3/ubuntu xenial InRelease
ヒット:41 http://ppa.launchpad.net/nixnote/nixnote2-daily/ubuntu xenial InRelease
ヒット:42 http://ppa.launchpad.net/stebbins/handbrake-releases/ubuntu xenial InRelease
ヒット:43 http://ppa.launchpad.net/thomas-schiex/blender/ubuntu xenial InRelease
ヒット:44 http://ppa.launchpad.net/ubuntu-desktop/ubuntu-make/ubuntu xenial InRelease
ヒット:45 http://ppa.launchpad.net/videolan/master-daily/ubuntu xenial InRelease
ヒット:46 http://ppa.launchpad.net/webupd8team/atom/ubuntu xenial InRelease
ヒット:47 http://ppa.launchpad.net/webupd8team/java/ubuntu xenial InRelease
パッケージリストを読み込んでいます... 完了
W: ターゲット Packages (contrib/binary-amd64/Packages) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット Packages (contrib/binary-all/Packages) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット Translations (contrib/i18n/Translation-ja_JP) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット Translations (contrib/i18n/Translation-ja) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット Translations (contrib/i18n/Translation-en) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット DEP-11 (contrib/dep11/Components-amd64.yml) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット DEP-11-icons (contrib/dep11/icons-64x64.tar) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット Packages (main/binary-amd64/Packages) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット Packages (main/binary-i386/Packages) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット Packages (main/binary-all/Packages) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット Translations (main/i18n/Translation-ja_JP) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット Translations (main/i18n/Translation-ja) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット Translations (main/i18n/Translation-en) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット DEP-11 (main/dep11/Components-amd64.yml) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット DEP-11-icons (main/dep11/icons-64x64.tar) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: http://download.ebz.epson.net/dsc/op/stable/debian/dists/lsb3.2/Release.gpg: 鍵 E5220FB7014D0FBDA50DFC2BE5E86C008AA65D56 による署名は弱い digest アルゴリズム (SHA1) を使用しています
W: GPG エラー: https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64 InRelease: 公開鍵を利用できないため、以下の署名は検証できませんでした: NO_PUBKEY A4B469963BF863CC
E: リポジトリ https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64 InRelease は署名されていません。
N: このようなリポジトリから更新を安全に行うことができないので、デフォルトでは更新が無効になっています。
N: リポジトリの作成とユーザ設定の詳細は、apt-secure(8) man ページを参照してください。
W: 署名照合中にエラーが発生しました。リポジトリは更新されず、過去のインデックスファイルが使われます。GPG エラー: https://dl.winehq.org/wine-builds/ubuntu xenial InRelease: 公開鍵を利用できないため、以下の署名は検証できませんでした: NO_PUBKEY 76F1A20FF987672F
E: /var/lib/apt/lists/partial/download.virtualbox.org_virtualbox_debian_dists_xenial_contrib_binary-amd64_Packages の状態を取得するのに失敗しました - pkgAcqTransactionItem::TransactionState-stat (2: そのようなファイルやディレクトリはありません)
W: ターゲット Packages (contrib/binary-amd64/Packages) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット Packages (contrib/binary-all/Packages) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット Translations (contrib/i18n/Translation-ja_JP) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット Translations (contrib/i18n/Translation-ja) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット Translations (contrib/i18n/Translation-en) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット DEP-11 (contrib/dep11/Components-amd64.yml) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット DEP-11-icons (contrib/dep11/icons-64x64.tar) は /etc/apt/sources.list:60 と /etc/apt/sources.list:62 で複数回設定されています
W: ターゲット Packages (main/binary-amd64/Packages) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット Packages (main/binary-i386/Packages) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット Packages (main/binary-all/Packages) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット Translations (main/i18n/Translation-ja_JP) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット Translations (main/i18n/Translation-ja) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット Translations (main/i18n/Translation-en) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット DEP-11 (main/dep11/Components-amd64.yml) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: ターゲット DEP-11-icons (main/dep11/icons-64x64.tar) は /etc/apt/sources.list:67 と /etc/apt/sources.list.d/geogebra.list:3 で複数回設定されています
W: Duplicate sources.list entry https://download.virtualbox.org/virtualbox/debian xenial Release

となっている

そういえば vim は ppa リポジトリを追加して
ubuntu 16 へインストールしたので
ubuntu touch でもできるか検証

vim8のインストール方法
を参考に

リポジトリを追加し

sudo apt install vim

としたが

パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています
状態情報を読み取っています... 完了
インストールすることができないパッケージがありました。おそらく、あり得
ない状況を要求したか、(不安定版ディストリビューションを使用しているの
であれば) 必要なパッケージがまだ作成されていなかったり Incoming から移
動されていないことが考えられます。
以下の情報がこの問題を解決するために役立つかもしれません:

以下のパッケージには満たせない依存関係があります:
vim : 依存: libcanberra0 (>= 0.2) しかし、インストールすることができません
E: 問題を解決することができません。壊れた変更禁止パッケージがあります。


sudo apt install libcanberra0
を実行しても
パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています
状態情報を読み取っています... 完了
パッケージ libcanberra0 は使用できませんが、別のパッケージから参照されます。
これは、パッケージが欠落しているか、廃止されたか、または別のソース
からのみ利用可能であることを意味します。

E: パッケージ 'libcanberra0' にはインストール候補がありません

となる

sudo add-apt-repository --remove ppa:jonathonf/vim

でとりあえず削除

かなり悩んだ結果

ubuntu touch install git

で検索し

anyone know how to install git
によれば
Ubuntu Touch の
OpenStore
を開いて
Seabass2
をインストールして
Libertineコンテナを作成すれば
最新版ではないけど
git がインストールできるらしいので実行

しかし途中でエラーになりとまるので
再インストールし
設定 > リセット > Erase& Reset All
で削除し再起動

Ubuntu Touch その140 – Ubuntu Touch OTA-23のテスト呼びかけ・Ubuntu Touch OTA-23のリリース予定日

を参考に
OSが最新版であるのを確認するため

設定 > 更新
で最新であるのを確認後

再度
SeaBass2 をインストール

このアプリは

anyone know how to install git
で紹介されていて
Liberine container を作成して
git などをいれるらしい

Libertine:UbuntuTouchにデスクトップアプリケーションをインストールする方法

Libertine の紹介がされている

コンテナなので、docker みたいに本体には影響がないのかもしれない

Ubuntu Touch をNexus5にインストールする方法
によれば

Andbox を使えば Android アプリもインストールが可能らしい

インストールに関しては

Android apps
を参考に

ubuntu touch へ ssh 接続

ubuntu touch へ ssh 接続

Generating public/private rsa key pair.
Enter file in which to save the key (/home/snowpool/.ssh/id_rsa):
/home/snowpool/.ssh/id_rsa already exists.
Overwrite (y/n)? n

となるので
ファイル名を指定して鍵を生成することにする

ssh-keygenでファイル名を指定して鍵を生成する
を参考に
-f ファイル名
をつければOK

ssh-keygen -t rsa -f id_rsa_touch

として

Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):


Enter

Enter same passphrase again:


Enter でOK

mv id_rsa_touch* .ssh/


.ssh ディレクトリに移動しておく

次に
Nexus7 で
システム設定  > アプリについて

開発者モードをONにする

これで Ubuntu と Nexus 7 を USBで接続し
ubuntu 側から端末で操作していく

adb devices

を実行し

* daemon not running. starting it now on port 5037 *
* daemon started successfully *
List of devices attached
09fed9ec unauthorized

というように認識されればOK

次に

adb shell android-gadget-service enable ssh

を実行

もし

error: device unauthorized. Please check the confirmation dialog on your device.

となったら
USBデバッグがONになっていない可能性がある

この場合USBデバッグを許可するか聞かれるダイアログがでてくるので
これを許可し
再度実行すれば成功する

adb shell mkdir /home/phablet/.ssh

でディレクトリを作成

adb push ~/.ssh/id_rsa_touch.pub/home/phablet/.ssh/authorized_keys

で鍵ファイルを転送

adb shell chown -R phablet.phablet /home/phablet/.ssh
adb shell chmod 700 /home/phablet/.ssh

で権限と所有者を変更

adb shell ip addr show wlan0|grep inet


IPアドレスを表示

今回の場合は

inet 192.168.1.10/24 brd 192.168.1.255 scope global wlan0
inet6 fe80::da50:e6ff:fe75:4fb3/64 scope link

これで接続しようとしたけど

ssh pablet@192.168.1.255

としたら

ssh: connect to host 192.168.1.255 port 22: Network is unreachable

となる

突然「ssh: connect to host ip アドレス port 22: Connection refused」が発生した場合の原因調査と対処法
をみたりしたけど
単純にIPアドレスを間違えていただけだった

ssh pablet@192.168.1.10

を実行したが

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
SHA256:HykJZUEwWspFZp9UbRUWgwSS+wYpJb/IHwXwj6XUVz4.
Please contact your system administrator.
Add correct host key in /home/snowpool/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /home/snowpool/.ssh/known_hosts:16
remove with:
ssh-keygen -f "/home/snowpool/.ssh/known_hosts" -R 192.168.1.10
RSA host key for 192.168.1.10 has changed and you have requested strict checking.
Host key verification failed.

となる

原因を調べると

ssh接続をする際に「WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!」と出てつながらない
にあるように

ssh-keygen -R 192.168.1.10

で一度情報を削除

原因は検証のため
virtualbox で仮想マシンを大量に作っていたので
IPが重複していたため

再度

ssh pablet@192.168.1.10

を実行すると

The authenticity of host '192.168.1.10 (192.168.1.10)' can't be established.
RSA key fingerprint is SHA256:HykJZUEwWspFZp9UbRUWgwSS+wYpJb/IHwXwj6XUVz4.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.10' (RSA) to the list of known hosts.
Received disconnect from 192.168.1.10 port 22:2: Too many authentication failures
Connection to 192.168.1.10 closed by remote host.
Connection to 192.168.1.10 closed.

で弾かれる

Google Nexus5 に Ubuntu Touch をインストールする。(第6版)
を参考に

adb shell chmod 600 /home/phablet/.ssh/authorized_keys

でパーミッションを変更したら無事にssh でのログインが可能になった

Nexus7 2013 Wifi を ubuntu touch にする

Nexus7 2013 Wifi を ubuntu touch にする

まず Nexus7 の写真などをバックアップしておく
USBで接続し
USBの使用をファイル転送にして
ubuntu で

mkdir ~/Nexus7_back
cp -rp ../DCIM/* ~/Nexus7_back/

でバックアップをとっておく

本体のバックアップをとっておきたいのなら

Nexus5バックアップ-GoogleのNexus5のデータをバックアップする2つの方法
にあるように
Google アカウントで
Nexus 7 のデータをバックアップしておく

サイトでは Nexus 5 だが
Nexus 7 でも同様に
設定 > バックアップとリセット
の設定でできた

次にカスタムROMを入れるには
Nexus 7のブートローダーアンロックが必要なので

Nexus 7のブートローダーアンロック(Bootloader Unlock)方法。
を参考に

Nexus7 Toolkit をインストールしようと調べたが
ubuntu の場合コマンドからできる

Nexus 7 に Ubuntu 13.04 を入れるの記
を参考に

sudo apt-get install android-tools-adb
sudo apt-get install android-tools-fastboot

が必要らしいが
すでに Android 開発環境を作っていたので
インストール済みだった

adb devices

* daemon not running. starting it now on port 5037 *
* daemon started successfully *
List of devices attached
09fed9ec unauthorized

となれば接続はされている

adb reboot bootloader

を実行すると
Nexus 7 が再起動するので

sudo fastboot oem unlock


ubuntu で実行すると
Unlock bootloader
の画面になるので

Nexus7 の音量ボタンの上を押すと
Yes になるので
電源ボタンを押す


(bootloader) The bootloader is already unlocked!
OKAY [ 0.002s]
finished. total time: 0.002s

となっているので成功しているはず

次に

Nexus7 2013にUbuntu Touchをインストールしてみた
を参考に実践

adb devices

を実行してもリストがでないため
初期化されたNexus7 のセットアップを行う

認証関連はほぼスキップして
起動したら
設定から
タブレット情報 > ビルド番号を7回タップ

これで設定の中に開発者向けオプションがでるので
USBデバッグを有効化

これで

adb devices

を実行すると

List of devices attached
09fed9ec device

と再び認識できるようになったので

ubportsはUSB接続したAndroidデバイスに
Ubuntu Touchのイメージを書き込んでくれるアプリ

これをダウンロードする

https://ubports.com/
へアクセスし
下へスクロール

get Ubuntu Touch をクリック

download installer をクリック

下へスクロールし
任意のOSでのインストーラーをダウンロード
今回は
.deb 形式を使用する

なお以前すでにインストールしたことがあり
依存パッケージがないとエラーになるので注意

先にインストールしようとして

sudo dpkg -i ubports-installer_0.9.7-beta_linux_amd64.deb

を実行したが

以前に未選択のパッケージ ubports-installer を選択しています。
(データベースを読み込んでいます ... 現在 346166 個のファイルとディレクトリがインストールされています。)
ubports-installer_0.9.7-beta_linux_amd64.deb を展開する準備をしています ...
ubports-installer (0.9.7-beta) を展開しています...
dpkg: 依存関係の問題により ubports-installer の設定ができません:
ubports-installer は以下に依存 (depends) します: android-tools-fastboot ...しかし:
パッケージ android-tools-fastboot はまだインストールされていません。
ubports-installer は以下に依存 (depends) します: heimdall-flash ...しかし:
パッケージ heimdall-flash はまだインストールされていません。

dpkg: パッケージ ubports-installer の処理中にエラーが発生しました (--install):
依存関係の問題 - 設定を見送ります
desktop-file-utils (0.22-1ubuntu5.2) のトリガを処理しています ...
gnome-menus (3.13.3-6ubuntu3.1) のトリガを処理しています ...
bamfdaemon (0.5.3~bzr0+16.04.20180209-0ubuntu1) のトリガを処理しています ...
Rebuilding /usr/share/applications/bamf-2.index...
mime-support (3.59ubuntu1) のトリガを処理しています ...
hicolor-icon-theme (0.15-0ubuntu1.1) のトリガを処理しています ...
処理中にエラーが発生しました:
ubports-installer

となるので
LinuxMintで、adb、fastbootコマンドを使用できるようにする
https://toshio-web.com/linuxmint-adb-fastboot
を参考に

sudo apt install android-tools-adb android-tools-fastboot

としたが

パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています
状態情報を読み取っています... 完了
android-tools-adb はすでに最新バージョン (5.1.1r36+git20160322-0ubuntu3) です。
以下の問題を解決するために 'apt-get -f install' を実行する必要があるかもしれません:
以下のパッケージには満たせない依存関係があります:
ubports-installer : 依存: heimdall-flash しかし、インストールされようとしていません
E: 未解決の依存関係です。'apt-get -f install' を実行してみてください (または解法を明示してください)。

となる

apt-get -f install

を実行後に

sudo dpkg -i ubports-installer_0.9.7-beta_linux_amd64.deb

を実行

これでインストールできたので

ubports-installer

を実行すると
インストーラーが起動する

デバイスがunlock されているか確認画面になるので
My device is unlocked
をクリック

デバイスへの書き込みに対しての警告がでるが
気にせず
Set up rules automatically
をクリック

管理者権限が必要なので
ubuntu ユーザパスワードを入力し
install をクリック

continue をクリック

インストールオプションは変更せず
OKをクリック

しかし途中でエラーとなるため
try again をクリック

このときのエラーは

info: Welcome to the UBports Installer version 0.9.7-beta!
[8991:1126/061016.240532:ERROR:gpu_memory_buffer_support_x11.cc(44)] dri3 extension not supported.
info: device detected: flo
info: Installing Ubuntu Touch on your Nexus 7 2013 WiFi (flo)
info: configuring...
info: settings: {"format":false,"bootstrap":true,"channel":"ubports-touch/16.04/stable"}
info: Downloading 2 files
info: Downloaded file 1 of 2
info: Downloaded file 2 of 2
error: Error: adb:format: Error: failed to format cache: Error: failed to mount: mount: mounting /dev/block/platform/msm_sdcc.1/by-name/cache on /cache failed: Device or resource busy
stack trace: Error: failed to format cache: Error: failed to mount: mount: mounting /dev/block/platform/msm_sdcc.1/by-name/cache on /cache failed: Device or resource busy
at /opt/ubports-installer/resources/app.asar.unpacked/node_modules/promise-android-tools/lib/module.cjs:678:15
at /opt/ubports-installer/resources/app.asar.unpacked/node_modules/promise-android-tools/node_modules/cancelable-promise/dist/CancelablePromise.js:27:18
at process.processTicksAndRejections (node:internal/process/task_queues:96:5)
warn: restart after error
info: Downloading 12 files
info: Downloaded file 1 of 12
info: Downloaded file 2 of 12
info: Downloaded file 3 of 12
info: Downloaded file 4 of 12
info: Downloaded file 5 of 12
info: Downloaded file 6 of 12
info: Downloaded file 7 of 12
info: Downloaded file 8 of 12
info: Downloaded file 9 of 12
info: Downloaded file 10 of 12
info: Downloaded file 11 of 12
info: Downloaded file 12 of 12
info: All done! Your device will now reboot and complete the installation. Enjoy exploring Ubuntu Touch!
info: Good bye!

再度実行したら無事にインストールされた

途中でエラーレポートについてでてくるので
FAIL をクリックすればok

経済指標の値の取得と計算

経済指標の値の取得と計算

とりあえず経済指標の基準値は調べたので

まずは売買するロジックを作成する

経済指標で結果が予測値より悪いなら売り

結果が予想より良いのなら書い

という簡単なロジックを実装する

def dealing_logic(forecast,actual_news):

    deal_flag = actual_news - forecast

    if deal_flag <0:

        print("売り")

    else:

        print("書い")

まずは簡単に実験

forecast = 962

actual = 853

dealing_logic(forecast,actual)

で売りになったので

次は
マイナスの値で
マイナスの値でも動作するのを確認

次に判定
フラグ変数を用意し

経済指標
債権
株価指数
Vix
といった値で売買判定をする

Vix は警戒とかはマイナスの値を多くすることにする

つまり

Vix は0〜100で
20までは安定しているとみるので

値を0
30で警戒なので-1
40を超えたらパニックなので-2
50 以上はリーマンショッククラスなので-3
とする

このように結果をもとにして

判定するフラグのトータルが+なら書い

マイナスなら売りとする

ダウの下げとかを気にするのではなく

これらをフラグとしておけば市場の数値ではなく

売り買いのみの判定に使える

https://note.nkmk.me/python-pandas-read-excel/

をみた感じだと

read_excel()

Pandas でexcel を読み込んでいる

Vix の取得は

import investpy

from datetime import datetime, date, timedelta

from dateutil.relativedelta import relativedelta

import altair as alt

import pandas as pd



today = datetime.today().strftime('%d/%m/%Y')



vix = investpy.get_index_historical_data(index='S&P 500 VIX',country='united states',

                                        from_date='01/01/2010',to_date=today)



vix.loc["2022-06-02"]["High"]

25.78

と Hight の値を取得できた

あとは日付の部分を自動で取得したいので

index_date に格納して指定する

index_today = datetime.today().strftime('%Y-%m-%d')

vix.loc[index_today]["High"]

としても同じ

25.78

となったので成功

問題はこれが数値か文字列かによるので

if flag_vix > 50:

    print("市場はパニック")

elif flag_vix > 20:

    print("市場は正常")

で判定できているので数字になっている

同様に経済指標カレンダーの

Forecast actual previous

の値も取り出してみる

あとtwitter で取得したツイート内容の切り出し

数字以外は削除しないと比較できない

とりあえず  broomberg のツイートを取得し

不要な部分を削除し経済指標の数値のみにする

https://teratail.com/questions/266272
によれば

特定ユーザの特定キーワード検索が可能

for tweet in tweepy.Cursor(api.search, q='"2020年05月28日" from:@TakumiSoftware').items(10):

    if (tweet.text[:2] == 'RT'): continue



    print(tweet.user.name)

    print(tweet.text)

    print('-----------------------------------------------')


しかしエラーになる

api.search_tweets(q='"RBA Rate Statemen"', lang='ja', result_type='recent',count=12)

もだめ

api.search_tweets(q='"#経済指標"', lang='ja', result_type='recent',count=12)

は動作する

ツイート取得したあとはテキストから数字のみ取り出せればいいので

これを先にやる

for tweet in tweepy.Cursor(api.search_tweets, q='GDP(YoY)').items(10):

    print(tweet.text)

としたら10件取得できた

結果が

⠀#EU 1Q 2022

#GDP = 5,4% YoY (5,1% previous)

#GDP = 0,6% QoQ (0,3% previous)

Grammar check: Eurozone GDP in Q1 better than estimated, QoQ +0,6% (estimated +0,3%) vs 0,3% in Q4 2021, YoY +5,4%… https://t.co/T2QYk1MzMT

RT @PatelisAlex: Powering ahead.



Greek real GDP surges 7.0%yoy in Q1 (real, not nominal) https://t.co/pWQqFZB8bi

BNP inom EURO-området bättre än väntat.



European Gross Domestic Product (GDP) YoY 5.4% - https://t.co/R9Ra2BQVGK

Euro area GDP came in stronger than expected for Q1:

+5.4% YoY (est. 5.1%); .6% QoQ (est. .3%).



Output rose .5% Q… https://t.co/U2xUt4c083

RT @Financialjuice1: EUROZONE GDP REVISED YOY ACTUAL 5.4% (FORECAST 5.1%, PREVIOUS 5.1%) $MACRO

EUROZONE GDP REVISED YOY ACTUAL 5.4% (FORECAST 5.1%, PREVIOUS 5.1%) $MACRO


 European GDP Growth Rate YoY 3rd Est (Q1)



Actual: 5.4%


Expected: 5.1%

Previous: 4.7%



#EUR

Euro Zone Econ. Stats Released:

GDP (YoY) (Q1)

Actual:  5.4%

Expected: 5.1%

Prior: 5.1%

Better Than Expected


 GDP Growth Rate YoY 3rd Est (Q1)

Actual: 5.4%

Expected: 5.1%

Previous: 4.7%

https://t.co/p0AAzoJmBh

なので

ほぼ取得したい内容がある

あとはここから数値のみ取り出して比較できるようにすr

https://docs.tweepy.org/en/stable/client.html#tweepy.Client.search_recent_tweets
のリファレンスを見た感じだと

since_id を指定すればユーザ指定ができそう

なので bloomberg のid を調べる

34713362
がid 

あとはこれを指定してできるかどうか

screen_name だと

@business
なので

bloomberg = api.user_timeline(screen_name='@business')

# bloomberg

for tweet in bloomberg:

    print(tweet.text)

で表示できた

あとは取得したついーとから数字だけ取り出す


for tweet in tweepy.Cursor(api.search_tweets, q='"French oil and gas" from:@business').items(10):

    if (tweet.text[:2] == 'RT'): continue



    print(tweet.user.name)

    print(tweet.text)

    print('-----------------------------------------------')

としたら特定のアカウントで検索もできた

あとはここから数値の抜き取り

https://teratail.com/questions/266272

を参考に特定ユーザツイート検索ができた

marketnews = api.user_timeline(screen_name='@Financialjuice1')

# bloomberg

for tweet in marketnews:

    print(tweet.text)

で経済指標の最も早いニュースを英語で取得

marketnews =list(marketnews)

marketnews_data = []

for tweet in marketnews:

    marketnews_data.append(tweet.text)

   

print(marketnews_data[9])

で経済指標発表時のツイート取得

次にこのツイートの中身を数字だけにする

【Python】文字列から数字だけを取り出す方法

を参考に

Re.sub()

を使い

marketnews_data[3]

を数値だけにする

actual = re.sub(r"\D","",marketnews_data[3])

actual

だと

'025'

となるので

少数だけにしたい

以前、経済指標で数値以外を削除した方法を使う

分かりやすいpythonの正規表現の例

を参考に

actual = re.sub(r"[^0-9.-]","",marketnews_data[3])

actual

としたが

'.0.25.'

となる

とりあえずリストにすれば正規表現で抜き出しはできるので
あとは処理を調べる

actual = re.sub(r"[^0-9.-]|.$","",marketnews_data[3])

というように

| で条件を追加して

.$ というように末尾が. であるものを削除

ただし最初の . が消せない

また

HONG KONG CPI MOM NSA ACTUAL -0.20% (FORECAST -, PREVIOUS -0.20%) $MACRO

を削除してみると

actual2 = re.sub(r"[^0-9.-]|.$","",marketnews_data[2])

actual2

の結果は

'-0.20--0.20'

となるので

少数を条件式に組み込んだ方がいいかもしれない

"ECB'S DE GUINDOS: EURO-ZONE INFLATION TO STAY ABOVE 8% IN COMING MONTHS."

を処理すると
-8 になる

数値とマッチする正規表現

を参考に小数点と不等号を含む数値のみ抽出する正規表現にする

しかし

[+-]?(?:\d*\.)?\d+(?:(?<!(\.\d+))\.\d*)?

だとエラ〜になる

actual2 = re.sub(r"[^\d.]|.$","",marketnews_data[2])

print(actual2)

にしたら

となった

Python の正規表現で . (ドット) を含む数値のみを抽出したい

を参考にした

ただしこれだと複数の数値を1つにしてしまうので

区切る必要がある

findall()

で試したが

actual2 = re.findall(r"\d+",marketnews_data[1])

print(actual2)

とすると

['53', '1', '52', '4', '53', '1']

となって小数点で区切ってしまう

文字列から浮動小数点数を抽出する方法

を参考に

actual2 = re.findall("\d+\.\d+",marketnews_data[1])

print(actual2[0])

としたら

53.1

が抽出できた

actual2 = re.findall("[-+]?\d*\.\d+|\d+",marketnews_data[1])

print(actual2)

とすることでマイナスの数値にも対応できた

しかし文字列なので

print(actual2+1)

としたらエラ〜となった

変換すればできそうだが小数点なので
Float になる

Vix を抽出した時
flag_vix の値は少数で比較もできた

flag_vix +1

としても演算し

+1 されている

【Python】型を確認・判定する(type関数、isinstance関数)

を参考に

type(flag_vix)

でデータ型を確認したら

numpy.float64

となった

なので float へ変換してみる

[解決!Python]文字列と数値を変換するには(int/float/str/bin/oct/hex関数)

を参考に

float(actual2)

としたがエラ〜

type(actual2)

で調べたら list だった

Python でリストを Float に変換する

を参考に

リスト内のアイテムを Python で numpy.float_() 関数を使用して Float に変換する

import numpy as np
actual2_float = np.float_(actual2)

print(actual2_float+1)

とすれば計算ができるようになった

 

Mac Jupyter notebook メモ

Mac Jupyter notebook メモ

Cmd + ←
で行頭へ移動後

Shift + cmd + →
で行を選択できる

単語ごとの選択は
Option + ←

単語の削除は
Option + backspace

これで
効率的にコードを書ける

[/python]
search_indicate[‘actual’] =search_indicate[‘actual’].str.replace(r”\D”, “”,regex=True)

search_indicate[‘forecast’] =search_indicate[‘forecast’].str.replace(r”\D”, “”,regex=True)

search_indicate[‘previous’] =search_indicate[‘previous’].str.replace(r”\D”, “”,regex=True)

search_indicate
[/python]

これで変換して

date2 =[]

for i in search_indicate['date']:

    new_date = datetime.datetime.strptime(i,"%d/%m/%Y").strftime("%Y-%m-%d")

    date2.append(new_date)

search_indicate['date']=search_indicate['date'].str.replace('/','-')

search_indicate['date'] = date2

search_indicate.fillna(0)

で日付を修正

あとは

actual =(

    alt.Chart(search_indicate)

    .mark_line(opacity=0.8,clip=True)

    .encode(

        x="date:T",

        y=alt.Y("actual:Q",stack=None)

    )

)



forecast =(

    alt.Chart(search_indicate)

    .mark_line(opacity=0.8,clip=True,color='red')

    .encode(

        x="date:T",

        y=alt.Y("forecast:Q",stack=None),      

    )

)



previous =(

    alt.Chart(search_indicate)

    .mark_line(opacity=0.8,clip=True,color='green')

    .encode(

        x="date:T",

        y=alt.Y("previous:Q",stack=None),      

    )

)

alt.layer(actual,forecast,previous).resolve_scale(

    y = 'independent'

)

それぞれのチャートを表示

次に
indicatorの ( 以降を
削除する

まずは

# s = 'abcxyz-xyz('



# print(my_removesuffix(s, '-xyz'))

txt ="ANZ Job Advertisements (MoM)"

print(txt)

として ( 以降を削除

Pythonで文字列の先頭と末尾から空白や文字列を削除する:strip()

を参考にしたが
strip ではできなかった

Replace と正規表現で行う

0回以上の繰り返し
*

任意の英数字は
[a-zA-Z0-9_]

\w

txt.replace("(","")

だとできた

エスケープは不要

year_economic_data2['event']=year_economic_data2['event'].replace("\([a-zA-Z0-9_]+\)","",regex=True)

year_economic_data2

とすることで解決

あとは経済指標カレンダーも同様に処理

# dealing_calender['event']= dealing_calender['event'].str.replace('(','\(').str.replace(')','\)')

dealing_calender['event']=dealing_calender['event'].replace("\([a-zA-Z0-9_]+\)","",regex=True)

とすることで解決

ただし

search_indicate['actual'] =search_indicate['actual'].str.replace(r"\D", "",regex=True)

search_indicate['forecast'] =search_indicate['forecast'].str.replace(r"\D", "",regex=True)

search_indicate['previous'] =search_indicate['previous'].str.replace(r"\D", "",regex=True)

search_indicate

だと

小数点のものまで書き換えてしまい
マイナス、小数点まで削除してしまう

不等号などはそのままにして
%
英数字のみ
削除すればいけるはず

Python: 正規表現ライブラリを使って、グループ化による置換

を参考に

import re

print(re.sub(r'([A-Z][a-z]?)(\d{1,3})', r"\\Nuc{\1}{\2}{}", "He4"))

# \Nuc{He}{4}{}

print(re.sub(r'([A-Z][a-z]?)(\d{1,3})L', r"\\Nuc{\1}{\2}{\\Lambda}", "He4L"))

# \Nuc{He}{4}{\Lambda}

みたいに

search_indicate['actual'] =search_indicate['actual'].str.replace(r"[a-zA-Z%]", "",regex=True)

search_indicate['forecast'] =search_indicate['forecast'].str.replace(r"[a-zA-Z%]", "",regex=True)

search_indicate['previous'] =search_indicate['previous'].str.replace(r"[a-zA-Z%]", "",regex=True)

search_indicate

とすればできた

とりあえず問題はあるけど
経済指標の取得後の処理はできてきた

次はIMM ポジションの取得

https://www.gaitame.com/market/imm/imm_currency.xls

からダウンロードしたいが

Mac だとそのままだとできないらしい

と思ったが Jupiter notebook からだとファイルを開けないみたい

Finder からだと普通にひらけた

Wgetは Mac にはないけど
Curl で代用できる

curl コマンド 使い方メモ

を参考に

-O オプションを付けることでファイル取得と保存ができる

!curl  "https://www.gaitame.com/market/imm/imm_currency.xls" -O

これで取得はコマンドでできるけど
Excel ファイル読み込みでエラー

No module xlrd

のエラーが出たので

【Python エラー】No module xlrd の対処法。権限がなくてxlrdモジュールをインストールできないとき

を参考に

!pip3 install xlrd

でインストール

あと excel の操作もできるように

!pip3 install openpyxl

で追加

あとは notebook を再起動すると
普通にExcelファイルの取り扱いできた

とりあえず
データ取得関連はほぼできた

経済指標の取得その2

経済指標の取得その2

次にpandas のカラムの結合をして新しいカラムを作成してみる

これをdate と time を合わせて
Datetime 形式にして
Datetime インデックスを作成する

https://note.com/kohaku935/n/n18205dcc60fa

を参考にまずは+で結合し

Datetime を追加する

economic_data['Datetime']=economic_data['date']+economic_data['time'].fillna('')

economic_data

で欠損値は削除できたが

Time がAllay のものだとこれになってしまう

あとくっついてるので変換できない

economic_data['Datetime']=economic_data['date']+" "+economic_data['time'].fillna('')

として余白を入れる

https://note.nkmk.me/python-pandas-datetime-timestamp/
を使えばdatetime へ変換できるはず

その前に一度フォーマットを変えないと日付が月扱いになっている

economic_data['Days']=economic_data['date']

economic_data['Days']=pd.to_datetime(economic_data['Days'])

economic_data

で確認したら

これだとだめ

date2 =[]

for i in economic_data['date']:

    new_date = datetime.datetime.strptime(i,"%d/%m/%Y").strftime("%Y-%m-%d")

    date2.append(new_date)

economic_data['date']=economic_data['date'].str.replace('/','-')

economic_data['date'] = date2

economic_data.fillna(0)

年月日へ変換

pd.to_datetime(economic_data['Days'], format="%Y%m%d %H:%M")

とすればエラーにならない

このため

あとは時間の部分で

時刻でないものを除外するようにする

正規表現で検索

economic_data['time'].tail(10).str.contains('[a-zA-Z]')

というようにすれば

アルファベットになっているものだけになる

なので

economic_data['time'].tail(10).str.contains('[1-9]')

とすれば時間は数値なので

これで調べることができる

あとはif などで条件をつけて

数値出ない場合には

Datetime には NA を入れるようにする

まずカレンダーで重要なものだけ表示してみて

これでも変わらないのなら、この措置をとる

importanceを hight にすればいけるはず

economic_data[economic_data['importance']=='high']

で前に出しているので

これでできたが日付関連が昨日と今日だと微妙におかしい

今日と明日で試してみる

Datetime index が設定できるようにすること

そして

Event の文字のエスケープをしておいて検索ができるようにしておくこと

date2 =[]

for i in dealing_calender['date']:

    new_date = datetime.datetime.strptime(i,"%d/%m/%Y").strftime("%Y-%m-%d")

    date2.append(new_date)

dealing_calender['date']=dealing_calender['date'].str.replace('/','-')

dealing_calender['date'] = date2

dealing_calender.fillna(0)

でdatetime にして

dealing_calender['DateTime']=dealing_calender['date']+" "+dealing_calender['time'].fillna('')

dealing_calender

Datetime index のためのカラムを作成

と思ったが

【Pandas】DataFrameの文字列日付データを比較して、抽出したりする
にあるようにカラムをdatetime にすれば抽出できそう

def convert_date(x):

    date = datetime.datetime.strptime(x,"%Y-%m-%d %H:%M:%S")

    return date

で変換するメソッドを用意

しかし元のデータは秒までないためエラ〜になるので

def convert_date(x):

    date = datetime.datetime.strptime(x,"%Y-%m-%d %H:%M")

    return date

とする

dealing_calender['DateTime'] = dealing_calender['DateTime'].apply(convert_date)

で変換できた

pandas.DataFrame, Seriesを時系列データとして処理
を参考に
Datetime index を設定する

今回は
既存データの列をDatetimeIndexとして指定する方法

dealing_calender.dtypes

で確認すると

id                    object

date                  object

time                  object

zone                  object

currency              object

importance            object

event                 object

actual                object

forecast              object

previous              object

DateTime      datetime64[ns]

dtype: object

となり

すでにdatetime には変換済

set_index()メソッドでdatetime64型の列をインデックスに指定する

dealing_calender.set_index('DateTime',inplace=True)

これでできた

あとは時間指定でデータ取り出し

DatetimeIndexがわからんので逆引きでまとめとくの巻
を参考に
時間を指定して取り出す

文字列で時間や日時を指定して行を取り出す, loc
でいけそう

しかしやりたいのは
指定した時間でのevent の取り出し

なので
indexとcolumnを指定してvalueを取り出す

dealing_calender.loc['2022-04-19 05:00']['event']

とすれば

経済指標は英語で

Economic indicators
なので

indicator = dealing_calender.loc['2022-04-19 05:00']['event']

print(indicator)

これで

RBNZ Gov Orr Speaks

となった

次に
この変数で経済指標のグラフの最初の検索処理ができるか試す

過去ログで見ると

economic_data = investpy.economic_calendar(time_zone=None, time_filter='time_only', countries=['japan', 'united states'], from_date='01/02/2021', to_date='28/03/2021')

economic_data.tail(5)

となっている

つまり最初の時点で国などを指定している
これだと日本とアメリカのみになっているので
これを変える必要がある

対象を全ての国にするか
メジャーカレンシーのみに絞る

https://investpy.readthedocs.io/_api/news.html

のリファレンスを見ると

investpy.news.economic_calendar(time_zone=None, time_filter='time_only', countries=None, importances=None, categories=None, from_date=None, to_date=None)

となっている

しかし期間を指定しないとエラ〜になる

economic_data2 = investpy.economic_calendar(time_zone=None, time_filter='time_only', countries=None, from_date='01/01/2021', to_date='31/01/2021')

economic_data2

というように国コードだけ指定外して
期間を指定したらできた

せっかくなので期間を
年始から今日までとしてみる
と思ったけど年間のデータから算出した方が良さそう
そもそも年始にトレードする時
修正が必要になってしまう

[Python]昨日や明日、月末などの日付を取得したい
を参考に

# 1年前# => 2019-04-02

one_year_ago = today + relativedelta(years=-1)

でいけるはず

処理が遅いため

economic_data2 = investpy.economic_calendar(time_zone=None, time_filter='time_only', countries=None, from_date='01/01/2022', to_date=deel_today)

economic_data2

としてみた

表示されるまで時間がかかる

ネット速度の問題か
それともマシンスペックかはわからない

つまり年ごとで取得するなら
別の時間枠でやらないと間に合わない

とりあえず直近1ヶ月で指定する

economic_data2 = investpy.economic_calendar(time_zone=None, time_filter='time_only', countries=None, from_date=deal_one_month_ago, to_date=deel_today)

economic_data2

でいける

この中から

#重要指標で actual が NULL 以外で importance = high のものを表示

economic_data2[~(economic_data2['actual'].isnull()) & (economic_data2['importance']=='high')]

以前に経済指標グラフを出す時には
取得期間を半年にした

economic_data = investpy.news.economic_calendar(time_zone=None, time_filter='time_only', countries=['japan', 'united states'],importances=None,categories=None,from_date='01/01/2021', to_date='11/06/2021')

で1年にしたら止まった

カレンシーを絞らないとできないと思う
カレンシーの絞り込みはなく国の指定になる

取り扱っている通貨で出すと
ドル united states
ユーロ germany
ポンド united kingdom
豪ドル australia
NZドル new zealand
カナダドル canada
スイスフラン switzerland

これだけに絞る

# economic_data2 = investpy.economic_calendar(time_zone=None, time_filter='time_only', countries=None, from_date='01/01/2022', to_date=deel_today)

# economic_data2

year_economic_data2 = investpy.economic_calendar(time_zone=None, time_filter='time_only', countries=[‘united states','germany','united kingdom','australia','new zealand','canada','switzerland'], from_date=deal_one_month_ago, to_date=deel_today)

year_economic_data2

これで絞り込み

さらに

# economic_data2 = investpy.economic_calendar(time_zone=None, time_filter='time_only', countries=None, from_date='01/01/2022', to_date=deel_today)

# economic_data2

year_economic_data2 = investpy.economic_calendar(time_zone=None, time_filter='time_only', countries=[‘united states','germany','united kingdom','australia','new zealand','canada','switzerland'], from_date=deal_one_year_ago, to_date=deel_today)

year_economic_data2

で年間にしたらできた

あとはグラフの時と同じ処理をやってみる
探す時に
経済指標の検索ワードを
カレンダーの結果で調べてみる

もしエラーならエスケープ後に再度挑戦する

まずはISMを検索

ISM =year_economic_data2[year_economic_data2['event'].str.contains('ISM Non-Manufacturing PMI')]

ISM

で1年間のISMを表示できた

チャートにするには
そのままのsate time ではできないので

date2 =[]

for i in ISM['date']:

    new_date = datetime.datetime.strptime(i,"%d/%m/%Y").strftime("%Y-%m-%d")

    date2.append(new_date)

ISM['date']=ISM['date'].str.replace('/','-')

ISM['date'] = date2

ISM.fillna(0)

と変換する

あとはチャート部分

actual =(

    alt.Chart(ISM)

    .mark_line(opacity=0.8,clip=True)

    .encode(

        x="date:T",

        y=alt.Y("actual:Q",stack=None)

    )

)



forecast =(

    alt.Chart(ISM)

    .mark_line(opacity=0.8,clip=True,color='red')

    .encode(

        x="date:T",

        y=alt.Y("forecast:Q",stack=None),      

    )

)



previous =(

    alt.Chart(ISM)

    .mark_line(opacity=0.8,clip=True,color='green')

    .encode(

        x="date:T",

        y=alt.Y("previous:Q",stack=None),      

    )

)

alt.layer(actual,forecast,previous).resolve_scale(

    y = 'independent'

)

で表示できる

なおaltair を使っているので

import altair as alt

が必要

経済指標の取得その1

経済指標の取得

行う処理は

カレンダーの予想時刻と
現在時刻

つまり date time が一緒になったら
Event で検索

とりあえず event 内容をリストに入れる

あと
Date time も格納する

Datetime に関しては
文字列から datetime に変換する

まずはリストにする

value.tolist()

でリスト変換可能

events = economic_data["event"]

economic_event = events.values.tolist()

#events=events[0]

print(economic_event[0])

economic_events="Chinese Industrial profit YTD  (Feb)"

test_event = economic_event[3]

print(test_event)

print(economic_events)

economic_event

これで

economic_event

へリストで格納できる

これを

economic_data[economic_data['event'].str.contains(economic_event[4])]

というようにすれば検索できるが

Chinese Industrial profit YTD  (Feb)

Investing.com GBP/USD Index

Chinese Industrial profit YTD  (Feb)

Out[78]:

['Chinese Industrial profit YTD  (Feb)',

'Finnish Consumer Confidence  (Mar)',

'Finnish Industrial Confidence  (Mar)',

'Investing.com GBP/USD Index',

'Investing.com Gold Index',

'Investing.com S&P 500 Index',

'Investing.com USD/CAD Index',

'Investing.com USD/CHF Index',

'Investing.com AUD/USD Index',

'Investing.com USD/JPY Index',

'Investing.com NZD/USD Index',

'Investing.com EUR/USD Index',

'Trade Balance  (Feb)',

'Credit Indicator (YoY)  (Feb)',

'Core Retail Sales (MoM)  (Feb)',

'Lithuania Retail Sales (MoM)',

'Lithuania Retail Sales (YoY)',

'Gross Wages (YoY)  (Jan)',

'Exports (MoM)  (Feb)',

'Imports (MoM)  (Feb)',

'Trade Balance',

'Irish Retail Sales (MoM)  (Feb)',

'Irish Retail Sales (YoY)  (Feb)',

'BoE Gov Bailey Speaks',

'Quarterly Unemployment Rate',

'M3 Money Supply (YoY)  (Dec)',

'Private Sector Loans (YoY)  (Dec)',

'BCB Focus Market Readout',

'Greek Credit Expansion (YoY)',

'Trade Balance  (Feb)',

'Trade Balance (USD)  (Feb)',

'GDP (YoY)',

'GDP Quarterly',

'Goods Trade Balance  (Feb)',

'Retail Inventories Ex Auto  (Feb)',

'Wholesale Inventories (MoM)',

'Current Account (USD)  (Feb)',

'Foreign direct investment (USD)  (Feb)',

'French 12-Month BTF Auction',

'French 3-Month BTF Auction',

'French 6-Month BTF Auction',

'Dallas Fed Mfg Business Index  (Mar)']

の中で

Chinese Industrial profit YTD  (Feb)

というように
(Feb)
があるとエラーになる

他の指標も試したけど
()があるものは全てエラーになる

この場合エスケープさせるか
(以降は削除するしかない

Macのキーボードの「Option」と
右上にある「¥マーク」を同時に押しすると
入力ソースが英数であろうと、
ひらがなであろうと
半角のバックスラッシュ(「\」)が入力される

Option + ¥

でバックスラッシュの\\ 2つで
エスケープできるので

economic_data[economic_data['event'].str.contains("Exports \\(MoM\\) ")]

としたらエラーがなくなった

つまりリストの中で()のある部分をエスケープしないとだめ

これは
Replace でできるので

economic_event.replace('(','\\(')

としたけど

すでにリストにしてしまうとだめ

events = economic_data["event"].str.replace('(','\(').str.replace(')','\)')

events

とすれば

/var/folders/db/tkl5w9dd3kn3h53ctyl4s6180000gn/T/ipykernel_8436/2811222662.py:4: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will *not* be treated as literal strings when regex=True.

  events = economic_data["event"].str.replace('(','\(').str.replace(')','\)')

とエラーは出るけど変換はできる

あとは

economic_event = events.values.tolist()

#events=events[0]

print(economic_event[0])

economic_events="Chinese Industrial profit YTD  (Feb)"

test_event = economic_event[3]

print(test_event)

print(economic_events)

print(economic_event)

でリストにできるので

economic_data[economic_data['event'].str.contains(economic_event[4])]

とすれば検索条件に当てはめることも可能