How to add H4 tag to the_content filter (after content)?

Try this instead :

   //Related stock photo function
   function custom_content_after_post($content){
    if (get_post_type( get_the_ID() ) == 'portfolio') {

    //Query for the the related posts - portfolio custom post type
    $loop = new WP_Query( array('post_type' => 'portfolio', 'posts_per_page' => 5, 'orderby' => 'rand'));
    $sptitle="<h4>Related Stock Photos</h4>";

    while ( $loop->have_posts() ) {
        $loop->the_post();

        $div  = '<div style="margin:25px 10px 0px 10px;">';
        $div .= '<ul style="list-style-type:none;">';
        $div .= '<li style="display:inline;float:left;">';              
        //Display post thumbnail assigned to it.
        $div .= '<div style="margin:25px 10px 0px 10px;">';
        $div .= '<a href="' .get_permalink(). '" >' .get_the_post_thumbnail($page->ID, 'thumbnail'). '</a>';
        $div .= '<p><strong><a href="' .get_permalink(). '" >' . get_the_title() . '</a></strong></p>';  
        $div .= '</div>';               
        $div .= '</li>';
        $div .= '</ul>';
        $div .= '</div>';

    }

 }

 return $content .$sptitle .$div;
}

add_filter( 'the_content', 'custom_content_after_post' );