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?

📈そろそろ来るかも?株&投資信託の“兆し”を分析して自動ポストする仕組みを作った話 - その10(投稿編)

1
Posted at

1.はじめに

どうも、趣味でデータ分析している猫背なエンジニアです。
今回は、前回に引き続き兆しシリーズのロジックについて考えたので記録していきます。

2. 投稿器

■ 概要
以下のような画像のスクリーニング1号機を作り内部ロジックで様々なロジックを入れてきましたが、今回はとりあえず形になってきたので「投稿器」を入れてみようと思います。

■ 機能仕様・コーディング
私の記事を定期的に見ていただいている方だと、Xに投稿するという行為自体は今までもやったことあるだろという感じではあります。
ですが、今回の投稿ロジックとしては数ある銘柄の中から最終的に抽出した銘柄を価格が安い順にソートして投稿するというロジックとしています。

■ コーディング
以下のように株値が安い順でソートし、投稿するロジックを実装しました。
※事前にpngの名称には値段を付与しています。

投稿器
import os
from dotenv import load_dotenv
import tweepy
import datetime
import re

def post_tweet(total_count,KK_count):
    # .env ファイルを読み込む
    load_dotenv()
    # Twitter Deverloper Portalで取得
    consumer_key = os.getenv("CONSUMER_KEY")
    consumer_secret =  os.getenv("CONSUMER_KEY_SECRET")
    bearer_token = os.getenv("BEARER_TOKEN")
    access_token = os.getenv("ACCESS_TOKEN")
    access_token_secret = os.getenv("ACCESS_TOKEN_SECRET")
    # None がある場合、エラーを出して処理を中断
    if None in (consumer_key, consumer_secret, access_token, access_token_secret):
        raise ValueError("環境変数が正しく設定されていません。'.env' ファイルを確認してください。")

    # Client (テキスト投稿用)
    client = tweepy.Client(bearer_token=bearer_token,
                            consumer_key=consumer_key,
                            consumer_secret=consumer_secret,
                            access_token=access_token,
                            access_token_secret=access_token_secret)
    # 認証処理
    auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret)
    api = tweepy.API(auth)

    # 画像選定ロジック
    image_dir = r"D:\01.開発\05KK_FinancialEater\result"
    pattern = re.compile(r'_(\d+)_スクリーニング通過結果\.png$')  # 末尾の価格を取得

    images_with_price = []

    for file in os.listdir(image_dir):
        if not file.endswith(".png"):
            continue

        match = pattern.search(file)
        if match:
            price = int(match.group(1))
            images_with_price.append((price, os.path.join(image_dir, file)))

    # 価格が安い順にソート
    images_with_price.sort(key=lambda x: x[0])

    # 最大4枚取得
    selected_images = [path for _, path in images_with_price[:4]]

    # 画像が0枚ならスキップ
    media_ids = []
    if selected_images:
        media_ids = [
            api.media_upload(image).media_id_string
            for image in selected_images
        ]

    # ツイート作成
    dt_now = datetime.datetime.now()
    date_str = dt_now.strftime('%Y年%m月%d日')
    tweet_text = (
        f"Post Day : {date_str}\n"
        f"全銘柄数:{total_count} | 最終通過数: {KK_count}\n"
        f"1株当たりの価格が安い順に添付しています。\n\n"
        f"※ Trial Operation Now\n"
        f"#Python #KK_FinancialEater"
    )

    tweet_notKK_text = (
        f"Post Day : {date_str}\n"
        f"全銘柄数:{total_count} | 最終通過数: {KK_count}\n"
        f"最適な投資先が見つかりませんでした\n\n"
        f"※ Trial Operation Now\n"
        f"#Python #KK_FinancialEater"
    )

    if media_ids:
        client.create_tweet(text=tweet_text, media_ids=media_ids)
    else:
        client.create_tweet(text=tweet_notKK_text)
    print("Post Complete")

■ 出力

4.おわりに

今回は兆しシリーズのKK-FinancialEaterに投稿器を付与しました。やっと出力ができるまでにちゃんとした形ができました。今後も改良してさらに安く高利回りのものを狙えるロジックにしていきたいと思います。

📈 KK-FinancialEater

■ 原点(KK-Adam)
■ その1:プロトタイプ編
■ その2:収集器強化編
■ その3-番外編:グランビルの法則 - 設計編
■ その3:グランビルの法則
■ その4:移動平均乖離率
■ その5:ボリンジャーバンド
■ その6:RSI
■ その7:Stochastic
■ その8:Volume ratio
■ その9:DMI
■ その10 -番外編:ロジック変更

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?