To write live animations in Python with Matplotlib and mpl-finance to simulate trading market K charts and volumes, you can follow these steps:

  1. Import the necessary libraries:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import mpl_finance as mpf
  1. Define the figure and axis objects:
fig = plt.figure()
ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)
ax2 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1, sharex=ax1)

Here, we create a figure with a grid of 6 rows and 1 column, with the first 5 rows for the K chart and the last row for the volume chart.

  1. Define the function to update the chart with new data:
def animate(i):
    # Get the latest data
    # Update the K chart
    mpf.candlestick_ohlc(ax1, data, width=0.4, colorup='g', colordown='r')
    # Update the volume chart
    ax2.bar(data[:,0], data[:,5])
  1. Create the animation object:
ani = animation.FuncAnimation(fig, animate, interval=1000)
  1. Show the chart:
plt.show()

Here is the complete code to simulate a trading market K chart with live data:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import mpl_finance as mpf
import pandas as pd
import numpy as np

# Generate some random data
data = np.random.rand(20,6)
data[:,0] = np.arange(20)

# Define the figure and axis objects
fig = plt.figure()
ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)
ax2 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1, sharex=ax1)

# Define the function to update the chart with new data
def animate(i):
    # Get the latest data
    data[-1,:] = np.random.rand(6)
    data[:,0] = np.arange(len(data))
    # Update the K chart
    mpf.candlestick_ohlc(ax1, data, width=0.4, colorup='g', colordown='r')
    # Update the volume chart
    ax2.bar(data[:,0], data[:,5])

# Create the animation object
ani = animation.FuncAnimation(fig, animate, interval=1000)

# Show the chart
plt.show()

This code will generate a K chart with 20 random data points, and then update it with new random data every second. The volume chart will also be updated accordingly. You can modify the data source to use real-time data from a trading market API or database.

Help to write live animations in python with Matplotlib and mpl-finance to simulate trading market K charts and volumes

原文地址: https://www.cveoy.top/t/topic/bFAx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录