I made a program in Python that reads CSV data of FX and creates a large amount of chart images

About this article

To make FX predictions in deep learning (CNN) From CSV data (date and time, opening price, high price, low price, closing price are described) I would like to generate a large number of chart images.

Deliverables

Create the following chart image from CSV. image.png

About CSV files

The CSV file is an hourly chart of USDJPY. (January 2007-September 2020) If you don't have 1 hour CSV data, please refer to this article . The contents of CSV are as follows. There are more than 80,000 lines. image.png

code

The code is below.

import matplotlib.pylab as plt
import pandas as pd
import numpy as np

def make_sma(parab, arr=None):
    """
Function description: Adds an average moving line to the array received as an argument.
    parab:period
    arr:Array consisting of date and time, open price, high price, low price, close price
    """
    row = arr.shape[1] #Get the number of columns in the array
    arr = np.c_[arr, np.zeros((len(arr),1))] #Add column
    for i in range(parab, len(arr)):
        tmp = arr[i-parab+1:i+1,4].astype(np.float) #Enter the number within the period
        arr[i,row] = np.mean(tmp) #Enter the value of the moving average

    return arr

def dataframe_to_img(chart_range, img_name, df=None):
    """
Function description: Convert DataFrame to image and save.
    chart_range:DataFrame range
    img_name:Image save destination
    df:DataFrame to draw
    """
    df = df[0:chart_range]

    plt.figure()
    df.plot(legend=None) #Delete legend
    plt.axis('off') #Border removal
    plt.tick_params(labelbottom=False,
                    labelleft=False,
                    bottom=False,
                    left=False) #Border removal
    plt.box(False) #Border removal
    plt.savefig(img_name,bbox_inches="tight") #Remove margins and save
    plt.close('all')


#Load csv into array
arr = np.loadtxt(r'CSV file', delimiter=",", skiprows=1, dtype='object') 

#Added technical indicators
arr = make_sma(parab=25, arr=arr)

#Convert to DataFrame
col_name = ['Date',"Open","High","Low","Close","SMA"]
df = pd.DataFrame(arr,columns=col_name)

#Convert to DataFrame and save the image
df = df[df!=0].dropna() #Delete line 0
df = df[['Close','SMA']] #Only the columns to draw on the graph
df = df.astype('float') #Convert to float

chart_range = 360

for i in range(20):
    try:
        img_name = str(i) + '.png' #Image save destination
        dataframe_to_img(chart_range, img_name, df=df[i:chart_range+i])
    except IndexError:
        pass

#DataFrame is also saved because it will be used as a correct label later.
df.to_csv(r'tarintest_labels.csv',encoding='utf_8_sig')

A description of the code. First, load the CSV with numpy.

Then, with ʻarr = make_sma (parab = 25, arr = arr) ` Add a moving average to arr. The period of the moving average is specified by parab. If you want to add long-term lines such as 75 and 200 instead of 25, You can add it by changing the value of parab and adding it.

After adding the technical indicators, With df = pd.DataFrame (arr, columns = col_name) Convert arr to DataFrame.

chart_range = 360 is the range of charts to display. This time it is a 1-hour CSV, so if it is 360, it will be displayed for 360 hours.

Finally, in the for statement, pass the DataFrame to the dataframe_to_img function and save it one by one. dataframe_to_img uses matplotlib. Borders etc. are deleted because they interfere with learning in deep learning.

After outputting the image, save the DataFrame as CSV. This is to use it as a correct label for deep learning.

Verification

Make sure the image is saved. image.png

This time it's just a simple moving average, It is also possible to display Bollinger Bands and Ichimoku Kinko Hyo.

If you find it helpful, please use LGTM. It will be encouraging of the update.

Recommended Posts

I made a program in Python that reads CSV data of FX and creates a large amount of chart images
I made a program in Python that changes the 1-minute data of FX to an arbitrary time frame (1 hour frame, etc.)
I made a program to collect images in tweets that I liked on twitter with Python
I made a payroll program in Python!
I made a program to check the size of a file in Python
I made a Caesar cryptographic program in Python.
I want to exe and distribute a program that resizes images Python3 + pyinstaller
I made a prime number generation program in Python
Full-width and half-width processing of CSV data in Python
I made a prime number generation program in Python 2
Get a large amount of Starbucks Twitter data with python and try data analysis Part 1
I made a program to convert images into ASCII art with Python and OpenCV
A program that summarizes the transaction history csv data of SBI SECURITIES stocks [Python3]
I made a Python program for Raspberry Pi that operates Omron's environmental sensor in the mode with data storage
I tried "a program that removes duplicate statements in Python"
[Python] Creating a GUI tool that automatically processes CSV of temperature rise data in Excel
A Python program that collects tweets containing specific keywords daily and saves them in csv
[Python3] I made a decorator that declares undefined functions and methods.
I made a program that solves the spot the difference in seconds
How to create a large amount of test data in MySQL? ??
[Python] A program that creates stairs with #
I made a web application in Python that converts Markdown to HTML
I made a Discord bot in Python that translates when it reacts
[IOS] I made a widget that displays Qiita trends in Pythonista3. [Python]
Code reading of faker, a library that generates test data in Python
[Python] I made a web scraping code that automatically acquires the news title and URL of Nikkei Inc.
A Python script that reads a SQL file, executes BigQuery and saves the csv
[Beginner] What happens if I write a program that runs in php in Python?
Publishing and using a program that automatically collects facial images of specified people
[Python] I made a LINE Bot that detects faces and performs mosaic processing.
I made a familiar function that can be used in statistics with Python
I made a module in C language to filter images loaded by Python
[Python] A program that calculates the number of updates of the highest and lowest records
In Python, I made a LINE Bot that sends pollen information from location information.
A program that sends a fixed amount of mail at a specified time by Python
A memo that I wrote a quicksort in Python
I wrote a class in Python3 and Java
A program that removes duplicate statements in Python
A well-prepared record of data analysis in Python
I made a tool in Python that right-clicks an Excel file and divides it into files for each sheet.
I made a Docker Image that reads RSS and automatically tweets regularly and released it.
[Python] A program that finds the shortest number of steps in a game that crosses clouds
I created a stacked bar graph with matplotlib in Python and added a data label
I compared the speed of the reference of the python in list and the reference of the dictionary comprehension made from the in list.
A note that runs an external program in Python and parses the resulting line
[Python / C] I made a device that wirelessly scrolls the screen of a PC remotely.
[Python] A program that counts the number of valleys
Receive dictionary data from a Python program in AppleScript
I made a VM that runs OpenCV for Python
A shell program that becomes aho in multiples of 3
[Python] A program that compares the positions of kangaroos.
A Python program that converts ical data into text
When writing to a csv file with python, a story that I made a mistake and did not meet the delivery date
Example of how to aggregate a large amount of time series data using Python at a reasonable speed in a small memory environment
I made a toolsver that spits out OS, Python, modules and tool versions to Markdown
A Python script that stores 15 years of MLB game data in MySQL in 10 minutes (Baseball Hack!)
[Python] A program to find the number of apples and oranges that can be harvested
A memo that reads data from dashDB with Python & Spark
I tried [scraping] fashion images and text sentences in Python.
A Python program in "A book that gently teaches difficult programming"
A general-purpose program that formats Linux command strings in python