Contents

finplot code example

0
Contents

Here’s a code example using the finplot library in Python to create a simple financial plot

import finplot as fplt
import pandas as pd

# Sample data
data = {
    'date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05'],
    'price': [100, 105, 98, 110, 102]
}

# Create a pandas DataFrame
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])

# Create a finplot plot
fplt.candlestick_ochl(df[['date', 'price']])

# Add a moving average
fplt.plot(df['date'], df['price'].rolling(window=3).mean(), color='orange')

# Set plot title and axis labels
fplt.title('Stock Price')
fplt.xlabel('Date')
fplt.ylabel('Price')

# Show the plot
fplt.show()

In this example, we first import the finplot library as fplt and the pandas library as pd. We then create sample data as a dictionary with dates and corresponding prices.

Next, we convert the data dictionary into a pandas DataFrame, ensuring that the ‘date’ column is in datetime format using pd.to_datetime().

We create a finplot plot using the candlestick_ochl() function, which expects a DataFrame with columns ‘date’, ‘open’, ‘close’, ‘high’, and ’low’. Since we only have a closing price (‘price’), we pass the DataFrame subset df[['date', 'price']] to the function.

To add a moving average line, we use the plot() function and pass the ‘date’ column and the rolling mean of the ‘price’ column, specifying a window of 3 days.

We set the plot title, x-axis label, and y-axis label using fplt.title(), fplt.xlabel(), and fplt.ylabel(), respectively.

Finally, we display the plot using fplt.show().

Make sure to install the finplot library using pip before running this code:

pip install finplot

This example demonstrates a basic usage of finplot to create a financial plot with candlestick data and a moving average. You can explore more advanced features and customization options of the library by referring to the finplot documentation and examples.

About finplot

finplot - A performant python library with a clean api to help you with your backtesting..