matplotlib 中的烛台

Candlesticks in matplotlib

我正在尝试制作一个密码扫描器,但我有点吃力。现在的代码可以遍历 symbols.csv 中的不同硬币并打印所有硬币的图表。这些图包括收盘价、SMA 和布林带。现在我真的希望收盘价是烛台而不是一条线。我发现还有像 mpf 这样的其他地块来制作烛台。问题是我不知道如何让布林带与 mpf 图一起工作,我不知道如何让烛台与 matplotlib 一起工作。有人可以帮我在 matplotlib 中制作烛台或者在 mpf 图中制作布林线。

提前致谢!

The graph looks like this right now

import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib



with open('symbols.csv') as f:
    symbols = f.read().splitlines()
    for symbol in symbols:
        df = yf.download(symbol, start='2020-01-01')
        # df = yf.download(symbol, period = '22h', interval = '15m')
        print(df)



# df = yf.download('ADA-USD', start='2021-01-01')

        df['SMA'] = df.Close.rolling(window=20).mean()
        df['stddev'] = df.Close.rolling(window=20).std()
        df['Upper'] = df.SMA + 2* df.stddev
        df['Lower'] = df.SMA - 2* df.stddev
        df['Buy_Signal'] = np.where(df.Lower > df.Close, True, False)
        df['Sell_Signal'] = np.where(df.Upper < df.Close, True, False)

        buys = []
        sells = []
        open_pos = False

        for i in range(len(df)):
            if df.Lower[i] > df.Close[i]:
                if open_pos == False:
                    buys.append(i)
                    open_pos = True
            elif df.Upper[i] < df.Close[i]:
                if open_pos:
                    sells.append(i)
                    open_pos = False



        plt.figure(figsize=(12, 6))

        plt.scatter(df.iloc[buys].index, df.iloc[buys].Close, marker = '^', color ='g')
        plt.scatter(df.iloc[sells].index, df.iloc[sells].Close, marker = '^', color ='r')


        plt.plot(df[['Close', 'SMA', 'Upper', 'Lower']])
        plt.fill_between(df.index, df.Upper, df.Lower, color='grey', alpha=0.3)
        plt.legend(['Close', 'SMA', 'Upper', 'Lower'])
        plt.show()

        merged = pd.concat([df.iloc[buys].Close, df.iloc[sells].Close], axis=1)
        merged.columns = ['Buys', 'Sells']
        print(merged)
        totalprofit = merged.shift(-1).Sells - merged.Buys
        print(totalprofit)
        relprofits = (merged.shift(-1).Sells - merged.Buys) / merged.Buys
        print(relprofits.mean())

评论中的链接提供了丰富的examples。由于您想在 mpf 中绘制烛台、布林带和 SMA,我修改了前面示例中的附加绘图示例以满足您的需要。这些图表是根据从股票而非货币中获得的数据创建的。

import yfinance as yf
import pandas as pd
import mplfinance as mpf

df = yf.download("AAPL", start="2020-01-01")

df['SMA'] = df.Close.rolling(window=20).mean()
df['stddev'] = df.Close.rolling(window=20).std()
df['Upper'] = df.SMA + 2* df.stddev
df['Lower'] = df.SMA - 2* df.stddev
df['Buy_Signal'] = np.where(df.Lower > df.Close, True, False)
df['Sell_Signal'] = np.where(df.Upper < df.Close, True, False)

tcdf = df[['Lower','Upper','SMA']]
apd = mpf.make_addplot(tcdf)
mpf.plot(df, figratio=(8,4), type='candle', addplot=apd, volume=False, style='yahoo')